repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are using python 3.10 or 3.11 for compatibility of the required packages %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install qiskit-transpiler-service %pip install graphviz %pip install circuit-knitting-toolbox %pip install qiskit-serverless -U %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U ### Save API Token, if needed %set_env QXToken=c5a303670922a83ac5699dc2fea334193919a9e2fe6943debde1ac52815df5e39c6a137e05136088f3a7715e8d6dbd10097baf193df1fa22206a85931166946f # Make sure there is no space between the equal sign # and the beginning of your token # qc-grader should be 0.18.11 (or higher) import qc_grader qc_grader.__version__ # Imports import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.visualization import plot_gate_map from qiskit.quantum_info import SparsePauliOp from qiskit_aer import AerSimulator from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2 as Sampler from circuit_knitting.cutting import generate_cutting_experiments, cut_gates # Setup the grader from qc_grader.challenges.iqc_2024 import grade_lab3_ckt_ex1, grade_lab3_ckt_ex2 # create a bell pair bell_state = QuantumCircuit(2) bell_state.h(0) bell_state.cx(0,1) bell_state.draw("mpl") ## If this is your first time accessing the backend ## remove # and fill your API key, and run the code #service = QiskitRuntimeService( # channel='ibm_quantum', # instance='ibm-q/open/main', # token='<IBM Quantum API key>' #) service = QiskitRuntimeService(channel="ibm_quantum") # Specify a system to use for transpilation, DO NOT change backend = service.backend("ibm_kyoto") layout=[122, 126] qubit_color = [] for i in range(127): if i in layout: qubit_color.append("#ff0066") else: qubit_color.append("#6600cc") plot_gate_map(backend, qubit_color=qubit_color, qubit_size=60, font_size=25, figsize=(8,8)) # transpile the circuit pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0) isa_qc = pm.run(bell_state) # original circuit depth isa_qc_depth = isa_qc.depth() print(f"Transpiled circuit depth: ", isa_qc_depth) isa_qc.draw("mpl", scale=0.6, idle_wires=False, fold=False) # Find the indices of the distant gates cut_indices = [ i for i, instruction in enumerate(bell_state.data) if {bell_state.find_bit(q)[0] for q in instruction.qubits} == {0, 1} ] # Decompose distant CNOTs into TwoQubitQPDGate instances qpd_circuit, bases = cut_gates(bell_state, cut_indices) qpd_circuit.draw("mpl", scale=0.6) observable = SparsePauliOp(["ZI"]) # Generate the sub-experiments and sampling coefficients sub_experiments, coefficients = generate_cutting_experiments( circuits=qpd_circuit, observables=observable.paulis, num_samples=np.inf ) # Transpile the circuit pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0) isa_qpd_circuit = pm.run(sub_experiments[5]) # depth using circuit cutting isa_qpd_depth = isa_qpd_circuit.depth() print(f"Original circuit depth after transpile: ", isa_qc_depth) print(f"QPD sub-experiment depth after transpile: ", isa_qpd_depth) print(f"Number of sub-experiments:", len(sub_experiments)) isa_qpd_circuit.draw("mpl", scale=0.6, idle_wires=False, fold=False) x = np.array([c.depth() for c in pm.run(sub_experiments)]) print(x) toffoli_layout = [122, 124, 126] toffoli = QuantumCircuit(3) toffoli.ccx(0, 1, 2) toffoli.draw("mpl") layout=[122,124, 126] qubit_color = [] for i in range(127): if i in layout: qubit_color.append("#ff0066") else: qubit_color.append("#6600cc") plot_gate_map(backend, qubit_color=qubit_color, qubit_size=60, font_size=25, figsize=(8,8)) # To know the original circuit depth ### Write your code below here ### # Transpile the circuit pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0) isa_qc = pm.run(toffoli) # Calculate original circuit depth isa_toffoli_depth = isa_qc.depth() ### Don't change any code past this line ### print(f"Transpiled circuit depth: ", isa_toffoli_depth) isa_qc.draw("mpl", scale=0.6, idle_wires=False, fold=False) # To know the depth using circuit cutting # Decompose the toffoli circuit toffoli_ = toffoli.decompose() ### Write your code below here ### # Find the indices of the distant gates gates_connecting_to_cut = {0,2} # Hint: Expected type: set {int, int}. Docs: https://docs.python.org/3/tutorial/datastructures.html#sets cut_indices = [ i for i, instruction in enumerate(toffoli_.data) if {toffoli_.find_bit(q)[0] for q in instruction.qubits} == gates_connecting_to_cut ] # Decompose distant CNOTs into TwoQubitQPDGate instances qpd_circuit, bases = cut_gates(toffoli_, cut_indices) ### Don't change any code past this line ### qpd_circuit.draw("mpl", scale=0.6) # set the observables observable = SparsePauliOp(["ZZZ"]) ### Write your code below here ### # Generate the sub-experiments and sampling coefficients sub_experiments, coefficients = generate_cutting_experiments( circuits=qpd_circuit, observables=observable.paulis, num_samples=np.inf ) # Transpile the circuit # Note: Use optimization_level=1 and seed_transpiler=0 pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0) isa_qpd_circuit = pm.run(sub_experiments[5]) # Depth using circuit cutting isa_qpd_toffoli_depth = isa_qpd_circuit.depth() ### Don't change any code past this line ### print(f"Transpiled circuit depth: ", isa_toffoli_depth) print(f"QPD sub-experiment depth after transpile: ", isa_qpd_toffoli_depth) print(f"Number of sub-experiments:", len(sub_experiments)) isa_qpd_circuit.draw("mpl", scale=0.6, idle_wires=False, fold=False) ### Write your code below here ### # mean of the depth of all sub-experiments depth_list = [c.depth() for c in pm.run(sub_experiments)] isa_qpd_toffoli_depth_mean = np.mean(depth_list) ### Don't change any code past this line ### print(isa_qpd_toffoli_depth_mean) # Submit your answer using following code grade_lab3_ckt_ex1(gates_connecting_to_cut, isa_toffoli_depth, depth_list) # Expected result type: set, int, numpy.ndarray ### Write your code below here ### # Find the indices of the distant gates gates_connecting_to_cut_1 = {1,2}# Hint: Expected type: set {int, int} gates_connecting_to_cut_2 = {0,2}# Hint: Expected type: set {int, int} cut_indices = [ i for i, instruction in enumerate(toffoli_.data) if {toffoli_.find_bit(q)[0] for q in instruction.qubits} == gates_connecting_to_cut_1 or {toffoli_.find_bit(q)[0] for q in instruction.qubits} == gates_connecting_to_cut_2 ] # Decompose distant CNOTs into TwoQubitQPDGate instances qpd_circuit_2, bases = cut_gates(toffoli_, cut_indices) ### Don't change any code past this line ### qpd_circuit_2.draw("mpl", scale=0.6) # set the observables observable = SparsePauliOp(["ZZZ"]) ### Write your code below here ### # Generate the sub-experiments and sampling coefficients sub_experiments_2, coefficients = generate_cutting_experiments( circuits=qpd_circuit_2, observables=observable.paulis, num_samples=np.inf ) # Transpile the circuit # Note: Use optimization_level=1 and seed_transpiler=0 pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0) isa_qpd_circuit_2 = pm.run(sub_experiments_2[5]) # Depth using circuit cutting isa_qpd_toffoli_depth_2 = pm.run(sub_experiments_2[5]).depth() ### Don't change any code past this line ### print(f"QPD sub-experiment depth after transpile: ", isa_qpd_toffoli_depth_2) print(f"Number of sub-experiments:", len(sub_experiments_2)) isa_qpd_circuit_2.draw("mpl", scale=0.6, idle_wires=False, fold=False) # Submit your answer using following code grade_lab3_ckt_ex2(gates_connecting_to_cut_1, gates_connecting_to_cut_2, sub_experiments_2) # Expected result type: set, set, list[QuantumCircuit] ### Write your code below here ### # mean of the depth of all sub-experiments depth_list_2 = [c.depth() for c in pm.run(sub_experiments_2)] isa_qpd_toffoli_depth_2_mean = np.mean(depth_list_2) ### Don't change any code past this line ### print(isa_qpd_toffoli_depth_2_mean) # Number of sub-experiments num_sub_experiments_1_cut = len(sub_experiments) num_sub_experiments_2_cut = len(sub_experiments_2) # Data for plotting categories = ['Before Cutting', 'After 1 Cut', 'After 2 Cuts'] depth_values = [isa_toffoli_depth, isa_qpd_toffoli_depth_mean, isa_qpd_toffoli_depth_2_mean] num_sub_experiments = [1, num_sub_experiments_1_cut, num_sub_experiments_2_cut] # Create figure and axis fig, ax1 = plt.subplots() # Plot depth values color = 'tab:blue' ax1.set_xlabel('Number of Cuts') ax1.set_ylabel('Circuit Depth', color=color) bars = ax1.bar(categories, depth_values, color=color, alpha=0.6) ax1.tick_params(axis='y', labelcolor=color) # Add value labels on bars for bar in bars: yval = bar.get_height() ax1.text(bar.get_x() + bar.get_width() / 2, yval + 1, round(yval, 2), ha='center', color=color, fontsize=10) # Create a second y-axis to plot the number of subexperiments ax2 = ax1.twinx() color = 'tab:green' ax2.set_ylabel('Number of Sub-experiments', color=color) ax2.plot(categories, num_sub_experiments, color=color, marker='o') ax2.tick_params(axis='y', labelcolor=color) # Add value labels on points for i, num in enumerate(num_sub_experiments): ax2.text(i, num + 0.1, num, ha='center', color=color, fontsize=10) # Add titles and labels plt.title('Circuit Knitting Toolbox Results') fig.tight_layout() # Adjust layout to make room for both y-axes # Show plot plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw()
https://github.com/1chooo/Quantum-Oracle
1chooo
#program 5.1a Define classical oracle f1 and test it def f1(x): return '1' print(f1('000'),f1('001'),f1('010'),f1('011'),f1('100'),f1('101'),f1('110'),f1('111')) #program 5.1b Define classical oracle f2 and test it def f2(x): if x[0]=='0': return '0' else: return '1' print(f2('000'),f2('001'),f2('010'),f2('011'),f2('100'),f2('101'),f2('110'),f2('111')) #Program 5.1c Solve constant-balanced function decision (CBFD) prob. with classical code import itertools def cbfd_test(f,n): count0=count1=0 iter = itertools.product([0,1], repeat=n) lst = [''.join(map(str, item)) for item in iter] for s in lst: if f(s)=='0': count0+=1 else: count1+=1 if count0>0 and count1>0: return True #for balanced function elif count0>2**(n-1) or count1>2**(n-1): return False #for constant function print(cbfd_test(f1,3)) print(cdfd_test(f2,3)) #Program 5.2 Define a quantum oracle from qiskit import QuantumRegister,QuantumCircuit qrx = QuantumRegister(3,'x') qry = QuantumRegister(1,'y') qc = QuantumCircuit(qrx,qry) qc.x(qry) qc.draw('mpl') #Program 5.3a Build quantum circuit of Deutsch-Jozsa alg. 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.measure(qrx,cr) qc.draw('mpl') #Program 5.3b Run Deutsch-Jozsa alg. with simulator 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) #Program 5.4 Define another quantum oracle from qiskit import QuantumRegister,QuantumCircuit qrx = QuantumRegister(3,'x') qry = QuantumRegister(1,'y') qc = QuantumCircuit(qrx,qry) qc.cx(qrx[0],qry) qc.draw('mpl') #Program 5.5a Build quantum circuit of Deutsch-Jozsa alg. 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.cx(qrx[0],qry) qc.barrier() qc.h(qrx) qc.measure(qrx,cr) qc.draw('mpl') #Program 5.5b Run Deutsch-Jozsa alg. with simulator 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) #Program 5.6 Show phase kickback of CNOT gate from qiskit import QuantumCircuit, Aer from qiskit.visualization import array_to_latex, plot_bloch_multivector sim = Aer.get_backend('aer_simulator') qc1 = QuantumCircuit(2) qc1.h(0) qc1.x(1) qc1.h(1) qc1.save_statevector() state1 = sim.run(qc1).result().get_statevector() display(qc1.draw('mpl')) display(array_to_latex(state1, prefix='\\text{Statevector before CNOT gate: }')) display(plot_bloch_multivector(state1)) print('='*60) qc2 = QuantumCircuit(2) qc2.h(0) qc2.x(1) qc2.h(1) qc2.cx(0,1) qc2.save_statevector() state2 = sim.run(qc2).result().get_statevector() display(qc2.draw('mpl')) display(array_to_latex(state2, prefix='\\text{Statevector after CNOT gate: }')) display(plot_bloch_multivector(state2)) # Program 5.7 Show phase kickback of CCNOT gate from qiskit import QuantumCircuit, Aer from qiskit.visualization import array_to_latex, plot_bloch_multivector sim = Aer.get_backend('aer_simulator') qc1 = QuantumCircuit(3) qc1.h([0,1]) qc1.x(2) qc1.h(2) qc1.save_statevector() state1 = sim.run(qc1).result().get_statevector() display(qc1.draw('mpl')) display(array_to_latex(state1, prefix="\\text{Statevector before CCNOT gate: }")) display(plot_bloch_multivector(state1)) print('='*80) qc2 = QuantumCircuit(3) qc2.h([0,1]) qc2.x(2) qc2.h(2) qc2.ccx(0,1,2) qc2.save_statevector() state2 = sim.run(qc2).result().get_statevector() display(qc2.draw('mpl')) display(array_to_latex(state2, prefix="\\text{Statevector before CCNOT gate: }")) display(plot_bloch_multivector(state2)) #Program 5.8 Show circuit containing CZ gate and CZ gate's unitary matrix from qiskit import QuantumCircuit, Aer from qiskit.visualization import array_to_latex sim = Aer.get_backend('aer_simulator') qc1 = QuantumCircuit(2) qc1.cz(0,1) qc1.save_unitary() unitary1 = sim.run(qc1).result().get_unitary() print("CZ Gate (q0 as control bit, q1 as target bit):") display(qc1.draw('mpl')) display(array_to_latex(unitary1, prefix="\\text{Unitray Matrix of CZ Gate (MSB as Target): }")) print('='*60) qc2 = QuantumCircuit(2) qc2.cz(1,0) qc2.save_unitary() unitary2 = sim.run(qc2).result().get_unitary() print("CZ Gate (q1 as control bit, q0 as target bit):") display(qc2.draw('mpl')) display(array_to_latex(unitary2, prefix="\\text{Unitray Matrix of CZ Gate (LSB as Target): }")) #Program 5.9 Show quantum circuit with CZ, CP, CS, CT gates from qiskit import QuantumCircuit from math import pi qc = QuantumCircuit(8) qc.cz(0,1) qc.cp(pi,2,3) qc.cp(pi/2,4,5) qc.cp(pi/4,6,7) display(qc.draw('mpl'))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.algorithms import AmplificationProblem # the state we desire to find is '11' good_state = ['11'] # specify the oracle that marks the state '11' as a good solution oracle = QuantumCircuit(2) oracle.cz(0, 1) # define Grover's algorithm problem = AmplificationProblem(oracle, is_good_state=good_state) # now we can have a look at the Grover operator that is used in running the algorithm # (Algorithm circuits are wrapped in a gate to appear in composition as a block # so we have to decompose() the op to see it expanded into its component gates.) problem.grover_operator.decompose().draw(output='mpl') from qiskit.algorithms import Grover from qiskit.primitives import Sampler grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Result type:', type(result)) print() print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) from qiskit.quantum_info import Statevector oracle = Statevector.from_label('11') problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Result type:', type(result)) print() print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) problem.grover_operator.oracle.decompose().draw(output='mpl') from qiskit.circuit.library.phase_oracle import PhaseOracle from qiskit.exceptions import MissingOptionalLibraryError # `Oracle` (`PhaseOracle`) as the `oracle` argument expression = '(a & b)' try: oracle = PhaseOracle(expression) problem = AmplificationProblem(oracle) display(problem.grover_operator.oracle.decompose().draw(output='mpl')) except MissingOptionalLibraryError as ex: print(ex) import numpy as np # Specifying `state_preparation` # to prepare a superposition of |01>, |10>, and |11> oracle = QuantumCircuit(3) oracle.ccz(0, 1, 2) theta = 2 * np.arccos(1 / np.sqrt(3)) state_preparation = QuantumCircuit(3) state_preparation.ry(theta, 0) state_preparation.ch(0,1) state_preparation.x(1) state_preparation.h(2) # we only care about the first two bits being in state 1, thus add both possibilities for the last qubit problem = AmplificationProblem(oracle, state_preparation=state_preparation, is_good_state=['110', '111']) # state_preparation print('state preparation circuit:') problem.grover_operator.state_preparation.draw(output='mpl') grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) oracle = QuantumCircuit(5) oracle.ccz(0, 1, 2) oracle.draw(output='mpl') from qiskit.circuit.library import GroverOperator grover_op = GroverOperator(oracle, insert_barriers=True) grover_op.decompose().draw(output='mpl') grover_op = GroverOperator(oracle, reflection_qubits=[0, 1, 2], insert_barriers=True) grover_op.decompose().draw(output='mpl') # a list of binary strings good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = ['11', '00'] problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # a list of integer good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = [0, 1] problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) from qiskit.quantum_info import Statevector # `Statevector` good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = Statevector.from_label('11') problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # Callable good state def callable_good_state(bitstr): if bitstr == "11": return True return False oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # integer iteration oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=1) # list iteration oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=[1, 2, 3]) # using sample_from_iterations oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=[1, 2, 3], sample_from_iterations=True) iterations = Grover.optimal_num_iterations(num_solutions=1, num_qubits=8) iterations def to_DIAMACS_CNF_format(bit_rep): return [index+1 if val==1 else -1 * (index + 1) for index, val in enumerate(bit_rep)] oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11'], post_processing=to_DIAMACS_CNF_format) problem.post_processing([1, 0, 1]) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mgg39/qiskit-networks
mgg39
# -*- 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/epelaaez/QuantumLibrary
epelaaez
from qiskit import QuantumCircuit, Aer, execute from math import pi import numpy as np from qiskit.visualization import plot_bloch_multivector, plot_histogram qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.cx(0,1) qc.draw() statevector_backend = Aer.get_backend('statevector_simulator') final_state = execute(qc,statevector_backend).result().get_statevector() print(final_state) plot_bloch_multivector(final_state) qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.z(1) qc.draw() final_state = execute(qc,statevector_backend).result().get_statevector() print(final_state) plot_bloch_multivector(final_state) qc.cx(0,1) qc.draw() final_state = execute(qc,statevector_backend).result().get_statevector() print(final_state) plot_bloch_multivector(final_state) qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.cx(0,1) qc.h(0) qc.h(1) display(qc.draw()) # `display` is an IPython tool, remove if it cases an error unitary_backend = Aer.get_backend('unitary_simulator') unitary = execute(qc,unitary_backend).result().get_unitary() print(unitary) qc = QuantumCircuit(2) qc.cx(1,0) display(qc.draw()) unitary_backend = Aer.get_backend('unitary_simulator') unitary = execute(qc,unitary_backend).result().get_unitary() print(unitary)
https://github.com/xtophe388/QISKIT
xtophe388
import getpass, time from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import available_backends, execute, register, least_busy # import basic plot tools from qiskit.tools.visualization import plot_histogram, circuit_drawer APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url":"https://quantumexperience.ng.bluemix.net/api"} try: register(qx_config['APItoken'], qx_config['url']) print('\nYou have access to great power!') print(available_backends({'local': False, 'simulator': False})) except: print('Something went wrong.\nDid you enter a correct token?') backend = least_busy(available_backends({'simulator': False, 'local': False})) print("The least busy backend is " + backend) q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) job_exp = execute(qc, backend=backend, shots=1024, max_credits=3) lapse = 0 interval = 30 while not job_exp.done: print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status) time.sleep(interval) lapse += 1 print(job_exp.status) plot_histogram(job_exp.result().get_counts(qc)) print('You have made entanglement!') circuit_drawer(qc)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb %run init.ipynb p = symbols('p') Ubf = Matrix([[sqrt(1-p),-sqrt(p),0,0],[0,0,sqrt(p),sqrt(1-p)],[0,0,sqrt(1-p),-sqrt(p)],[sqrt(p),sqrt(1-p),0,0]]) Ubf Ubf*Ubf.T, Ubf.T*Ubf g = symbols('gamma') Uad = Matrix([[sqrt(1-g),0,0,sqrt(g)],[0,1,0,0],[0,0,1,0],[-sqrt(g),0,0,sqrt(1-g)]]) Uad, Uad*Uad.T, Uad.T*Uad
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_aer.utils import approximate_quantum_error, approximate_noise_model import numpy as np # Import Aer QuantumError functions that will be used from qiskit_aer.noise import amplitude_damping_error, reset_error, pauli_error from qiskit.quantum_info import Kraus gamma = 0.23 error = amplitude_damping_error(gamma) results = approximate_quantum_error(error, operator_string="reset") print(results) p = (1 + gamma - np.sqrt(1 - gamma)) / 2 q = 0 print("") print("Expected results:") print("P(0) = {}".format(1-(p+q))) print("P(1) = {}".format(p)) print("P(2) = {}".format(q)) gamma = 0.23 K0 = np.array([[1,0],[0,np.sqrt(1-gamma)]]) K1 = np.array([[0,np.sqrt(gamma)],[0,0]]) results = approximate_quantum_error(Kraus([K0, K1]), operator_string="reset") print(results) reset_to_0 = Kraus([np.array([[1,0],[0,0]]), np.array([[0,1],[0,0]])]) reset_to_1 = Kraus([np.array([[0,0],[1,0]]), np.array([[0,0],[0,1]])]) reset_kraus = [reset_to_0, reset_to_1] gamma = 0.23 error = amplitude_damping_error(gamma) results = approximate_quantum_error(error, operator_list=reset_kraus) print(results) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/carstenblank/dc-qiskit-algorithms
carstenblank
# Copyright 2021 Carsten Blank # # 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. import logging import unittest import numpy as np import qiskit from ddt import ddt, data as test_data, unpack from qiskit import QuantumRegister, QuantumCircuit from qiskit_aer import AerJob from qiskit_aer.backends.aerbackend import AerBackend from qiskit.result import Result from scipy import sparse from scipy.sparse import linalg from dc_qiskit_algorithms.ControlledStatePreparation import ControlledStatePreparationGate logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO') log = logging.getLogger(__name__) log.setLevel(logging.INFO) @ddt class AngleMatrixYTests(unittest.TestCase): @unpack @test_data( {'matrix': np.sqrt([ [0.1, 0.2, 0.3, 0.4], [0.25, 0.25, 0.25, 0.25] ])} ) def test_angle_matrix_y(self, matrix): matrix = sparse.dok_matrix(matrix) abs_matrix = np.abs(matrix) log.info("Input Matrix (Y):\n" + str(abs_matrix)) iso_gate = ControlledStatePreparationGate(matrix) angle_matrix = iso_gate._to_angle_matrix_y() log.info("Final Angle Matrix (Y):\n" + str(angle_matrix.todense())) # The recovery is done by using a pre factor of 1/2 given the definition of the R_y gate matrix_recovered = sparse.dok_matrix(matrix.shape) for row in range(angle_matrix.shape[0]): matrix_recovered[row, 0] = np.cos(0.5 * angle_matrix[row, 0]) * np.cos(0.5 * angle_matrix[row, 1]) matrix_recovered[row, 1] = np.cos(0.5 * angle_matrix[row, 0]) * np.sin(0.5 * angle_matrix[row, 1]) matrix_recovered[row, 2] = np.sin(0.5 * angle_matrix[row, 0]) * np.cos(0.5 * angle_matrix[row, 2]) matrix_recovered[row, 3] = np.sin(0.5 * angle_matrix[row, 0]) * np.sin(0.5 * angle_matrix[row, 2]) log.info("Recovered Matrix (Y):\n" + str(matrix_recovered.todense())) self.assertAlmostEqual(linalg.norm(abs_matrix - matrix_recovered), 0.0, delta=1e-13) @ddt class AngleMatrixZTests(unittest.TestCase): @unpack @test_data( { 'matrix': np.sqrt([ [-0.25 + 0j, +0.25 + 0j, -0.25 + 0j, +0.25 + 0j], [+0.25 + 0j, +0.25 + 0j, +0.25 + 0j, +0.25 + 0j] ]) }, { 'matrix': np.sqrt([ [+0.50 + 0j, +0.30 + 0j, +0.20 + 0j, +0.00 + 0j], [+0.50 + 0j, -0.25 + 0j, +0.25 + 0j, +0.25 + 0j] ]) } ) def test_angle_matrix_z(self, matrix): phase_matrix = np.angle(matrix) matrix = sparse.dok_matrix(matrix) log.info("Input Phase Matrix (Z):\n" + str(phase_matrix)) iso_gate = ControlledStatePreparationGate(matrix) angle_matrix, global_phase = iso_gate._to_angle_matrix_z() angle_matrix = sparse.hstack([global_phase, angle_matrix]).todok() log.info("Final Angle Matrix (Z):\n" + str(angle_matrix.todense())) # The recovery is done by using a pre factor of 1/2 given the definition of the R_y gate matrix_recovered = sparse.dok_matrix(matrix.shape) for row in range(angle_matrix.shape[0]): matrix_recovered[row, 0] = np.angle(np.exp(1.0j * angle_matrix[row, 0]) * np.exp(-0.5j * angle_matrix[row, 1]) * np.exp(-0.5j * angle_matrix[row, 2])) matrix_recovered[row, 1] = np.angle(np.exp(1.0j * angle_matrix[row, 0]) * np.exp(-0.5j * angle_matrix[row, 1]) * np.exp(+0.5j * angle_matrix[row, 2])) matrix_recovered[row, 2] = np.angle(np.exp(1.0j * angle_matrix[row, 0]) * np.exp(+0.5j * angle_matrix[row, 1]) * np.exp(-0.5j * angle_matrix[row, 3])) matrix_recovered[row, 3] = np.angle(np.exp(1.0j * angle_matrix[row, 0]) * np.exp(+0.5j * angle_matrix[row, 1]) * np.exp(+0.5j * angle_matrix[row, 3])) global_phases = np.unique(np.round(phase_matrix - matrix_recovered.todense(), decimals=13), axis=1) self.assertEqual(global_phases.shape, (matrix_recovered.shape[0], 1)) matrix_recovered_1 = global_phases + matrix_recovered log.info("Recovered Matrix (Z):\n" + str(matrix_recovered_1)) self.assertAlmostEqual(np.linalg.norm(phase_matrix - matrix_recovered_1), 0.0, delta=1e-13) @ddt class ControlledMottonenStatePrepTests(unittest.TestCase): @unpack @test_data( { 'matrix': np.sqrt([ [+0.5, +0.5], [0.5 * np.exp(1j * np.pi), 0.5 * np.exp(1j * 0)] ]), 'debug_circuit': False }, { 'matrix': np.sqrt([ [+0.5, +0.5], [0.5 * np.exp(1j * np.pi), 0.5 * np.exp(1j * 0)] ]), 'debug_circuit': True }, { 'matrix': np.sqrt([ [+0.5, +0.5], [+0.6, +0.4], [+0.7, +0.3], [+0.9, +0.1] ]), 'debug_circuit': False }, { 'matrix': np.sqrt([ [+0.5, +0.5], [+0.6, +0.4], [+0.7, +0.3], [+0.9, +0.1] ]), 'debug_circuit': True }, { 'matrix': np.sqrt([ [+0.50, +0.30, +0.20, +0.00], [+0.25, +0.25, +0.25, +0.25] ]), 'debug_circuit': False }, { 'matrix': np.sqrt([ [+0.50, +0.30, +0.20, +0.00], [+0.25, +0.25, +0.25, +0.25] ]), 'debug_circuit': True }, { 'matrix': np.sqrt([ [+0.50, +0.30, +0.20, +0.00], [+0.25, +0.25, +0.25, +0.25], [+0.10, +0.10, +0.40, +0.40], [+0.40, +0.10, +0.30, +0.20], [+0.50, +0.30, +0.20, +0.00], [+0.25, +0.25, +0.25, +0.25], [+0.10, +0.10, +0.40, +0.40], [+0.40, +0.10, +0.30, +0.20] ]), 'debug_circuit': True }, { 'matrix': np.sqrt([ [+0.50, +0.30, +0.20, +0.00], [+0.25, +0.25, +0.25, +0.25], [+0.10, +0.10, +0.40, +0.40], [+0.40, +0.10, +0.30, +0.20], [+0.50, +0.30, +0.20, +0.00], [+0.25, +0.25, +0.25, +0.25], [+0.10, +0.10, +0.40, +0.40], [+0.40, +0.10, +0.30, +0.20] ]), 'debug_circuit': False }, { 'matrix': np.sqrt([ [0.50 * np.exp(1j * 0), 0.30 * np.exp(1j * 0), 0.20 * np.exp(1j * 0), 0.00 * np.exp(1j * 0)], [0.40 * np.exp(1j * 0), 0.10 * np.exp(-1j * np.pi), 0.25 * np.exp(1j * 0), 0.25 * np.exp(1j * 0)] ]), 'debug_circuit': False }, { 'matrix': np.sqrt([ [0.50 * np.exp(1j * 0), 0.30 * np.exp(1j * 0), 0.20 * np.exp(1j * 0), 0.00 * np.exp(1j * 0)], [0.40 * np.exp(1j * 0), 0.10 * np.exp(-1j * np.pi), 0.25 * np.exp(1j * 0), 0.25 * np.exp(1j * 0)] ]), 'debug_circuit': True } ) def test_define(self, matrix, debug_circuit): log.info("STARTING TEST") control_qubits = int(np.ceil(np.log2(matrix.shape[0]))) target_qubits = int(np.ceil(np.log2(matrix.shape[1]))) # We can compute the expected state vector by assuming we use an equal superposition (hadamard) on the # control qubits (we need to do that a few lines down) so a factor in the Hadamard factors 2^{-n/2} is needed # Also, the ordering of the registers is extremely important here. A few lines below, we first add the control # and then the target qubits. That gives the canonical ordering such that we can do column first ravel (order=F) theoretical_state_vector: np.ndarray = np.asarray( matrix.ravel(order='F') ).reshape(-1) * np.power(2, -control_qubits / 2) log.info(f"Expected State: {theoretical_state_vector.tolist()}") # As mentioned above the ordering is important for this test! ctrl_qb = QuantumRegister(control_qubits, name='ctrl') tgt_qb = QuantumRegister(target_qubits, name='tgt') qc = QuantumCircuit(ctrl_qb, tgt_qb) # Here we do the equal superposition on the control register as assumed above. qc.h(ctrl_qb) qc.append( ControlledStatePreparationGate(sparse.dok_matrix(matrix)).set_debug_flag(debug_circuit), list(ctrl_qb) + list(tgt_qb) ) drawing = ControlledStatePreparationGate(sparse.dok_matrix(matrix)) \ .set_debug_flag(debug_circuit) \ .definition \ .draw(fold=-1) log.info(f'Circuit:\n{drawing}') # The the resulting state vector from the state vector simulator backend: AerBackend = qiskit.Aer.get_backend('statevector_simulator') job: AerJob = qiskit.execute(qc, backend) result: Result = job.result() vector: np.ndarray = np.asarray(result.get_statevector()) # Computing the test: # The extracted state from the simulation is allowed to be off by a common (global) phase # If this is the case, taking the angle difference and correcting it, should give the same vector correction = np.angle(theoretical_state_vector[0]) - np.angle(vector[0]) vector_phase_corrected = vector * np.exp(1.0j * correction) log.info(f"Actual State: {vector_phase_corrected.tolist()}") diff = vector_phase_corrected - theoretical_state_vector self.assertAlmostEqual(np.linalg.norm(diff), 0.0, places=13) if log.level == logging.DEBUG: basic_qc = qiskit.transpile(qc, optimization_level=0, basis_gates=['uni_rot_rz', 'uni_rot_ry', 'state_prep_möttönen', 'h']) log.debug(f"\n{basic_qc.draw(fold=-1)}") basic_qc = qiskit.transpile(qc, optimization_level=0, basis_gates=['rz', 'cp', 'cx', 'ry', 'p', 'h']) log.debug(f"\n{basic_qc.draw(fold=-1)}") basic_qc = qiskit.transpile(qc, optimization_level=3, basis_gates=['u3', 'u2', 'u1', 'cx']) log.debug(f"\n{basic_qc.draw(fold=-1)}") log.debug('Theoretical result:') log.debug(np.round(theoretical_state_vector, decimals=4).tolist()) log.debug('Absolute:') log.debug(np.round(np.abs(vector), decimals=4).tolist()) log.debug(np.round(np.abs(theoretical_state_vector), decimals=4).tolist()) log.debug('Angle:') corrected_angle_vector = correction + np.angle(vector) corrected_angle_vector = np.fmod(corrected_angle_vector, 2*np.pi) log.debug(np.round(corrected_angle_vector, decimals=4).tolist()) log.debug(np.round(np.angle(theoretical_state_vector), decimals=4).tolist()) log.debug('TEST:') angle_diff = corrected_angle_vector - np.angle(theoretical_state_vector) abs_diff = np.abs(vector) - np.abs(theoretical_state_vector) log.debug(np.round(abs_diff, decimals=4).tolist()) log.debug(np.round(angle_diff, decimals=4).tolist()) log.debug('Real:') log.debug(np.round(np.real(vector * np.exp(1.0j * correction)), decimals=4).tolist()) log.debug('Difference:') log.debug(np.round(diff, decimals=4).tolist()) log.info("ENDING TEST")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): 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(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import json import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit import ParameterVector from qiskit.circuit.library import ZFeatureMap from qiskit.quantum_info import SparsePauliOp from qiskit.utils import algorithm_globals from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier from qiskit_machine_learning.neural_networks import EstimatorQNN from sklearn.model_selection import train_test_split algorithm_globals.random_seed = 12345 # We now define a two qubit unitary as defined in [3] def conv_circuit(params): target = QuantumCircuit(2) target.rz(-np.pi / 2, 1) target.cx(1, 0) target.rz(params[0], 0) target.ry(params[1], 1) target.cx(0, 1) target.ry(params[2], 1) target.cx(1, 0) target.rz(np.pi / 2, 0) return target # Let's draw this circuit and see what it looks like params = ParameterVector("θ", length=3) circuit = conv_circuit(params) circuit.draw("mpl") def conv_layer(num_qubits, param_prefix): qc = QuantumCircuit(num_qubits, name="Convolutional Layer") qubits = list(range(num_qubits)) param_index = 0 params = ParameterVector(param_prefix, length=num_qubits * 3) for q1, q2 in zip(qubits[0::2], qubits[1::2]): qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2]) qc.barrier() param_index += 3 for q1, q2 in zip(qubits[1::2], qubits[2::2] + [0]): qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2]) qc.barrier() param_index += 3 qc_inst = qc.to_instruction() qc = QuantumCircuit(num_qubits) qc.append(qc_inst, qubits) return qc circuit = conv_layer(4, "θ") circuit.decompose().draw("mpl") def pool_circuit(params): target = QuantumCircuit(2) target.rz(-np.pi / 2, 1) target.cx(1, 0) target.rz(params[0], 0) target.ry(params[1], 1) target.cx(0, 1) target.ry(params[2], 1) return target params = ParameterVector("θ", length=3) circuit = pool_circuit(params) circuit.draw("mpl") def pool_layer(sources, sinks, param_prefix): num_qubits = len(sources) + len(sinks) qc = QuantumCircuit(num_qubits, name="Pooling Layer") param_index = 0 params = ParameterVector(param_prefix, length=num_qubits // 2 * 3) for source, sink in zip(sources, sinks): qc = qc.compose(pool_circuit(params[param_index : (param_index + 3)]), [source, sink]) qc.barrier() param_index += 3 qc_inst = qc.to_instruction() qc = QuantumCircuit(num_qubits) qc.append(qc_inst, range(num_qubits)) return qc sources = [0, 1] sinks = [2, 3] circuit = pool_layer(sources, sinks, "θ") circuit.decompose().draw("mpl") def generate_dataset(num_images): images = [] labels = [] hor_array = np.zeros((6, 8)) ver_array = np.zeros((4, 8)) j = 0 for i in range(0, 7): if i != 3: hor_array[j][i] = np.pi / 2 hor_array[j][i + 1] = np.pi / 2 j += 1 j = 0 for i in range(0, 4): ver_array[j][i] = np.pi / 2 ver_array[j][i + 4] = np.pi / 2 j += 1 for n in range(num_images): rng = algorithm_globals.random.integers(0, 2) if rng == 0: labels.append(-1) random_image = algorithm_globals.random.integers(0, 6) images.append(np.array(hor_array[random_image])) elif rng == 1: labels.append(1) random_image = algorithm_globals.random.integers(0, 4) images.append(np.array(ver_array[random_image])) # Create noise for i in range(8): if images[-1][i] == 0: images[-1][i] = algorithm_globals.random.uniform(0, np.pi / 4) return images, labels images, labels = generate_dataset(50) train_images, test_images, train_labels, test_labels = train_test_split( images, labels, test_size=0.3 ) fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(4): ax[i // 2, i % 2].imshow( train_images[i].reshape(2, 4), # Change back to 2 by 4 aspect="equal", ) plt.subplots_adjust(wspace=0.1, hspace=0.025) feature_map = ZFeatureMap(8) feature_map.decompose().draw("mpl") feature_map = ZFeatureMap(8) ansatz = QuantumCircuit(8, name="Ansatz") # First Convolutional Layer ansatz.compose(conv_layer(8, "с1"), list(range(8)), inplace=True) # First Pooling Layer ansatz.compose(pool_layer([0, 1, 2, 3], [4, 5, 6, 7], "p1"), list(range(8)), inplace=True) # Second Convolutional Layer ansatz.compose(conv_layer(4, "c2"), list(range(4, 8)), inplace=True) # Second Pooling Layer ansatz.compose(pool_layer([0, 1], [2, 3], "p2"), list(range(4, 8)), inplace=True) # Third Convolutional Layer ansatz.compose(conv_layer(2, "c3"), list(range(6, 8)), inplace=True) # Third Pooling Layer ansatz.compose(pool_layer([0], [1], "p3"), list(range(6, 8)), inplace=True) # Combining the feature map and ansatz circuit = QuantumCircuit(8) circuit.compose(feature_map, range(8), inplace=True) circuit.compose(ansatz, range(8), inplace=True) observable = SparsePauliOp.from_list([("Z" + "I" * 7, 1)]) # we decompose the circuit for the QNN to avoid additional data copying qnn = EstimatorQNN( circuit=circuit.decompose(), observables=observable, input_params=feature_map.parameters, weight_params=ansatz.parameters, ) circuit.draw("mpl") def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() with open("11_qcnn_initial_point.json", "r") as f: initial_point = json.load(f) classifier = NeuralNetworkClassifier( qnn, optimizer=COBYLA(maxiter=200), # Set max iterations here callback=callback_graph, initial_point=initial_point, ) x = np.asarray(train_images) y = np.asarray(train_labels) objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) classifier.fit(x, y) # score classifier print(f"Accuracy from the train data : {np.round(100 * classifier.score(x, y), 2)}%") y_predict = classifier.predict(test_images) x = np.asarray(test_images) y = np.asarray(test_labels) print(f"Accuracy from the test data : {np.round(100 * classifier.score(x, y), 2)}%") # Let's see some examples in our dataset fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(0, 4): ax[i // 2, i % 2].imshow(test_images[i].reshape(2, 4), aspect="equal") if y_predict[i] == -1: ax[i // 2, i % 2].set_title("The QCNN predicts this is a Horizontal Line") if y_predict[i] == +1: ax[i // 2, i % 2].set_title("The QCNN predicts this is a Vertical Line") plt.subplots_adjust(wspace=0.1, hspace=0.5) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/toticavalcanti/qiskit_examples
toticavalcanti
from qiskit import IBMQ IBMQ.save_account('seu token') from qiskit import * qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) %matplotlib inline circuit.draw() circuit.h(0) circuit.draw(output='mpl') circuit.cx(0,1) # order is: control(0) and target(1) circuit.draw(output='mpl') circuit.measure(qr, cr) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator).result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) IBMQ.load_account() provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_16_melbourne') job = execute(circuit, backend=qcomp) from qiskit.tools.monitor import job_monitor job_monitor(job)
https://github.com/maryrbarros2/QuantumAlgorithms_Qiskit
maryrbarros2
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.providers.aer import QasmSimulator from qiskit.visualization import plot_histogram # Create a Quantum Circuit acting on a quantum register of three qubits circ = QuantumCircuit(3) #default, each qubit in the register is initialized to |0⟩ # Add a H gate on qubit 0, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. circ.cx(0, 1) # Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting # the qubits in a GHZ state. circ.cx(0, 2) circ.draw('mpl') # Import Aer from qiskit import Aer from qiskit import execute # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') # Create a Quantum Program for execution job = execute(circ, backend) job.status() result = job.result() #results object contains the data outputstate = result.get_statevector(circ, decimals=3) print(outputstate) from qiskit.visualization import plot_state_city plot_state_city(outputstate) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = execute(circ, backend) result = job.result() output = result.get_unitary(circ, decimals=3) # Show the results print(output) plot_state_city(output) # Create a Quantum Circuit meas = QuantumCircuit(3, 3) meas.barrier(range(3)) # map the quantum measurement to the classical bits meas.measure(range(3), range(3)) # The Qiskit circuit object supports composition using # the addition operator. qc = circ + meas #drawing the circuit qc.draw() # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim = execute(qc, backend_sim, shots=1024) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(qc) print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts) #Trying with different shots to compare: job_sim2 = execute(qc, backend_sim, shots=3000) # Grab the results from the job. result_sim2 = job_sim2.result() counts2 = result_sim2.get_counts(qc) plot_histogram(counts2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, backend=FakeBoeblingen())
https://github.com/renatawong/classical-shadow-vqe
renatawong
''' (C) 2023 Renata Wong Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510 This code uses Qiskit as platform. The shadow is constructed based on derandomized Hamiltonian. The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g). The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'. ''' import time import numpy as np from collections import Counter import matplotlib.pyplot as plt from qiskit import QuantumCircuit, execute from qiskit_aer.primitives import Estimator as AerEstimator from qiskit_aer import QasmSimulator from qiskit.quantum_info import SparsePauliOp from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock from qiskit_nature.second_q.algorithms import VQEUCCFactory from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA # Estimator primitive is based on the Statevector construct = algebraic simulation from qiskit.primitives import Estimator from qiskit.utils import algorithm_globals from modified_derandomization import modified_derandomized_classical_shadow from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow from predicting_quantum_properties.prediction_shadow import estimate_exp import qiskit_nature qiskit_nature.settings.use_pauli_sum_op = False import h5py H5PY_DEFAULT_READONLY=1 ''' DEFINING DRIVERS FOR THE MOLECULES ''' H2_driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="6-31g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) LiH_driver = PySCFDriver( atom="Li 0 0 0; H 0 0 1.599", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) BeH2_driver = PySCFDriver( atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) H2O_driver = PySCFDriver( atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) NH3_driver = PySCFDriver( atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) ''' FORMATTING HAMILTONIAN ''' def process_hamiltonian(hamiltonian, derandomize = False): hamiltonian_observables = [] hamiltonian_coefficients = [] for observable in hamiltonian.paulis: op_list = [] for op_index, pauli_op in enumerate(observable): pauli_op = str(pauli_op) if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z': op_list.append((pauli_op, op_index)) hamiltonian_observables.append(op_list) hamiltonian_coefficients = hamiltonian.coeffs.real system_size = len(hamiltonian_observables[0]) # removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left # these observables are needed for estimate_exp() observables_xyze = [] for observable in hamiltonian_observables: XYZE = [] for pauli in observable: if pauli[0] != 'I': XYZE.append(pauli) observables_xyze.append(XYZE) # derandomisation procedure requires that coefficients are non-negative if derandomize == True: absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients] # removing the empty list as well # these observables are needed for derandomisation procedure observables_xyz = [] for idx, observable in enumerate(observables_xyze): if observable: observables_xyz.append(observable) else: absolute_coefficients.pop(idx) return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients return system_size, observables_xyze, hamiltonian_coefficients ''' COST FUNCTION AND HELPER FUNCTIONS ''' def basis_change_circuit(pauli_op): # Generating circuit with just the basis change operators # # pauli_op: n-qubit Pauli operator basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits) for idx, op in enumerate(pauli_op): if op == 'X': basis_change.h(idx) if op == 'Y': basis_change.h(idx) basis_change.p(-np.pi/2, idx) return basis_change def ground_state_energy_from_shadow(operators, params): backend = QasmSimulator(method='statevector', shots=1) pauli_op_dict = Counter(tuple(x) for x in operators) shadow = [] for pauli_op in pauli_op_dict: qc = ansatz.bind_parameters(params) qc = qc.compose(basis_change_circuit(pauli_op)) qc.measure(reversed(range(system_size)), range(system_size)) result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result() counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure for count in counts: for _ in range(counts[count]): # number of repeated measurement values output_str = list(count) output = [int(i) for i in output_str] eigenvals = [x+1 if x == 0 else x-2 for x in output] snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)] shadow.append(snapshot) expectation_value = 0.0 for term, weight in zip(observables_xyze, hamiltonian_coefficients): sum_product, match_count = estimate_exp(shadow, term) if match_count != 0: expectation_value += (weight * sum_product / match_count) return expectation_value ''' EXPERIMENTS ''' start_time = time.time() all_molecules_rmse_errors = [] # CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN MOLECULES = ['NH3'] for molecule in MOLECULES: rmse_errors = [] if molecule == 'H2': problem = H2_driver.run() if molecule == 'LiH': problem = LiH_driver.run() if molecule == 'BeH2': problem = BeH2_driver.run() if molecule == 'H2O': problem = H2O_driver.run() if molecule == 'NH3': problem = NH3_driver.run() hamiltonian = problem.hamiltonian second_q_op = hamiltonian.second_q_op() bk_mapper = BravyiKitaevMapper() #ParityMapper(num_particles=problem.num_particles) #BravyiKitaevMapper() bkencoded_hamiltonian = bk_mapper.map(second_q_op) #print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian) # process the Hamiltonian to obtain properly formatted data hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True) system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data ''' VARIATIONAL ANSATZ ''' ansatz = UCCSD( problem.num_spatial_orbitals, problem.num_particles, bk_mapper, initial_state=HartreeFock( problem.num_spatial_orbitals, problem.num_particles, bk_mapper, ), ) ''' Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive) ''' #estimator = Estimator() # If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions # with standard errors as standard deviations using normal distribution approximation. #estimator.set_options(shots = None) #estimator = AerEstimator() #estimator.set_options(approximation=True, shots=None) vqe_solver = VQE(Estimator(), ansatz, SLSQP()) vqe_solver.initial_point = np.zeros(ansatz.num_parameters) calc = GroundStateEigensolver(bk_mapper, vqe_solver) result = calc.solve(problem) print(result.raw_result) #print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n') measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750] for num_operators in measurement_range: derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, 50, system_size, weight=absolute_coefficients) tuples = (tuple(pauli) for pauli in derandomized_hamiltonian) counts = Counter(tuples) print('Original derandomized Hamiltonian', counts) # derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators # adjusting for this issue: while sum(counts.values()) != num_operators: for key, value in zip(counts.keys(), counts.values()): sum_counts = sum(counts.values()) if sum_counts == num_operators: break if sum_counts < num_operators: # generate additional operators from the existing ones by increasing the number of counts counts[key] += 1 if sum_counts > num_operators: # remove the element with highest count max_element_key = [k for k, v in counts.items() if v == max(counts.values())][0] counts[max_element_key] -= 1 print('Size-adjusted derandomized Hamiltonian', counts) # translate the Counter to a set of derandomized operators new_derandomized_hamiltonian = [] for key, value in counts.items(): for _ in range(value): new_derandomized_hamiltonian.append(list(key)) #print('Size-adjusted derandomized Hamiltonian', new_derandomized_hamiltonian) expectation_values = [] num_experiments = 10 for iteration in range(num_experiments): expectation_value = ground_state_energy_from_shadow(new_derandomized_hamiltonian, result.raw_result.optimal_point) expectation_values.append(expectation_value) print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value)) rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2 for i in range(num_experiments)])/num_experiments) rmse_errors.append(rmse_derandomised_cs) print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs)) all_molecules_rmse_errors.append(rmse_errors) elapsed_time = time.time() - start_time print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time))) import matplotlib.pyplot as plt points = measurement_range num_points = len(points) plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='derandomized classical shadow') plt.xlabel('Number of measurements') plt.ylabel('Average RMSE error') plt.legend(loc=1)
https://github.com/kaelynj/Qiskit-HubbardModel
kaelynj
%matplotlib inline import sys sys.path.append('./src') # 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 * import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np import ClassicalHubbardEvolutionChain as chc import FullClassicalHubbardEvolutionChain as fhc import random as rand import scipy.linalg as la #System parameters numsites = 3 t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) states_list = fhc.get_states(numsites) #Create full Hamiltonian wfk_full = np.zeros(len(states_list)) #wfk_full[18] = 1. #010010 wfk_full[21] = 1. #010101 #wfk_full[2] = 1. #000010 evolution2, engs2, wfks = fhc.sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step) print(wfks[10]) print(evolution2) #print(engs2) colors = list(mcolors.TABLEAU_COLORS.keys()) fig2, ax2 = plt.subplots(figsize=(20,10)) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution2[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution2[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) plt.legend() def get_bin(x, n=0): """ Get the binary representation of x. Parameters: x (int), n (int, number of digits)""" binry = format(x, 'b').zfill(n) sup = list( reversed( binry[0:int(len(binry)/2)] ) ) sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) ) return format(x, 'b').zfill(n) #==== Create all Possible States for given system size ===# states_list = [] nsite = 3 for state in range(0, 2**(2*nsite)): state_bin = get_bin(state, 2*nsite) state_list = [[],[]] for mode in range(0,nsite): state_list[0].append(int(state_bin[mode])) state_list[1].append(int(state_bin[mode+nsite])) #print(state_list) states_list.append(state_list) def repel(l,state): if state[0][l]==1 and state[1][l]==1: return state else: return [] #Check if two states are different by a single hop def hop(psii, psij, hopping): #Check spin down hopp = 0 if psii[0]==psij[0]: #Create array of indices with nonzero values hops = [] for site in range(len(psii[0])): if psii[1][site] != psij[1][site]: hops.append(site) if len(hops)==2 and np.sum(psii[1]) == np.sum(psij[1]): if hops[1]-hops[0]==1: hopp = -hopping return hopp #Check spin up if psii[1]==psij[1]: hops = [] for site in range(len(psii[1])): if psii[0][site] != psij[0][site]: hops.append(site) if len(hops)==2 and np.sum(psii[0])==np.sum(psij[0]): if hops[1]-hops[0]==1: hopp = -hopping return hopp return hopp def get_hamiltonian(states, t, U): H = np.zeros((len(states),len(states)) ) #Construct Hamiltonian matrix for i in range(len(states)): psi_i = states[i] for j in range(i, len(states)): psi_j = states[j] if j==i: for l in range(0,len(states[0][0])): if psi_i == repel(l,psi_j): H[i,j] = U break else: #print('psi_i: ',psi_i,' psi_j: ',psi_j) H[i,j] = hop(psi_i, psi_j, t) H[j,i] = H[i,j] return H def get_mapping(states): num_sites = len(states[0][0]) mode_list = [] for i in range(0,2*num_sites): index_list = [] for state_index in range(0,len(states)): state = states[state_index] #Check spin-up modes if i < num_sites: if state[0][i]==1: index_list.append(state_index) #Check spin-down modes else: if state[1][i-num_sites]==1: index_list.append(state_index) if index_list: mode_list.append(index_list) return mode_list def wfk_energy(wfk, hamil): eng = np.dot(np.conj(wfk), np.dot(hamil, wfk)) return eng def get_variance(wfk, h): h_squared = np.matmul(h, h) eng_squared = np.vdot(wfk, np.dot(h_squared, wfk)) squared_eng = np.vdot(wfk, np.dot(h, wfk)) var = np.sqrt(eng_squared - squared_eng) return var def sys_evolve(states, init_wfk, hopping, repulsion, total_time, dt): hamiltonian = get_hamiltonian(states, hopping, repulsion) t_operator = la.expm(-1j*hamiltonian*dt) wavefunctions = [] mapping = get_mapping(states) #print(mapping) #Initalize system tsteps = int(total_time/dt) evolve = np.zeros([tsteps, len(init_wfk)]) mode_evolve = np.zeros([tsteps, len(mapping)]) wfk = init_wfk wavefunctions.append(np.ndarray.tolist(wfk)) energies = np.zeros(tsteps) #Store first time step in mode_evolve evolve[0] = np.multiply(np.conj(wfk), wfk) for i in range(0, len(mapping)): wfk_sum = 0. norm = 0. for j in mapping[i]: wfk_sum += evolve[0][j] norm += evolve[0][j] if norm == 0.: norm = 1. mode_evolve[0][i] = wfk_sum #/ norm #print('wfk_sum: ',wfk_sum,' norm: ',norm) energies[0] = wfk_energy(wfk, hamiltonian) #print('Variance: ',get_variance(wfk, hamiltonian) ) #Now do time evolution print(mode_evolve[0]) times = np.arange(0., total_time, dt) for t in range(1, tsteps): wfk = np.dot(t_operator, wfk) evolve[t] = np.multiply(np.conj(wfk), wfk) wavefunctions.append(np.ndarray.tolist(wfk)) #print(evolve[t]) energies[t] = wfk_energy(wfk, hamiltonian ) for i in range(0, len(mapping)): norm = 0. wfk_sum = 0. for j in mapping[i]: wfk_sum += evolve[t][j] norm += evolve[t][j] #print('wfk_sum: ',wfk_sum,' norm: ',norm) if norm == 0.: norm = 1. mode_evolve[t][i] = wfk_sum #/ norm #print(mode_evolve[t]) #Return time evolution return mode_evolve, energies, wavefunctions #System parameters t = 1.0 U = 2. classical_time_step = 0.01 classical_total_time = 500*0.01 times = np.arange(0., classical_total_time, classical_time_step) #Create full Hamiltonian wfk_full = np.zeros(len(states_list)) #wfk_full[18] = 1. #010010 wfk_full[21] = 1. #010101 #wfk_full[2] = 1. #000010 evolution2, engs2, wfks = sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step) print(wfks[10]) print(evolution2) #print(engs2) colors = list(mcolors.TABLEAU_COLORS.keys()) fig2, ax2 = plt.subplots(figsize=(20,10)) for i in range(3): #Create string label strup = "Site "+str(i+1)+r'$\uparrow$' strdwn = "Site "+str(i+1)+r'$\downarrow$' ax2.plot(times, evolution2[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup) ax2.plot(times, evolution2[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn) plt.legend()
https://github.com/C2QA/bosonic-qiskit
C2QA
from qiskit import QuantumCircuit from . import circuit_constructor, circuit_eq def test_circuit_constructor(): gates_list = ["h", "hs", "hs", "i", "i", "h"] result = circuit_constructor(gates_list) result_dag = circuit_constructor(gates_list, True) expected = QuantumCircuit(6) expected.h(0) _ = expected.s(1), expected.h(1) _ = expected.s(2), expected.h(2) expected.h(5) expected_dag = QuantumCircuit(6) expected_dag.h(0) _ = expected_dag.h(1), expected_dag.sdg(1) _ = expected_dag.h(2), expected_dag.sdg(2) expected_dag.h(5) assert circuit_eq(result, expected) assert circuit_eq(result_dag, expected_dag)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
from qiskit import * from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector from qiskit.quantum_info import Statevector from qiskit.extensions import * import matplotlib.pyplot as plt %matplotlib inline import numpy as np import math from math import pi, sqrt from qiskit.quantum_info import random_unitary from random import seed from random import random import cmath from qiskit.circuit import Parameter import numpy as np import scipy.linalg as la from qiskit.exceptions import QiskitError from qiskit.quantum_info.states.densitymatrix import DensityMatrix, Statevector from qiskit.quantum_info.states.utils import (partial_trace, shannon_entropy,_format_state, _funm_svd, partial_trace) from qiskit.quantum_info.states.measures import partial_trace, _format_state qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.h(qr[0]) qc.h(qr[1]) qc.cz(qr[0],qr[1]) svsim = Aer.get_backend('statevector_simulator') def entange_measure2(qc,n): qobj = assemble(qc) state = svsim.run(qobj).result().get_statevector() dm=DensityMatrix(state) partial=[] for i in range(n): pt=partial_trace(dm,[i]).to_operator().data partial.append((1/2)*np.dot(pt,pt).trace()) return 2*(1-(sum(partial))) def entange_measure4(qc,n): qobj = assemble(qc) state = svsim.run(qobj).result().get_statevector() dm=DensityMatrix(state) partial=[] for i in range(4): for j in range(4): for k in range(4): if i>j>k: pt=partial_trace(dm,[i,j,k]).data partial.append(np.dot(pt,pt).trace()) return 2*(1-(1/16)*(sum(partial))) entange_measure(qc,2) ll=0; for i in range(4): for j in range(4): for k in range(4): if i>j and j>k: ll=ll+1 ll qr = QuantumRegister(4) qc = QuantumCircuit(qr) theta=[]; for y in range(500): theta.append(2*pi*random()) qc=circuit1(qc,qr,theta,1,0) qobj = assemble(qc) state = svsim.run(qobj).result().get_statevector() dm=DensityMatrix(state) pt=partial_trace(dm,[0,1,2]).data pt backend = Aer.get_backend('qasm_simulator') nshot=1000 m=[]; qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr) theta=[]; for y in range(80): theta.append(2*pi*random()) qc=circuit1(qc,qr,theta,1,0) qc.measure(qr[:],cr[:]) job = execute(qc, bWackend, shots=nshot) result = job.result() count =result.get_counts() count Q=Q+0.5**(u[i]*v[j]-u[j]*v[i])**2 Q def circuit1(qc,qr,theta,L,repeat): #circuit 1 #theta is list of the parameters #theta length is 8L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 return qc def circuit2(qc,qr,theta,L,repeat): #circuit 2 #theta is list of the parameters #theta length is 8L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.cx(qr[3],qr[2]) qc.cx(qr[2],qr[1]) qc.cx(qr[1],qr[0]) if repeat!=0: qc.barrier(qr) for l in range(L): qc.cx(qr[1],qr[0]) qc.cx(qr[2],qr[1]) qc.cx(qr[3],qr[2]) for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 return qc def circuit3(qc,qr,theta,L,repeat): #circuit 3 #theta is list of the parameters #theta length is (11)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.crz(theta[count],qr[3],qr[2]) count=count+1 qc.crz(theta[count],qr[2],qr[1]) count=count+1 qc.crz(theta[count],qr[1],qr[0]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): qc.crz(theta[count],qr[1],qr[0]) count=count+1 qc.crz(theta[count],qr[2],qr[1]) count=count+1 qc.crz(theta[count],qr[3],qr[2]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 return qc def circuit4(qc,qr,theta,L,repeat): #circuit 4 #theta is list of the parameters #theta length is (11)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.crx(theta[count],qr[3],qr[2]) count=count+1 qc.crx(theta[count],qr[2],qr[1]) count=count+1 qc.crx(theta[count],qr[1],qr[0]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): qc.crx(theta[count],qr[1],qr[0]) count=count+1 qc.crx(theta[count],qr[2],qr[1]) count=count+1 qc.crx(theta[count],qr[3],qr[2]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 return qc def circuit5(qc,qr,theta,L,repeat): #circuit 5 #theta is list of the parameters #theta length is (28)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for j in range(4): for i in range(4): if i!=j: qc.crz(theta[count],qr[3-j],qr[3-i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for j in range(4): for i in range(4): if i!=j: qc.crz(theta[count],qr[j],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 return qc def circuit6(qc,qr,theta,L,repeat): #circuit 6 #theta is list of the parameters #theta length is (28)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for j in range(4): for i in range(4): if i!=j: qc.crx(theta[count],qr[3-j],qr[3-i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for j in range(4): for i in range(4): if i!=j: qc.crx(theta[count],qr[j],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 return qc def circuit7(qc,qr,theta,L,repeat): #circuit 7 #theta is list of the parameters #theta length is (19)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.crz(theta[count],qr[1],qr[0]) count=count+1 qc.crz(theta[count],qr[3],qr[2]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.crz(theta[count],qr[2],qr[1]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): qc.crz(theta[count],qr[2],qr[1]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 qc.crz(theta[count],qr[3],qr[2]) count=count+1 qc.crz(theta[count],qr[1],qr[0]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 return qc def circuit8(qc,qr,theta,L,repeat): #circuit 8 #theta is list of the parameters #theta length is (19)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.crx(theta[count],qr[1],qr[0]) count=count+1 qc.crx(theta[count],qr[3],qr[2]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.crx(theta[count],qr[2],qr[1]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): qc.crx(theta[count],qr[2],qr[1]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 qc.crx(theta[count],qr[3],qr[2]) count=count+1 qc.crx(theta[count],qr[1],qr[0]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 return qc def circuit9(qc,qr,theta,L,repeat): #circuit 9 #theta is list of the parameters #theta length is (4)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.h(qr[i]) qc.cz(qr[3],qr[2]) qc.cz(qr[2],qr[1]) qc.cz(qr[1],qr[0]) for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 qc.cz(qr[1],qr[0]) qc.cz(qr[2],qr[1]) qc.cz(qr[3],qr[2]) for i in range(4): qc.h(qr[i]) return qc def circuit10(qc,qr,theta,L,repeat): #circuit 10 #theta is list of the parameters #theta length is (4)L+4 #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 for l in range(L): qc.cz(qr[3],qr[2]) qc.cz(qr[2],qr[1]) qc.cz(qr[1],qr[0]) qc.cz(qr[3],qr[0]) for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 qc.cz(qr[3],qr[0]) qc.cz(qr[1],qr[0]) qc.cz(qr[2],qr[1]) qc.cz(qr[3],qr[2]) for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 return qc def circuit11(qc,qr,theta,L,repeat): #circuit 11 #theta is list of the parameters #theta length is (12)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.cx(qr[1],qr[0]) qc.cx(qr[3],qr[2]) qc.ry(theta[count],qr[1]) count=count+1 qc.ry(theta[count],qr[2]) count=count+1 qc.rz(theta[count],qr[1]) count=count+1 qc.rz(theta[count],qr[2]) count=count+1 qc.cx(qr[2],qr[1]) if repeat!=0: qc.barrier(qr) for l in range(L): qc.cx(qr[2],qr[1]) qc.rz(theta[count],qr[2]) count=count+1 qc.rz(theta[count],qr[1]) count=count+1 qc.ry(theta[count],qr[2]) count=count+1 qc.ry(theta[count],qr[1]) count=count+1 qc.cx(qr[3],qr[2]) qc.cx(qr[1],qr[0]) for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 return qc def circuit12(qc,qr,theta,L,repeat): #circuit 12 #theta is list of the parameters #theta length is (12)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.cz(qr[1],qr[0]) qc.cz(qr[3],qr[2]) qc.ry(theta[count],qr[1]) count=count+1 qc.ry(theta[count],qr[2]) count=count+1 qc.rz(theta[count],qr[1]) count=count+1 qc.rz(theta[count],qr[2]) count=count+1 qc.cz(qr[2],qr[1]) if repeat!=0: qc.barrier(qr) for l in range(L): qc.cz(qr[2],qr[1]) qc.rz(theta[count],qr[2]) count=count+1 qc.rz(theta[count],qr[1]) count=count+1 qc.ry(theta[count],qr[2]) count=count+1 qc.ry(theta[count],qr[1]) count=count+1 qc.cz(qr[3],qr[2]) qc.cz(qr[1],qr[0]) for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 return qc def circuit13(qc,qr,theta,L,repeat): #circuit 13 #theta is list of the parameters #theta length is (16)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 qc.crz(theta[count],qr[3],qr[0]) count=count+1 qc.crz(theta[count],qr[2],qr[3]) count=count+1 qc.crz(theta[count],qr[1],qr[2]) count=count+1 qc.crz(theta[count],qr[0],qr[1]) count=count+1 for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 qc.crz(theta[count],qr[3],qr[2]) count=count+1 qc.crz(theta[count],qr[0],qr[3]) count=count+1 qc.crz(theta[count],qr[1],qr[0]) count=count+1 qc.crz(theta[count],qr[2],qr[1]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): qc.crz(theta[count],qr[2],qr[1]) count=count+1 qc.crz(theta[count],qr[1],qr[0]) count=count+1 qc.crz(theta[count],qr[0],qr[3]) count=count+1 qc.crz(theta[count],qr[3],qr[2]) count=count+1 for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 qc.crz(theta[count],qr[0],qr[1]) count=count+1 qc.crz(theta[count],qr[1],qr[2]) count=count+1 qc.crz(theta[count],qr[2],qr[3]) count=count+1 qc.crz(theta[count],qr[3],qr[0]) count=count+1 for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 return qc def circuit14(qc,qr,theta,L,repeat): #circuit 14 #theta is list of the parameters #theta length is (16)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 qc.crx(theta[count],qr[3],qr[0]) count=count+1 qc.crx(theta[count],qr[2],qr[3]) count=count+1 qc.crx(theta[count],qr[1],qr[2]) count=count+1 qc.crx(theta[count],qr[0],qr[1]) count=count+1 for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 qc.crx(theta[count],qr[3],qr[2]) count=count+1 qc.crx(theta[count],qr[0],qr[3]) count=count+1 qc.crx(theta[count],qr[1],qr[0]) count=count+1 qc.crx(theta[count],qr[2],qr[1]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): qc.crx(theta[count],qr[2],qr[1]) count=count+1 qc.crx(theta[count],qr[1],qr[0]) count=count+1 qc.crx(theta[count],qr[0],qr[3]) count=count+1 qc.crx(theta[count],qr[3],qr[2]) count=count+1 for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 qc.crx(theta[count],qr[0],qr[1]) count=count+1 qc.crx(theta[count],qr[1],qr[2]) count=count+1 qc.crx(theta[count],qr[2],qr[3]) count=count+1 qc.crx(theta[count],qr[3],qr[0]) count=count+1 for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 return qc def circuit15(qc,qr,theta,L,repeat): #circuit 15 #theta is list of the parameters #theta length is (8)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 qc.cx(qr[3],qr[0]) qc.cx(qr[2],qr[3]) qc.cx(qr[1],qr[2]) qc.cx(qr[0],qr[1]) for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 qc.cx(qr[3],qr[2]) qc.cx(qr[0],qr[3]) qc.cx(qr[1],qr[0]) qc.cx(qr[2],qr[1]) if repeat!=0: qc.barrier(qr) for l in range(L): qc.cx(qr[2],qr[1]) qc.cx(qr[1],qr[0]) qc.cx(qr[0],qr[3]) qc.cx(qr[3],qr[2]) for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 qc.cx(qr[0],qr[1]) qc.cx(qr[1],qr[2]) qc.cx(qr[2],qr[3]) qc.cx(qr[3],qr[0]) for i in range(4): qc.ry(theta[count],qr[i]) count=count+1 return qc def circuit16(qc,qr,theta,L,repeat): #circuit 16 #theta is list of the parameters #theta length is (11)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.crz(theta[count],qr[1],qr[0]) count=count+1 qc.crz(theta[count],qr[3],qr[2]) count=count+1 qc.crz(theta[count],qr[2],qr[1]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): qc.crz(theta[count],qr[2],qr[1]) count=count+1 qc.crz(theta[count],qr[3],qr[2]) count=count+1 qc.crz(theta[count],qr[1],qr[0]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 return qc def circuit17(qc,qr,theta,L,repeat): #circuit 17 #theta is list of the parameters #theta length is (11)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.crx(theta[count],qr[1],qr[0]) count=count+1 qc.crx(theta[count],qr[3],qr[2]) count=count+1 qc.crx(theta[count],qr[2],qr[1]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): qc.crx(theta[count],qr[2],qr[1]) count=count+1 qc.crx(theta[count],qr[3],qr[2]) count=count+1 qc.crx(theta[count],qr[1],qr[0]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 return qc def circuit18(qc,qr,theta,L,repeat): #circuit 18 #theta is list of the parameters #theta length is (12)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.crz(theta[count],qr[3],qr[0]) count=count+1 qc.crz(theta[count],qr[2],qr[3]) count=count+1 qc.crz(theta[count],qr[1],qr[2]) count=count+1 qc.crz(theta[count],qr[0],qr[1]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): qc.crz(theta[count],qr[0],qr[1]) count=count+1 qc.crz(theta[count],qr[1],qr[2]) count=count+1 qc.crz(theta[count],qr[2],qr[3]) count=count+1 qc.crz(theta[count],qr[3],qr[0]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 return qc def circuit19(qc,qr,theta,L,repeat): #circuit 1 #theta is list of the parameters #theta length is (12)L #L is the number of repeatation # repeat will conjugate the first part and add next the the circuit for expressibility # 0:No, 1: Repeat count=0 for l in range(L): for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 qc.crx(theta[count],qr[3],qr[0]) count=count+1 qc.crx(theta[count],qr[2],qr[3]) count=count+1 qc.crx(theta[count],qr[1],qr[2]) count=count+1 qc.crx(theta[count],qr[0],qr[1]) count=count+1 if repeat!=0: qc.barrier(qr) for l in range(L): qc.crx(theta[count],qr[0],qr[1]) count=count+1 qc.crx(theta[count],qr[1],qr[2]) count=count+1 qc.crx(theta[count],qr[2],qr[3]) count=count+1 qc.crx(theta[count],qr[3],qr[0]) count=count+1 for i in range(4): qc.rz(theta[count],qr[i]) count=count+1 for i in range(4): qc.rx(theta[count],qr[i]) count=count+1 return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# If you introduce a list with less colors than bars, the color of the bars will # alternate following the sequence from the list. import numpy as np from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0, 1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) matrix = DensityMatrix(qc) plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import IBMQ, transpile from qiskit import QuantumCircuit from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram from qiskit.providers.fake_provider import FakeVigo device_backend = FakeVigo() # Construct quantum circuit circ = QuantumCircuit(3, 3) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.measure([0, 1, 2], [0, 1, 2]) sim_ideal = AerSimulator() # Execute and get counts result = sim_ideal.run(transpile(circ, sim_ideal)).result() counts = result.get_counts(0) plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state') sim_vigo = AerSimulator.from_backend(device_backend) # Transpile the circuit for the noisy basis gates tcirc = transpile(circ, sim_vigo) # Execute noisy simulation and get counts result_noise = sim_vigo.run(tcirc).result() counts_noise = result_noise.get_counts(0) plot_histogram(counts_noise, title="Counts for 3-qubit GHZ state with device noise model") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/AlphaMiyaL/Qiskit-Quantum-Journey
AlphaMiyaL
#Qiskit Categories #Terra - Foundation, where we build and test our circuit #Aer - Simulator, simulation of circuit theoretically #Ignis - Masks noise, helps understand/mitigate error #energy relaxation - scenario - leave qbit in energized state, will eventually relax to zero state #Measurement error mitigation from qiskit import * nqubits = 3 circuit = QuantumCircuit(nqubits, nqubits) circuit.h(0) circuit.cx(0,1) circuit.cx(1,2) circuit.measure([0,1,2], [0,1,2]) %matplotlib inline circuit.draw(output='mpl') #Aer Simulaton simulator = Aer.get_backend('qasm_simulator') sim_result = execute(circuit, backend=simulator, shots=1024).result() from qiskit.visualization import plot_histogram plot_histogram(sim_result.get_counts(circuit)) #Terra Real Hardware Execution IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') device = provider.get_backend('ibm_oslo') job = execute(circuit, backend=device, shots=1024) print(job.job_id()) from qiskit.tools.monitor import job_monitor job_monitor(job) device_result = job.result() plot_histogram(device_result.get_counts(circuit)) #Ignis Error Mitigation from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter) cal_circuits, state_labels = complete_meas_cal(qr = circuit.qregs[0], circlabel='measerrormitigationcal') cal_circuits[2].draw(output='mpl') len(cal_circuits) cal_job = execute(cal_circuits, backend = device, shots = 1024, optimization_level = 0 ) print(cal_job.job_id()) job_monitor(cal_job) cal_results = cal_job.result() plot_histogram( cal_results.get_counts(cal_circuits[3]) ) meas_fitter = CompleteMeasFitter(cal_results, state_labels) meas_fitter.plot_calibration() meas_filter = meas_fitter.filter mitigated_result = meas_filter.apply(device_result) device_counts = device_result.get_counts(circuit) mitigated_counts = mitigated_result.get_counts(circuit) plot_histogram([device_counts, mitigated_counts], legend =['device, noisy', 'device, mitigated']) #Another example using a different circuit circuit2 = QuantumCircuit(3,3) circuit2.x(1) circuit2.h(0) circuit2.cx(0,1) circuit2.cx(1,2) circuit2.measure([0,1,2],[0,1,2]) circuit2.draw(output = 'mpl') plot_histogram( execute(circuit2, backend=simulator, shots = 1024).result().get_counts(circuit2) ) device_counts_2 = execute(circuit2, backend = device, shots=1024).result().get_counts(circuit2) plot_histogram(device_counts_2) device_mitigated_counts_2 = meas_filter.apply(device_counts_2) plot_histogram(device_mitigated_counts_2)
https://github.com/abbarreto/qiskit3
abbarreto
from qiskit_ibm_runtime import QiskitRuntimeService # Save an IBM Quantum account. QiskitRuntimeService.save_account(channel='ibm_quantum', #channel='ibm_cloud', token='17efde49764005e8eeb00dd065d44bc208778be72d44b475e508d20504818786f842988b0e506515c78debdd1b0c4b570717863db5e4f85569fb43c4c8626b8a', overwrite=True) service = QiskitRuntimeService( channel='ibm_quantum', instance='ibm-q/open/main' #instance='ibm-q-research-2/federal-uni-sant-1/main' ) program_inputs = {'iterations': 1} options = {"backend_name": "ibmq_qasm_simulator"} job = service.run(program_id="hello-world", options=options, inputs=program_inputs ) #print(f"job id: {job.job_id()}") result = job.result() print(result) backend = service.get_backend("ibmq_qasm_simulator") from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp from qiskit.primitives import Estimator from qiskit import QuantumCircuit #circuit = random_circuit(2, 2, seed=1).decompose(reps=1) circuit = QuantumCircuit(2) circuit.x(0) circuit.draw(output='mpl') observable = SparsePauliOp("IZ") # ordem ...210 #options = {"backend_name": "ibmq_qasm_simulator"} estimator = Estimator()#options=options) job = estimator.run(circuit, observable) result = job.result() display(circuit.draw("mpl")) print(f" > Observable: {observable.paulis}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") import math qc1 = QuantumCircuit(2); qc2 = QuantumCircuit(2) qc1.h(1) qc2.h(0); qc2.p(-math.pi/2, 0) circuits = ( #random_circuit(2, 2, seed=0).decompose(reps=1), #random_circuit(2, 2, seed=1).decompose(reps=1), qc1, qc2 ) observables = ( SparsePauliOp("XZ"), SparsePauliOp("IY"), ) estimator = Estimator() job = estimator.run(circuits, observables) result = job.result() [display(cir.draw("mpl")) for cir in circuits] print(f" > Observables: {[obs.paulis for obs in observables]}") print(f" > Expectation values: {result.values.tolist()}") print(f" > Metadata: {result.metadata}") circuits = ( random_circuit(2, 2, seed=0).decompose(reps=1), random_circuit(2, 2, seed=1).decompose(reps=1), ) observables = ( SparsePauliOp("XZ"), SparsePauliOp("IY"), ) estimator = Estimator() job_0 = estimator.run(circuits[0], observables[0]) job_1 = estimator.run(circuits[1], observables[1]) result_0 = job_0.result() result_1 = job_1.result() [display(cir.draw("mpl")) for cir in circuits] print(f" > Observables: {[obs.paulis for obs in observables]}") print(f" > Expectation values [0]: {result_0.values.tolist()[0]}") print(f" > Metadata [0]: {result_0.metadata[0]}") print(f" > Expectation values [1]: {result_1.values.tolist()[0]}") print(f" > Metadata [1]: {result_1.metadata[0]}") from qiskit.circuit.library import RealAmplitudes circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1) observable = SparsePauliOp("ZI") parameter_values = [0, 1, 2, 3, 4, 5] estimator = Estimator() job = estimator.run(circuit, observable, parameter_values) result = job.result() display(circuit.draw("mpl")) print(f" > Observable: {observable.paulis}") print(f" > Parameter values: {parameter_values}") print(f" > Expectation value: {result.values}") print(f" > Metadata: {result.metadata[0]}") circuit = RealAmplitudes(num_qubits=2, reps=1).decompose(reps=1) display(circuit.draw("mpl")) from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp from qiskit_ibm_runtime import QiskitRuntimeService, Session, Estimator, Options circuit = random_circuit(2, 2, seed=1).decompose(reps=1) observable = SparsePauliOp("IY") options = Options() options.optimization_level = 2 options.resilience_level = 2 service = QiskitRuntimeService() with Session(service=service, backend="ibmq_qasm_simulator") as session: estimator = Estimator(session=session, options=options) job = estimator.run(circuit, observable) result = job.result() display(circuit.draw("mpl")) print(f" > Observable: {observable.paulis}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp from qiskit_ibm_runtime import QiskitRuntimeService, Session, Estimator, Options circuit = random_circuit(2, 2, seed=1).decompose(reps=1) observable = SparsePauliOp("IY") options = Options() options.optimization_level = 2 options.resilience_level = 2 service = QiskitRuntimeService() with Session(service=service, backend="ibmq_belem") as session: estimator = Estimator(session=session, options=options) job = estimator.run(circuit, observable) result = job.result() display(circuit.draw("mpl")) print(f" > Observable: {observable.paulis}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Session, Options circuit = random_circuit(2, 2, seed=1).decompose(reps=1) observable = SparsePauliOp("IY") options = Options() options.optimization_level = 2 options.resilience_level = 2 service = QiskitRuntimeService() backend = service.get_backend("ibmq_belem") with Session(service=service, backend=backend): estimator = Estimator() job = estimator.run(circuit, observable) result = job.result() display(circuit.draw("mpl")) print(f" > Observable: {observable.paulis}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit.circuit.random import random_circuit from qiskit.primitives import Sampler circuit = random_circuit(2, 2, seed=1).decompose(reps=1) circuit.measure_all() sampler = Sampler() job = sampler.run(circuit) result = job.result() display(circuit.draw("mpl")) print(f" > Quasi probability distribution: {result.quasi_dists[0]}") #print(f" > Metadata: {result.metadata[0]}") #print(result.quasi_dists,result.quasi_dists[0][1]) print(result.quasi_dists[0][0]+result.quasi_dists[0][1]+result.quasi_dists[0][2]+result.quasi_dists[0][3]) from qiskit.circuit.random import random_circuit from qiskit.primitives import Sampler circuits = ( random_circuit(2, 2, seed=0).decompose(reps=1), random_circuit(2, 2, seed=1).decompose(reps=1), ) [c.measure_all() for c in circuits] sampler = Sampler() job = sampler.run(circuits) result = job.result() [display(cir.draw("mpl")) for cir in circuits] print(f" > Quasi probability distributions: {result.quasi_dists}") #print(f" > Metadata: {result.metadata}") from qiskit.circuit.library import RealAmplitudes # RealAmplitudes is one way to generate a parametrized circuit from qiskit.primitives import Sampler circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1) circuit.measure_all() parameter_values = [0, 1, 2, 3, 4, 5] sampler = Sampler() job = sampler.run(circuit, parameter_values) result = job.result() display(circuit.draw("mpl")) print(f" > Parameter values: {parameter_values}") print(f" > Quasi probability distribution: {result.quasi_dists[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit.circuit.random import random_circuit from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Options backend = service.get_backend("ibmq_qasm_simulator") circuit = random_circuit(2, 2, seed=2).decompose(reps=1) circuit.measure_all() options = Options() options.optimization_level = 2 options.resilience_level = 0 service = QiskitRuntimeService() with Session(service=service, backend=backend): sampler = Sampler() job = sampler.run(circuit) result = job.result() display(circuit.draw("mpl")) print(f" > Quasi probability distribution: {result.quasi_dists[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit.circuit.random import random_circuit from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Options backend = service.get_backend("ibmq_quito") circuit = random_circuit(2, 2, seed=2).decompose(reps=1) circuit.measure_all() options = Options() options.optimization_level = 2 options.resilience_level = 0 service = QiskitRuntimeService() with Session(service=service, backend=backend): sampler = Sampler() job = sampler.run(circuit) print(job.job_id()) result = job.result() display(circuit.draw("mpl")) print(f" > Quasi probability distribution: {result.quasi_dists[0]}") print(f" > Metadata: {result.metadata[0]}")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from os import listdir as ld files = [ff for ff in ld('bronze') if ff[:1] == 'B'] sols = [ff for ff in ld('bronze-solutions') if ff[:1] == 'B'] files.sort() sols.sort() for ss in files: print('- ['+ss+'](bronze/'+ss+')') tt = [ff for ff in sols if ff[:3]==ss[:3]] if len(tt) > 0: print('<br> *solutions:* [`'+tt[0]+'`](bronze-solutions/'+tt[0]+')')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 42 from qiskit.circuit import Parameter from qiskit import QuantumCircuit params1 = [Parameter("input1"), Parameter("weight1")] qc1 = QuantumCircuit(1) qc1.h(0) qc1.ry(params1[0], 0) qc1.rx(params1[1], 0) qc1.draw("mpl") from qiskit.quantum_info import SparsePauliOp observable1 = SparsePauliOp.from_list([("Y" * qc1.num_qubits, 1)]) from qiskit_machine_learning.neural_networks import EstimatorQNN estimator_qnn = EstimatorQNN( circuit=qc1, observables=observable1, input_params=[params1[0]], weight_params=[params1[1]] ) estimator_qnn from qiskit.circuit import ParameterVector inputs2 = ParameterVector("input", 2) weights2 = ParameterVector("weight", 4) print(f"input parameters: {[str(item) for item in inputs2.params]}") print(f"weight parameters: {[str(item) for item in weights2.params]}") qc2 = QuantumCircuit(2) qc2.ry(inputs2[0], 0) qc2.ry(inputs2[1], 1) qc2.cx(0, 1) qc2.ry(weights2[0], 0) qc2.ry(weights2[1], 1) qc2.cx(0, 1) qc2.ry(weights2[2], 0) qc2.ry(weights2[3], 1) qc2.draw(output="mpl") from qiskit_machine_learning.neural_networks import SamplerQNN sampler_qnn = SamplerQNN(circuit=qc2, input_params=inputs2, weight_params=weights2) sampler_qnn estimator_qnn_input = algorithm_globals.random.random(estimator_qnn.num_inputs) estimator_qnn_weights = algorithm_globals.random.random(estimator_qnn.num_weights) print( f"Number of input features for EstimatorQNN: {estimator_qnn.num_inputs} \nInput: {estimator_qnn_input}" ) print( f"Number of trainable weights for EstimatorQNN: {estimator_qnn.num_weights} \nWeights: {estimator_qnn_weights}" ) sampler_qnn_input = algorithm_globals.random.random(sampler_qnn.num_inputs) sampler_qnn_weights = algorithm_globals.random.random(sampler_qnn.num_weights) print( f"Number of input features for SamplerQNN: {sampler_qnn.num_inputs} \nInput: {sampler_qnn_input}" ) print( f"Number of trainable weights for SamplerQNN: {sampler_qnn.num_weights} \nWeights: {sampler_qnn_weights}" ) estimator_qnn_forward = estimator_qnn.forward(estimator_qnn_input, estimator_qnn_weights) print( f"Forward pass result for EstimatorQNN: {estimator_qnn_forward}. \nShape: {estimator_qnn_forward.shape}" ) sampler_qnn_forward = sampler_qnn.forward(sampler_qnn_input, sampler_qnn_weights) print( f"Forward pass result for SamplerQNN: {sampler_qnn_forward}. \nShape: {sampler_qnn_forward.shape}" ) estimator_qnn_forward_batched = estimator_qnn.forward( [estimator_qnn_input, estimator_qnn_input], estimator_qnn_weights ) print( f"Forward pass result for EstimatorQNN: {estimator_qnn_forward_batched}. \nShape: {estimator_qnn_forward_batched.shape}" ) sampler_qnn_forward_batched = sampler_qnn.forward( [sampler_qnn_input, sampler_qnn_input], sampler_qnn_weights ) print( f"Forward pass result for SamplerQNN: {sampler_qnn_forward_batched}. \nShape: {sampler_qnn_forward_batched.shape}" ) estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward( estimator_qnn_input, estimator_qnn_weights ) print( f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad}" ) print( f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}" ) sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward( sampler_qnn_input, sampler_qnn_weights ) print( f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) estimator_qnn.input_gradients = True sampler_qnn.input_gradients = True estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward( estimator_qnn_input, estimator_qnn_weights ) print( f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad.shape}" ) print( f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}" ) sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward( sampler_qnn_input, sampler_qnn_weights ) print( f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad.shape}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) observable2 = SparsePauliOp.from_list([("Z" * qc1.num_qubits, 1)]) estimator_qnn2 = EstimatorQNN( circuit=qc1, observables=[observable1, observable2], input_params=[params1[0]], weight_params=[params1[1]], ) estimator_qnn_forward2 = estimator_qnn2.forward(estimator_qnn_input, estimator_qnn_weights) estimator_qnn_input_grad2, estimator_qnn_weight_grad2 = estimator_qnn2.backward( estimator_qnn_input, estimator_qnn_weights ) print(f"Forward output for EstimatorQNN1: {estimator_qnn_forward.shape}") print(f"Forward output for EstimatorQNN2: {estimator_qnn_forward2.shape}") print(f"Backward output for EstimatorQNN1: {estimator_qnn_weight_grad.shape}") print(f"Backward output for EstimatorQNN2: {estimator_qnn_weight_grad2.shape}") parity = lambda x: "{:b}".format(x).count("1") % 2 output_shape = 2 # parity = 0, 1 sampler_qnn2 = SamplerQNN( circuit=qc2, input_params=inputs2, weight_params=weights2, interpret=parity, output_shape=output_shape, ) sampler_qnn_forward2 = sampler_qnn2.forward(sampler_qnn_input, sampler_qnn_weights) sampler_qnn_input_grad2, sampler_qnn_weight_grad2 = sampler_qnn2.backward( sampler_qnn_input, sampler_qnn_weights ) print(f"Forward output for SamplerQNN1: {sampler_qnn_forward.shape}") print(f"Forward output for SamplerQNN2: {sampler_qnn_forward2.shape}") print(f"Backward output for SamplerQNN1: {sampler_qnn_weight_grad.shape}") print(f"Backward output for SamplerQNN2: {sampler_qnn_weight_grad2.shape}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/rickapocalypse/final_paper_qiskit_sat
rickapocalypse
from qiskit import* from qiskit.providers.aer import QasmSimulator from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt quantum_register = QuantumRegister(2) # Linhas do circuito / numeros de Qbit no circuito """ Para medir, em mecanica quântica, ao medir um Qbit nós destruimos a informação daquele estado e armazenamos ela em um bit clássico """ classic_register = ClassicalRegister(2) first_circuit = QuantumCircuit(quantum_register, classic_register) # Constrói o circuito first_circuit.draw(output = 'mpl') # Desenha o circuito, funciona no app da IBM first_circuit.h(quantum_register[0]) # Aplicando a primeira gate no primeira linha, gate hadarmat # Aplicando a porta CNOT ### first_circuit.draw(output = 'mpl') ### first_circuit.cx(quantum_register[0], quantum_register[1]) #CNOT faz operação tensorial entre o Qbit #de controle na linha zero, e o outro é o Qbit alvo ### first_circuit.draw(output = 'mpl') ### first_circuit.measure(quantum_register, classic_register) # para extrair a medida ### first_circuit.draw(output = 'mpl') ### simulator = QasmSimulator() # Simulador que vai realizar os calculos para nós result = execute(first_circuit, backend= simulator).result() counts = result.get_counts(first_circuit) first_circuit.draw(output='mpl') plot_histogram(counts) plt.ylabel(counts) plt.show() """ IBMQ.load_account() host = IBMQ.get_provider('ibm-q') quantum_computer = host.get_backend('ibmq_belem') result_qcomputer = execute(first_circuit, backend= quantum_computer) job_monitor(result_qcomputer) result = result_qcomputer.result() plot_histogram(result.get_counts(first_circuit)) plt.ylabel(counts) plt.show() """
https://github.com/EdoardoZappia/Qiskit-Primitive
EdoardoZappia
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram from qiskit.quantum_info import Statevector import numpy as np import matplotlib backend = BasicAer.get_backend('qasm_simulator') shots = 1024 style = {'backgroundcolor': 'lightyellow'} # Style of the circuits qreg1 = QuantumRegister(2) # The quantum register of the qubits, in this case 2 qubits register1 = ClassicalRegister(1) qc = QuantumCircuit(qreg1, register1) #qc.x(0) qc.x(1) qc.barrier() qc.draw(output='mpl', style=style) qc.h(0) qc.h(1) qc.barrier() qc.draw(output='mpl', style=style) qc.cx(0,1) qc.barrier() qc.draw(output='mpl', style=style) qc.h(0) qc.draw(output='mpl', style=style) qc.measure(qreg1[0],register1) qc.draw(output='mpl', style=style) results = execute(qc, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) def oracleBalance1(qcir): qcir.cx(0,1) qcir.barrier() return qcir def oracleBalance2(qcir): qcir.x(1) qcir.cx(0,1) qcir.barrier() return qcir def oracleConstant1(qcir): qcir.x(1) qcir.barrier() return qcir def oracleConstant2(qcir): qcir.barrier() return qcir def deutsch(oracle): Qreg = QuantumRegister(2) Creg = ClassicalRegister(1) qcirc = QuantumCircuit(Qreg, Creg) qcirc.x(1) qcirc.h(0) qcirc.h(1) qcirc.barrier() qcirc = oracle(qcirc) qcirc.h(0) qcirc.barrier() qcirc.measure(Qreg[0],Creg) return qcirc resultBalanced1 = deutsch(oracleBalance1) resultBalanced1.draw(output='mpl', style=style) resultsB1 = execute(resultBalanced1, backend=backend, shots=shots).result() answerB1 = resultsB1.get_counts() plot_histogram(answerB1) resultBalanced2 = deutsch(oracleBalance1) resultBalanced2.draw(output='mpl', style=style) resultsB2 = execute(resultBalanced2, backend=backend, shots=shots).result() answerB2 = resultsB2.get_counts() plot_histogram(answerB2) resultConstant1 = deutsch(oracleConstant1) resultConstant1.draw(output='mpl', style=style) resultsC1= execute(resultConstant1, backend=backend, shots=shots).result() answerC1 = resultsC1.get_counts() plot_histogram(answerC1) resultConstant2 = deutsch(oracleConstant2) resultConstant2.draw(output='mpl', style=style) resultsC2= execute(resultConstant2, backend=backend, shots=shots).result() answerC2 = resultsC2.get_counts() plot_histogram(answerC2)
https://github.com/tanishabassan/QAOA-Maxcut
tanishabassan
import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import matplotlib.axes as axes import numpy as np from scipy import linalg as la from itertools import permutations from functools import partial import networkx as nx # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram # import optimization tools from qiskit.tools.apps.optimization import trial_circuit_ry, SPSA_optimization, SPSA_calibration from qiskit.tools.apps.optimization import Energy_Estimate, make_Hamiltonian, eval_hamiltonian, group_paulis from qiskit.tools.qi.pauli import Pauli # Random choice of the cities/nodes N = 4 xc = (np.random.rand(N)-0.5)*10 yc = (np.random.rand(N)-0.5)*10 plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i,(xc[i]+0.15,yc[i]),size=16,color='r') plt.show() # Getting the distances w = np.zeros([N,N]) for i in range(N): for j in range(N): w[i,j]= np.sqrt((xc[i]-xc[j])**2+(yc[i]-yc[j])**2) a=list(permutations(range(1,N))) last_best_distance = 10000000 for i in a: distance = 0 pre_j = 0 for j in i: distance = distance + w[j,pre_j] pre_j = j distance = distance + w[0,pre_j] order = (0,) + i if distance < last_best_distance: best_order = order last_best_distance = distance print('order = ' + str(order) + ' Distance = ' + str(distance)) best_distance_brute = last_best_distance best_order_brute = best_order plt.scatter(xc, yc) xbest = np.array([xc[i] for i in best_order_brute]) xbest = np.append(xbest,xbest[0]) ybest = np.array([yc[i] for i in best_order_brute]) ybest = np.append(ybest,ybest[0]) plt.plot(xbest, ybest, 'b.-', ms = 40) plt.plot(xc[0], yc[0], 'r*', ms = 20) for i in range(len(xc)): plt.annotate(i,(xc[i]+0.2,yc[i]),size=16,color='r') plt.show() print('Best order from brute force = ' + str(best_order_brute) + ' with total distance = ' + str(best_distance_brute)) n=(N-1)**2 # number of qubits A = np.max(w)*100 # A parameter of cost function # takes the part of w matrix excluding the 0-th point, which is the starting one wsave = w[1:N,1:N] # nearest-neighbor interaction matrix for the prospective cycle (p,p+1 interaction) shift = np.zeros([N-1,N-1]) shift = la.toeplitz([0,1,0], [0,1,0])/2 # the first and last point of the TSP problem are fixed by initial and final conditions firststep = np.zeros([N-1]) firststep[0] = 1; laststep = np.zeros([N-1]) laststep[N-2] = 1; # The binary variables that define a path live in a tensor product space of position and ordering indices # Q defines the interactions between variables Q = np.kron(shift,wsave) + np.kron(A*np.ones((N-1, N-1)), np.identity(N-1)) + np.kron(np.identity(N-1),A*np.ones((N-1, N-1))) # G defines the contribution from the individual variables G = np.kron(firststep,w[0,1:N]) + np.kron(laststep,w[1:N,0]) - 4*A*np.kron(np.ones(N-1),np.ones(N-1)) # M is the constant offset M = 2*A*(N-1) # Evaluates the cost distance from a binary representation of a path fun = lambda x: np.dot(np.around(x),np.dot(Q,np.around(x)))+np.dot(G,np.around(x))+M def get_order_tsp(x): # This function takes in a TSP state, an array of (N-1)^2 binary variables, and returns the # corresponding travelling path associated to it order = [0] for p in range(N-1): for j in range(N-1): if x[(N-1)*p+j]==1: order.append(j+1) return order def get_x_tsp(order): # This function takes in a traveling path and returns a TSP state, in the form of an array of (N-1)^2 # binary variables x = np.zeros((len(order)-1)**2) for j in range(1,len(order)): p=order[j] x[(N-1)*(j-1)+(p-1)]=1 return x # Checking if the best results from the brute force approach are correct for the mapped system of binary variables # Conversion from a path to a binary variable array xopt_brute = get_x_tsp(best_order_brute) print('Best path from brute force mapped to binary variables: \n') print(xopt_brute) flag = False for i in range(100000): rd = np.random.randint(2, size=n) if fun(rd) < (best_distance_brute - 0.0001): print('\n A random solution is better than the brute-force one. The path measures') print(fun(rd)) flag = True if flag == False: print('\nCheck with 10^5 random solutions: the brute-force solution mapped to binary variables is correct.\n') print('Shortest path evaluated with binary variables: ') print(fun(xopt_brute)) # Optimization with simulated annealing initial_x = np.random.randint(2, size=n) cost = fun(initial_x) x = np.copy(initial_x) alpha = 0.999 temp = 10 for j in range(10000): # pick a random index and flip the bit associated with it flip = np.random.randint(len(x)) new_x = np.copy(x) new_x[flip] = (x[flip] + 1) % 2 # compute cost function with flipped bit new_cost = fun(new_x) if np.exp(-(new_cost - cost) / temp) > np.random.rand(): x = np.copy(new_x) cost = new_cost temp = temp * alpha print('distance = ' + str(cost) + ' x_solution = ' + str(x) + ', final temperature= ' + str(temp)) best_order_sim_ann = get_order_tsp(x) plt.scatter(xc, yc) xbest = np.array([xc[i] for i in best_order_sim_ann]) xbest = np.append(xbest, xbest[0]) ybest = np.array([yc[i] for i in best_order_sim_ann]) ybest = np.append(ybest, ybest[0]) plt.plot(xbest, ybest, 'b.-', ms=40) plt.plot(xc[0], yc[0], 'r*', ms=20) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.15, yc[i]), size=16, color='r') plt.show() print('Best order from simulated annealing = ' + str(best_order_sim_ann) + ' with total distance = ' + str(cost)) # Defining the new matrices in the Z-basis Iv=np.ones((N-1)**2) Qz = (Q/4) Gz =( -G/2-np.dot(Iv,Q/4)-np.dot(Q/4,Iv)) Mz = (M+np.dot(G/2,Iv)+np.dot(Iv,np.dot(Q/4,Iv))) Mz = Mz + np.trace(Qz) Qz = Qz - np.diag(np.diag(Qz)) # Recall the change of variables is # x = (1-z)/2 # z = -2x+1 z= -(2*xopt_brute)+Iv for i in range(1000): rd = 1-2*np.random.randint(2, size=n) if np.dot(rd,np.dot(Qz,rd))+np.dot(Gz,rd)+Mz < (best_distance_brute-0.0001): print(np.dot(rd,np.dot(Qz,rd))+np.dot(Gz,rd)+Mz) # Getting the Hamiltonian in the form of a list of Pauli terms pauli_list = [] for i in range(n): if Gz[i] != 0: wp = np.zeros(n) vp = np.zeros(n) vp[i] = 1 pauli_list.append((Gz[i], Pauli(vp, wp))) for i in range(n): for j in range(i): if Qz[i, j] != 0: wp = np.zeros(n) vp = np.zeros(n) vp[i] = 1 vp[j] = 1 pauli_list.append((2 * Qz[i, j], Pauli(vp, wp))) pauli_list.append((Mz, Pauli(np.zeros(n), np.zeros(n)))) # Making the Hamiltonian as a full matrix and finding its lowest eigenvalue H = make_Hamiltonian(pauli_list) we, v = la.eigh(H, eigvals=(0, 0)) exact = we[0] print(exact) H = np.diag(H) # Setting up a quantum program and connecting to the Quantum Experience API Q_program = QuantumProgram() # set the APIToken and API url Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # Optimization of the TSP using a quantum computer # Quantum circuit parameters # the entangler step is made of two-qubit gates between a control and target qubit, control: [target] coupling_map = None # the coupling_maps gates allowed on the device entangler_map = {0: [1], 1: [2], 2: [3], 3: [4], 4: [5], 5: [6], 6: [7], 7: [8]} # the layout of the qubits initial_layout = None # the backend used for the quantum computation backend = 'local_qasm_simulator' # Total number of trial steps used in the optimization max_trials = 1500; n = 9 # the number of qubits # Depth of the quantum circuit that prepares the trial state m = 5 # initial starting point for the control angles initial_theta = np.random.randn(m * n) # number of shots for each evaluation of the cost function (shots=1 corresponds to perfect evaluation, # only available on the simulator) shots = 1 # choose to plot the results of the optimizations every save_steps save_step = 1 """ ########################## RUN OPTIMIZATION ####################### if shots == 1: obj_funct_partial = partial(obj_funct, Q_program, pauli_list, entangler_map, coupling_map, initial_layout, n, m, backend, shots) initial_c=0.01 else: obj_funct_partial = partial(obj_funct, Q_program, pauli_list, entangler_map, coupling_map, initial_layout, n, m, backenddevice, shots) initial_c=0.1 target_update=2*np.pi*0.1 SPSA_parameters=SPSA_calibration(obj_funct_partial,initial_theta,initial_c,target_update,25) print ('SPSA parameters = ' + str(SPSA_parameters)) best_distance_quantum, best_theta, cost_plus, cost_minus,_,_ = SPSA_optimization(obj_funct_partial, initial_theta, SPSA_parameters, max_trials, save_step) """ def cost_function(Q_program, H, n, m, entangler_map, shots, device, theta): return eval_hamiltonian(Q_program, H, trial_circuit_ry(n, m, theta, entangler_map, None, False), shots, device).real initial_c = 0.1 target_update = 2 * np.pi * 0.1 save_step = 1 if shots != 1: H = group_paulis(pauli_list) SPSA_params = SPSA_calibration(partial(cost_function, Q_program, H, n, m, entangler_map, shots, backend), initial_theta, initial_c, target_update, 25) best_distance_quantum, best_theta, cost_plus, cost_minus, _, _ = SPSA_optimization( partial(cost_function, Q_program, H, n, m, entangler_map, shots, backend), initial_theta, SPSA_params, max_trials, save_step,1); """ ########################## PLOT RESULTS #######################""" plt.plot(np.arange(0, max_trials,save_step),cost_plus,label='C(theta_plus)') plt.plot(np.arange(0, max_trials,save_step),cost_minus,label='C(theta_minus)') plt.plot(np.arange(0, max_trials,save_step),(np.ones(max_trials//save_step)*best_distance_quantum), label='Final Cost') plt.plot(np.arange(0, max_trials,save_step),np.ones(max_trials//save_step)*exact, label='Exact Cost') plt.legend() plt.xlabel('Number of trials') plt.ylabel('Cost') # Sampling from the quantum state generated with the optimal angles from the quantum optimization shots = 100 circuits = ['final_circuit'] Q_program.add_circuit('final_circuit', trial_circuit_ry(n, m, best_theta, entangler_map,None,True)) result = Q_program.execute(circuits, backend=backend, shots=shots, coupling_map=coupling_map, initial_layout=initial_layout) data = result.get_counts('final_circuit') plot_histogram(data,5) # Getting path and total distance from the largest component of the quantum state max_value = max(data.values()) # maximum value max_keys = [k for k, v in data.items() if v == max_value] # getting all keys containing the `maximum` x_quantum = np.zeros(n) for bit in range(n): if max_keys[0][bit] == '1': x_quantum[bit] = 1 quantum_order = get_order_tsp(list(map(int, x_quantum))) best_distance_quantum_amp = fun(x_quantum) plt.scatter(xc, yc) xbest = np.array([xc[i] for i in quantum_order]) xbest = np.append(xbest, xbest[0]) ybest = np.array([yc[i] for i in quantum_order]) ybest = np.append(ybest, ybest[0]) plt.plot(xbest, ybest, 'b.-', ms=40) plt.plot(xc[0], yc[0], 'r*', ms=20) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.15, yc[i]), size=14, color='r') plt.show() print('Best order from quantum optimization is = ' + str(quantum_order) + ' with total distance = ' + str( best_distance_quantum_amp))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.draw('mpl')
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
from qiskit_chemistry import FermionicOperator, QMolecule from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD from qiskit_chemistry import QMolecule as qm from qiskit_aqua.components.optimizers import COBYLA from qiskit_aqua import Operator from qiskit_aqua.algorithms import VQE, ExactEigensolver from qiskit import Aer from scipy import linalg as la import numpy as np import yaml as yml from yaml import SafeLoader as Loader import os from dask.distributed import Client, LocalCluster import dask import Load_Hamiltonians as lh #Define functions that can be used in parallel algorithm def read_variables(root_dir, file1, file2): Ham_data_file = str(os.path.join(root_dir, file1)) OrbE_data_file = str(os.path.join(root_dir + '/DOWNFOLDED_ORBITAL_ENERGIES', file2)) try: doc_nw = open(Ham_data_file, 'r') doc_orbe = open(OrbE_data_file, 'r') dat = yml.load(doc_nw, Loader) content_orbe = doc_orbe.readlines() finally: doc_nw.close() doc_orbe.close() # Import all the data from a yaml file print('Getting data') #Importing the integrals one_e = dat['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values'] two_e = dat['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values'] num_spatial_orbitals = dat['integral_sets'][0]['n_orbitals'] coulomb_energy = dat['integral_sets'][0]['coulomb_repulsion']['value'] num_orbitals = 2 * num_spatial_orbitals num_particles = dat['integral_sets'][0]['n_electrons'] d = 2 * dat['integral_sets'][0]['geometry']['atoms'][1]['coords'][2] print('Bond distance is {}'.format(d)) if map_type == 'parity': # For two-qubit reduction num_qubits = num_orbitals - 2 else: num_qubits = num_orbitals # Populating the QMolecule class with the data to make calculations easier - No need for returns # qm.num_orbitals = num_spatial_orbitals # qm.num_alpha = num_particles // 2 # qm.num_beta = num_particles // 2 # qm.core_orbitals = 0 # qm.nuclear_repulsion_energy = coulomb_energy # qm.hf_energy = dat['integral_sets'][0]['scf_energy']['value'] ###################Get Orbital Energies from FOCK file######################## orbital_energies = [] found = False count = 0 for line in content_orbe: if 'Eigenvalues:' in line.split()[0]: found = True if found and len(line.split()) > 1: orbital_energies.append(float(line.split()[1])) count += 1 if count >= num_spatial_orbitals: break qm.orbital_energies = orbital_energies return num_spatial_orbitals, num_orbitals, num_particles, num_qubits, d, coulomb_energy, one_e, two_e def get_molecular_qubit_operator(one_ints, two_ints, n_orbitals, thresh, qubit_map): # Getting spatial integrals and spin integrals to construct Hamiltonian one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_ints, two_ints, n_orbitals) h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals, two_electron_spatial_integrals, n_orbitals, thresh) # For the MP2 Calculation qm.mo_eri_ints = two_electron_spatial_integrals # Constructing the fermion operator and qubit operator from integrals data fop = FermionicOperator(h1, h2) qop_paulis = fop.mapping(qubit_map) return qop_paulis def run_vqe(pauli_operator, num_orbitals, num_particles, num_qubits, coulomb_energy, mapping, backend): var_energy = 0 #Get Variational form and intial state initial_state = HartreeFock(num_qubits, num_orbitals, num_particles, mapping, two_qubit_reduction=False) var_op = UCCSD(num_qubits, 1, num_orbitals, num_particles, active_occupied=None, active_unoccupied=None, initial_state=initial_state, qubit_mapping=mapping, mp2_reduction=True) ######################## VQE RESULT ############################### # setup a classical optimizer for VQE max_eval = 200 optimizer = COBYLA(maxiter=max_eval, disp=True, tol=1e-3) print('Doing VQE') algorithm = VQE(pauli_operator, var_op, optimizer,'paulis', initial_point=None, ) result = algorithm.run(backend) var_energy = result['energy'] + coulomb_energy # vqe_params = result['opt_params'] return var_energy def run_exact(pauli_operator, coulomb_energy): exact_eigensolver = ExactEigensolver(pauli_operator, k=1) ret = exact_eigensolver.run() print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real)) print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + coulomb_energy)) ed_energy = ret['eigvals'][0].real + coulomb_energy return ed_energy ##Carefully upgrade terra to see if qasm/state-vector simulator perform quicker.## #################### WALK ROOT DIR ############################ root_dir = 'IntegralData/vqe-data-master/Li2_cc-pVTZ/4_ORBITALS' data_file_list = [] data_file_list_oe = [] for dirName, subdirList, fileList in os.walk(root_dir): print('Found directory: %s' % dirName) for fname in sorted(fileList): if fname.endswith('.yaml'): data_file_list.append(fname) if fname.endswith('.FOCK'): data_file_list_oe.append(fname) #This 'del' is four the 4-orbital case since the OEs are missing for the distance 13... #This should be resolved for the future del data_file_list[-1] #I added an x in front of the 10s for distance to force the sorting, else it sees 13 as 1 #If any distance is in the 100s (unlikely) then add a 'y' in front of dist in file name ############################################################### ############# Output Files to Plot stuff ############### print(data_file_list) Fout = open('Li2_ExactEnergies_wMP2_4-orbitals_061219.dat',"w") ########################################################### #Variables that can be assigned outside of Loop map_type = str('jordan_wigner') truncation_threshold = 0.01 ################# IBM BACKEND ##################### backend1 = Aer.get_backend('statevector_simulator') backend2 = Aer.get_backend('qasm_simulator') ################################################### @dask.delayed def final(root_dir, file1, file2): spatial_orbitals, spin_orbitals, particle_num, qubits_num, dist, nuclear_energy, one_electron_import, two_electron_import = read_variables( root_dir, file1, file2) qop = get_molecular_qubit_operator(one_electron_import, two_electron_import, spatial_orbitals, truncation_threshold, map_type) # vqe_energy = run_vqe(qop, spin_orbitals, particle_num, qubits_num, nuclear_energy, map_type, backend1) vqe_energy = 0 exact_energy = run_exact(qop, nuclear_energy) my_info = [dist, exact_energy, vqe_energy] return my_info # print(output_data) Fout.close() if __name__ == "__main__": computations = [] cluster = LocalCluster() client = Client(cluster, asyncronous=True) for file1, file2 in zip(data_file_list, data_file_list_oe): computations.append(final(root_dir, file1, file2)) # my_info_to_str = " ".join(str(e) for e in final_energies) # Fout.write(my_info_to_str + "\n") output_data = dask.compute(*computations, scheduler='distributed')
https://github.com/harshagarine/QISKIT_INDIA_CHALLENGE
harshagarine
### WRITE YOUR CODE BETWEEN THESE LINES - START # import libraries that are used in the function below. from qiskit import QuantumCircuit import numpy as np ### WRITE YOUR CODE BETWEEN THESE LINES - END def build_state(): # initialize a 3 qubit circuit qc = QuantumCircuit(3) qc.h(0) qc.cx(0,1) qc.cx(1,2) return qc ### WRITE YOUR CODE BETWEEN THESE LINES - START # apply necessary gates ### WRITE YOUR CODE BETWEEN THESE LINES - END return circuit
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
from IPython.display import IFrame; IFrame("https://www.ibm.com/quantum", 900,500) import csv with open('ibm_lagos_calibrations_2023-09-28T17_22_25Z.csv', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: print(', '.join(row)) import qiskit qiskit.__qiskit_version__ # Copie se API Token no IBMQ e cole aqui qiskit.IBMQ.save_account('ee8631db565e87e97b066d08e02cafb9bfa745be07e573095b666daa608a37ce58ae6ef5c174aff56a935dadfe1fa9c82edfe37aec6b24774bc94613658cc7d8', overwrite = True) # Execute esse comando uma vez só qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider.backends() from qiskit import * qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr,cr) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr[0],cr[0]) qc.measure(qr[1],cr[1]) qc.draw('mpl') simulator = Aer.get_backend('qasm_simulator') nshots = 8192 # número de "prepara-e-mede" job = execute(qc, backend = simulator, shots = nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts(qc)) # Acessando as contagens com numpy counts = job.result().get_counts(qc) counts counts['00'] # probabilidade p00 = 0; p01 = 0; p10 = 0; p11 = 0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots p00, p01, p10, p11 device = provider.get_backend('ibm_lagos') from qiskit.tools.monitor import job_monitor job = execute(qc, backend = device, shots = nshots) job_monitor(job) plot_histogram(job.result().get_counts(qc)) counts = job.result().get_counts(qc) counts counts['00'] # probabilidade p00 = 0; p01 = 0; p10 = 0; p11 = 0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots p00, p01, p10, p11
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 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. r""" =================== Overview of Sampler =================== Sampler class calculates probabilities or quasi-probabilities of bitstrings from quantum circuits. A sampler is initialized with an empty parameter set. The sampler is used to create a :class:`~qiskit.providers.JobV1`, via the :meth:`qiskit.primitives.Sampler.run()` method. This method is called with the following parameters * quantum circuits (:math:`\psi_i(\theta)`): list of (parameterized) quantum circuits. (a list of :class:`~qiskit.circuit.QuantumCircuit` objects) * parameter values (:math:`\theta_k`): list of sets of parameter values to be bound to the parameters of the quantum circuits. (list of list of float) The method returns a :class:`~qiskit.providers.JobV1` object, calling :meth:`qiskit.providers.JobV1.result()` yields a :class:`~qiskit.primitives.SamplerResult` object, which contains probabilities or quasi-probabilities of bitstrings, plus optional metadata like error bars in the samples. Here is an example of how sampler is used. .. code-block:: python from qiskit.primitives import Sampler from qiskit import QuantumCircuit from qiskit.circuit.library import RealAmplitudes # a Bell circuit bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell.measure_all() # two parameterized circuits pqc = RealAmplitudes(num_qubits=2, reps=2) pqc.measure_all() pqc2 = RealAmplitudes(num_qubits=2, reps=3) pqc2.measure_all() theta1 = [0, 1, 1, 2, 3, 5] theta2 = [0, 1, 2, 3, 4, 5, 6, 7] # initialization of the sampler sampler = Sampler() # Sampler runs a job on the Bell circuit job = sampler.run(circuits=[bell], parameter_values=[[]], parameters=[[]]) job_result = job.result() print([q.binary_probabilities() for q in job_result.quasi_dists]) # Sampler runs a job on the parameterized circuits job2 = sampler.run( circuits=[pqc, pqc2], parameter_values=[theta1, theta2], parameters=[pqc.parameters, pqc2.parameters]) job_result = job2.result() print([q.binary_probabilities() for q in job_result.quasi_dists]) """ from __future__ import annotations from abc import abstractmethod from collections.abc import Sequence from copy import copy from typing import Generic, TypeVar from qiskit.circuit import QuantumCircuit from qiskit.circuit.parametertable import ParameterView from qiskit.providers import JobV1 as Job from .base_primitive import BasePrimitive T = TypeVar("T", bound=Job) class BaseSampler(BasePrimitive, Generic[T]): """Sampler base class Base class of Sampler that calculates quasi-probabilities of bitstrings from quantum circuits. """ __hash__ = None def __init__( self, *, options: dict | None = None, ): """ Args: options: Default options. """ self._circuits = [] self._parameters = [] super().__init__(options) def run( self, circuits: QuantumCircuit | Sequence[QuantumCircuit], parameter_values: Sequence[float] | Sequence[Sequence[float]] | None = None, **run_options, ) -> T: """Run the job of the sampling of bitstrings. Args: circuits: One of more circuit objects. parameter_values: Parameters to be bound to the circuit. run_options: Backend runtime options used for circuit execution. Returns: The job object of the result of the sampler. The i-th result corresponds to ``circuits[i]`` evaluated with parameters bound as ``parameter_values[i]``. Raises: ValueError: Invalid arguments are given. """ # Singular validation circuits = self._validate_circuits(circuits) parameter_values = self._validate_parameter_values( parameter_values, default=[()] * len(circuits), ) # Cross-validation self._cross_validate_circuits_parameter_values(circuits, parameter_values) # Options run_opts = copy(self.options) run_opts.update_options(**run_options) return self._run( circuits, parameter_values, **run_opts.__dict__, ) @abstractmethod def _run( self, circuits: tuple[QuantumCircuit, ...], parameter_values: tuple[tuple[float, ...], ...], **run_options, ) -> T: raise NotImplementedError("The subclass of BaseSampler must implment `_run` method.") # TODO: validate measurement gates are present @classmethod def _validate_circuits( cls, circuits: Sequence[QuantumCircuit] | QuantumCircuit, ) -> tuple[QuantumCircuit, ...]: circuits = super()._validate_circuits(circuits) for i, circuit in enumerate(circuits): if circuit.num_clbits == 0: raise ValueError( f"The {i}-th circuit does not have any classical bit. " "Sampler requires classical bits, plus measurements " "on the desired qubits." ) return circuits @property def circuits(self) -> tuple[QuantumCircuit, ...]: """Quantum circuits to be sampled. Returns: The quantum circuits to be sampled. """ return tuple(self._circuits) @property def parameters(self) -> tuple[ParameterView, ...]: """Parameters of quantum circuits. Returns: List of the parameters in each quantum circuit. """ return tuple(self._parameters)
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
from qiskit.circuit.library import SwapGate, CXGate from qiskit.quantum_info import random_unitary from qiskit.extensions import UnitaryGate from monodromy.haar import expected_cost from qiskit.circuit.library import iSwapGate, XXPlusYYGate, CXGate import numpy as np from monodromy.render import gates_to_coverage_plot from monodromy.haar import expected_cost from monodromy.coverage import coverage_lookup_cost import h5py import json import matplotlib.pyplot as plt from scipy import stats from collections import Counter import scienceplots import LovelyPlots.utils as lp from tqdm import tqdm # %matplotlib widget class ErrorModel: """Use exponential decay error model. Define fidelity model as some function of (time) cost. """ def __init__(self, unit_fidelity=0.99): """Unit fidelity is the fidelity of operation with unit cost 1.0 NOTE: simple convention is that CX, iSWAP have unit cost 1.0, then sqrt(CX) and sqrt(iSWAP) have unit cost 0.5, etc. """ assert 0 <= unit_fidelity and unit_fidelity <= 1 self.unit_fidelity = unit_fidelity self.normalized_lifetime = -1.0 / np.log(unit_fidelity) def fidelity(self, cost): """Convert (time) cost to fidelity""" return np.exp(-cost / self.normalized_lifetime) def infidelity(self, cost): """Convert (time) cost to infidelity""" return 1 - self.fidelity(cost) # ErrorModel(0.99).fidelity(1.5) indx = 2.0 U = iSwapGate().power(1 / indx) safe_basis_str = f"sqrt_{indx}_iswap" basis_str = r"$\sqrt[" + f"{indx}" + r"]{\texttt{iSWAP}}$" basis_cost = 1.0 / indx unit_fidelity = 0.99 affine_error_model = ErrorModel(unit_fidelity=unit_fidelity) coverage_1 = gates_to_coverage_plot(U, costs=[basis_cost]) no_mirror_haar_exact = expected_cost(coverage_1) print(no_mirror_haar_exact) average_fidelity = affine_error_model.fidelity(no_mirror_haar_exact) print(average_fidelity) coverage_2 = gates_to_coverage_plot(U, SwapGate(), costs=[basis_cost, 0]) mirror_haar_exact = expected_cost(coverage_2) print(mirror_haar_exact) average_fidelity = affine_error_model.fidelity(mirror_haar_exact) print(average_fidelity) def data_collection(coverage_set, error_model, allow_approx, N=1000, save_to=None): """Collects data for Haar score calculations. Args: coverage_set (List[CircuitPolytopeData]): List of coverage sets. error_model (ErrorModel): Error model to use for cost calculation. allow_approx (bool): Whether to allow approximate decomposition. N (int, optional): Number of iterations. Defaults to 1000. check_every (int, optional): Check the running average every `check_every` iterations. Defaults to 100. save_to (str, optional): Path to the HDF5 file to save the data. If None, data won't be saved. Defaults to None. Returns: dict: Collected data. """ costs = [] running_avgs = [] conf_intervals = [] fidelities = [] progress_bar = tqdm(total=N, desc="Starting") for _ in range(N): target = UnitaryGate(random_unitary(4)) # NOTE fidelity here is circuit cost and decomposition fidelity combined cost, fidelity = coverage_lookup_cost( coverage_set, target, error_model, allow_approx=allow_approx ) costs.append(cost) fidelities.append(fidelity) running_avgs.append(np.mean(costs)) if len(np.unique(costs)) > 1: confidence = 0.95 conf_interval = stats.t.interval( confidence, len(costs) - 1, loc=np.mean(costs), scale=stats.sem(costs), ) conf_intervals.append(conf_interval) else: conf_intervals.append((np.nan, np.nan)) if len(np.unique(costs)) > 1: progress_bar.set_description( f"Current average cost: {running_avgs[-1]:.4f}, Std. Error: {stats.sem(costs):.4f}" ) else: progress_bar.set_description( f"Current average cost: {running_avgs[-1]:.4f}" ) progress_bar.update() progress_bar.close() # print frequency of each cost print(Counter(costs)) print("Monte Carlo: Haar score", np.mean(costs)) # print average fidelity print("Monte Carlo: Average fidelity", np.mean(fidelities)) data = { "costs": costs, "running_avgs": running_avgs, "conf_intervals": conf_intervals, "fidelities": fidelities, } if save_to is not None: with h5py.File(save_to, "w") as f: for key, value in data.items(): f.create_dataset(key, data=json.dumps(value)) return data coverage_sets = [coverage_1, coverage_1, coverage_2, coverage_2] allow_approx = [False, True, False, True] mirror_flags = ["no_mirror", "no_mirror", "mirror", "mirror"] labels = [ "mirror_data/" + rf"{mirror_flag}-{safe_basis_str}-approx{approx_bool}-{affine_error_model.unit_fidelity}" for mirror_flag, approx_bool in zip(mirror_flags, allow_approx) ] # # NOTE uncomment if want to actually run the data collection # for coverage_set, approx_bool, label in zip(coverage_sets, allow_approx, labels): # print(f"Running: {label}") # data_collection( # coverage_set, affine_error_model, approx_bool, save_to=label + ".hdf5" # ) # print("\n") def plot_data(data, labels, pretty_labels, exact_convergence=None): """Plots running averages and confidence intervals from data. Args: data (List[dict]): List of dictionaries containing data from each run. labels (List[str]): List of labels for each data set (used for exact_convergence matching). pretty_labels (List[str]): List of 'pretty' labels for each data set (used for plotting). exact_convergence (dict, optional): Dictionary containing values of exact convergence for each data set. If None, it won't be plotted. Defaults to None. """ assert len(labels) == len( pretty_labels ), "Labels and pretty_labels must have the same length." with plt.style.context(["ieee", "science"]): plt.rc("text", usetex=True) for d, label, pretty_label in zip(data, labels, pretty_labels): running_avgs = d["running_avgs"] conf_intervals = d["conf_intervals"] plt.plot(running_avgs, label=f"{pretty_label}") # plt.fill_between( # range(len(running_avgs)), # [ci[0] for ci in conf_intervals], # [ci[1] for ci in conf_intervals], # alpha=0.1, # ) if exact_convergence and label in exact_convergence: plt.axhline( y=exact_convergence[label], color="k", linestyle="--", alpha=0.5, # label=f"Exact Convergence - {pretty_label}", ) # # Extract basis gate name and error value from the first label # directory, label_info = labels[0].split('/') # basis_gate, name, error_value = label_info.split('-') # Use the extracted information to build the title # plt.title( # f"Haar Score vs Iteration" #, {basis_str}, unit fidelity {unit_fidelity}" # ) plt.xlabel("Iteration") plt.ylabel("Haar Score") # use log scales # plt.yscale("log") plt.xscale("log") # plt.legend() # put legend above plot in 2 columns plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.26), ncol=2) # shrink figure height plt.gcf().set_size_inches(3.5, 1.85) fig = plt.gcf() plt.show() # return fig so can be saved return fig def load_hdf5_data(filename): """Load data from an HDF5 file. Args: filename (str): Path to the HDF5 file. Returns: dict: Data loaded from the file. """ with h5py.File(filename, "r") as f: data = {key: json.loads(value[()]) for key, value in f.items()} return data data = [load_hdf5_data(f"{label}.hdf5") for label in labels] exact_convergence = { labels[0]: no_mirror_haar_exact, labels[2]: mirror_haar_exact, } # Replace with actual values pretty_labels = [ "Exact", "Approximate", "Exact + Mirrors", "Approximate + Mirrors", ] fig = plot_data(data, labels, pretty_labels, exact_convergence=exact_convergence) fig.savefig( "weyl_mirror_sqrt[2].pdf", bbox_inches="tight", pad_inches=0, )
https://github.com/OccumRazor/implement-quantum-algotirhms-with-qiskit
OccumRazor
from qiskit import QuantumRegister,ClassicalRegister,QuantumCircuit,Aer,execute from qiskit.providers.aer import QasmSimulator from qiskit.circuit.library.standard_gates import CU1Gate from numpy import pi from qiskit_code.classicalMethod import printCounts,Dec2Bi,modifyExpValue from qiskit_code.quantumMethod import ini from qiskit.aqua.operators import StateFn,I from numpy import real def physicalQubits(ipt): qr=QuantumRegister(5) circ=QuantumCircuit(qr) if ipt==1: circ.x(qr[0]) # controlled phase flip - if the input state is |1>, # then flip the global phase by pi CU1=CU1Gate(pi) circ.append(CU1,[qr[0],qr[1]]) circ.cx(qr[0],qr[1]) circ.append(CU1,[qr[0],qr[1]]) circ.cx(qr[0],qr[1]) circ.h(qr[4]) circ.s(qr[4]) # g1 circ.cz(qr[4],qr[3]) circ.cz(qr[4],qr[1]) circ.cy(qr[4],qr[0]) circ.h(qr[3]) #g2 circ.cz(qr[3],qr[2]) circ.cz(qr[3],qr[1]) circ.cx(qr[3],qr[0]) circ.h(qr[2]) #g3 circ.cz(qr[2],qr[4]) circ.cz(qr[2],qr[3]) circ.cx(qr[2],qr[0]) circ.h(qr[1]) circ.s(qr[1]) #g4 circ.cz(qr[1],qr[4]) circ.cz(qr[1],qr[2]) circ.cy(qr[1],qr[0]) return circ.to_gate() def checkPhases(): operator=I.tensorpower(5) for i in range(32): qr=QuantumRegister(5) circ=QuantumCircuit(qr) ini(circ,qr,Dec2Bi(i)) # generate the state vector of the test state psi=StateFn(circ) # generate the state vector of the 0L state phi1=StateFn(physicalQubits(0)) thisNumber=bin(i)[2:] if len(thisNumber)<5: thisNumber=(5-len(thisNumber))*'0'+thisNumber print('expectation value for state '+thisNumber) print(' and the physical qubits of 0:') exp01=(~phi1@operator@psi).eval() exp1=modifyExpValue(real(exp01)) print(exp1) # generate the state vector of the 1L state phi2=StateFn(physicalQubits(1)) print(' and the physical qubits of 1:') exp02=(~phi2@operator@psi).eval() exp2=modifyExpValue(real(exp02)) print(exp2) def stabilized(ipt): operator=I.tensorpower(5) qr=QuantumRegister(5) circ=QuantumCircuit(qr) circ.append(physicalQubits(ipt),qr) # stabilized: phi=StateFn(circ) # g1 check circ.cz(qr[4],qr[3]) circ.cz(qr[4],qr[1]) circ.cy(qr[4],qr[0]) psi=StateFn(circ) print((~phi@operator@psi).eval()) #g2 check circ.cz(qr[3],qr[2]) circ.cz(qr[3],qr[1]) circ.cx(qr[3],qr[0]) psi=StateFn(circ) print((~phi@operator@psi).eval()) #g3 check circ.cz(qr[2],qr[4]) circ.cz(qr[2],qr[3]) circ.cx(qr[2],qr[0]) psi=StateFn(circ) print((~phi@operator@psi).eval()) #g4 check circ.cz(qr[1],qr[4]) circ.cz(qr[1],qr[2]) circ.cy(qr[1],qr[0]) psi=StateFn(circ) print((~phi@operator@psi).eval()) #checkPhase() stabilized(0) stabilized(1)
https://github.com/dlyongemallo/qiskit-zx-transpiler
dlyongemallo
import sys; sys.path.append('..') from qiskit import transpile from qiskit.circuit import QuantumCircuit from qiskit.transpiler import PassManager from qiskit.qasm2 import dumps from qiskit.qasm3 import dumps as dumps3 import pyzx as zx from zxpass import ZXPass pass_manager = PassManager(ZXPass()) # Select the benchmark circuit to examine. subdir = "medium" circuit_name = "qft_n18" # Output the original circuit. with open(f"QASMBench/{subdir}/{circuit_name}/{circuit_name}.qasm", "r") as file: qasm_str = file.read() print(f"Benchmark circuit: {circuit_name}") qc = QuantumCircuit.from_qasm_str(qasm_str) # qc.draw(output = "mpl") # Output the ZX diagram for the original circuit. g = zx.Circuit.from_qasm(qasm_str).to_graph() zx.draw(g) # Output the circuit produced by Qiskit optimisation. opt_qc = transpile(qc, basis_gates=['u3', 'cx'], optimization_level=3) # opt_qc.draw(output = "mpl") # Output the ZX diagram for the Qiskit-optimised circuit. opt_g = zx.Circuit.from_qasm(dumps3(opt_qc)).to_graph() zx.draw(opt_g) # Output the ZX-optimised circuit. zx_qc = pass_manager.run(qc) # zx_qc.draw(output = "mpl") # Re-create the graph from the circuit. zx_g = zx.Circuit.from_qasm(dumps(zx_qc)).to_graph() zx.draw(zx_g)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/qiskit-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/HypsoHypso/QuantumComputingScripts
HypsoHypso
# Importing all the necessary library from qiskit import QuantumCircuit, Aer, IBMQ, QuantumRegister, ClassicalRegister, execute from qiskit.tools.jupyter import * from qiskit.visualization import * import qiskit.tools.jupyter import ipywidgets as widgets # Layout button_p = widgets.Button( description='Play') gate_p = widgets.Dropdown( options=[('Identity', 'i'), ('Bit Flip', 'x')], description='Choice: ', disabled=False, ) out_p = widgets.Output() def on_button_clicked(b): with out_p: # Initial Circuit circuit_p = QuantumRegister(1, 'circuit') measure_p = ClassicalRegister(1, 'result') qc_p = QuantumCircuit(circuit_p, measure_p) # Turn 1 qc_p.h(circuit_p[0]) # Turn 2 if gate_p.value == 'i': qc_p.i(circuit_p[0]) if gate_p.value == 'x': qc_p.x(circuit_p[0]) # Turn 3 qc_p.h(circuit_p[0]) # Measure qc_p.measure(circuit_p, measure_p) # QASM backend_p = Aer.get_backend('aer_simulator') job_p = execute(qc_p, backend_p, shots=8192) res_p = job_p.result().get_counts() # Result if len(res_p) == 1 and list(res_p.keys())[0] == '0': print("You Lose to Quantum. Quantum Computer Wins") if len(res_p) == 1 and list(res_p.keys())[0] == '1': print("You Win against Quantum Computer") if len(res_p) == 2: print("Either Quantum or You Wins") button_p.on_click(on_button_clicked) widgets.VBox([gate_p, button_p, out_p])
https://github.com/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Basic example with the Qiskit AQT provider. Creates a 4-qubit GHZ state.""" import qiskit from qiskit import QuantumCircuit from qiskit_aqt_provider.aqt_provider import AQTProvider if __name__ == "__main__": # Ways to specify an access token (in precedence order): # - as argument to the AQTProvider initializer # - in the AQT_TOKEN environment variable # - if none of the above exists, default to an empty string, which restricts access # to the default workspace only. provider = AQTProvider("token") # The backends() method lists all available computing backends. Printing it # renders it as a table that shows each backend's containing workspace. print(provider.backends()) # Retrieve a backend by providing search criteria. The search must have a single # match. For example: backend = provider.get_backend("offline_simulator_no_noise", workspace="default") # Define a quantum circuit that produces a 4-qubit GHZ state. qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.measure_all() # Transpile for the target backend. qc = qiskit.transpile(qc, backend) # Execute on the target backend. result = backend.run(qc, shots=200).result() if result.success: print(result.get_counts()) else: # pragma: no cover print(result.to_dict()["error"])
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Layout Score pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import CXGate from qiskit.transpiler.passes import Layout2qDistance from qiskit.transpiler import CouplingMap, Layout from qiskit.converters import circuit_to_dag from qiskit.transpiler.target import Target from qiskit.test import QiskitTestCase class TestLayoutScoreError(QiskitTestCase): """Test error-ish of Layout Score""" def test_no_layout(self): """No Layout. Empty Circuit CouplingMap map: None. Result: None""" qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) coupling = CouplingMap() layout = None dag = circuit_to_dag(circuit) pass_ = Layout2qDistance(coupling) pass_.property_set["layout"] = layout pass_.run(dag) self.assertIsNone(pass_.property_set["layout_score"]) class TestTrivialLayoutScore(QiskitTestCase): """Trivial layout scenarios""" def test_no_cx(self): """Empty Circuit CouplingMap map: None. Result: 0""" qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) coupling = CouplingMap() layout = Layout().generate_trivial_layout(qr) dag = circuit_to_dag(circuit) pass_ = Layout2qDistance(coupling) pass_.property_set["layout"] = layout pass_.run(dag) self.assertEqual(pass_.property_set["layout_score"], 0) def test_swap_mapped_true(self): """Mapped circuit. Good Layout qr0 (0):--(+)---(+)- | | qr1 (1):---.-----|-- | qr2 (2):---------.-- CouplingMap map: [1]--[0]--[2] """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) coupling = CouplingMap([[0, 1], [0, 2]]) layout = Layout().generate_trivial_layout(qr) dag = circuit_to_dag(circuit) pass_ = Layout2qDistance(coupling) pass_.property_set["layout"] = layout pass_.run(dag) self.assertEqual(pass_.property_set["layout_score"], 0) def test_swap_mapped_false(self): """Needs [0]-[1] in a [0]--[2]--[1] Result:1 qr0:--(+)-- | qr1:---.--- CouplingMap map: [0]--[2]--[1] """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) coupling = CouplingMap([[0, 2], [2, 1]]) layout = Layout().generate_trivial_layout(qr) dag = circuit_to_dag(circuit) pass_ = Layout2qDistance(coupling) pass_.property_set["layout"] = layout pass_.run(dag) self.assertEqual(pass_.property_set["layout_score"], 1) def test_swap_mapped_true_target(self): """Mapped circuit. Good Layout qr0 (0):--(+)---(+)- | | qr1 (1):---.-----|-- | qr2 (2):---------.-- CouplingMap map: [1]--[0]--[2] """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) target = Target() target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None}) layout = Layout().generate_trivial_layout(qr) dag = circuit_to_dag(circuit) pass_ = Layout2qDistance(target) pass_.property_set["layout"] = layout pass_.run(dag) self.assertEqual(pass_.property_set["layout_score"], 0) def test_swap_mapped_false_target(self): """Needs [0]-[1] in a [0]--[2]--[1] Result:1 qr0:--(+)-- | qr1:---.--- CouplingMap map: [0]--[2]--[1] """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) target = Target() target.add_instruction(CXGate(), {(0, 2): None, (2, 1): None}) layout = Layout().generate_trivial_layout(qr) dag = circuit_to_dag(circuit) pass_ = Layout2qDistance(target) pass_.property_set["layout"] = layout pass_.run(dag) self.assertEqual(pass_.property_set["layout_score"], 1) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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 unittest import qiskit from qiskit.circuit.library import TwoLocal from qiskit import BasicAer from qiskit.utils import QuantumInstance from qiskit.opflow import Z, I from volta.vqd import VQD from volta.utils import classical_solver class TestVQDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="swap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] message = ( "VQD with SWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))" ) self.assertAlmostEqual(want, got, decimal_place, message) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] message = "VQD with SWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimal_place, message) class TestVQDDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() # backend = BasicAer.get_backend("qasm_simulator") backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="dswap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class TestVQDAmplitude(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="amplitude", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class VQDRaiseError(unittest.TestCase): def test_not_implemented_overlapping_method(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) with self.assertRaises(NotImplementedError): VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="test", ), if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
from qiskit import QuantumCircuit, execute, transpile from dell_runtime import DellRuntimeProvider provider = DellRuntimeProvider() provider.remote('http://qdr-dev.oro-sandbox-small1.k8s.cec.lab.emc.com') provider.runtime.programs() RUNTIME_PROGRAM = """ from qiskit.compiler import transpile, schedule def main( backend, user_messenger, circuits, **kwargs, ): user_messenger.publish({'results': 'intermittently'}) circuits = transpile( circuits, ) if not isinstance(circuits, list): circuits = [circuits] # Compute raw results for i in range(0, 10): result = backend.run(circuits, **kwargs).result() user_messenger.publish({f'result_{i}': result}) user_messenger.publish('completed', final=True) print("job complete successfully") """ RUNTIME_PROGRAM_METADATA = { "max_execution_time": 600, "description": "Qiskit test program" } program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA) program_id qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) program_inputs = { 'circuits': qc, } job = provider.runtime.run(program_id, options=None, inputs=program_inputs, callback=print) job.get_unread_messages() job.result(timeout=20) job.status()
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/dkp-quantum/Tutorials
dkp-quantum
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import * from qiskit.visualization import * import numpy as np def encoding_x(qc): qc.cx(0,1) qc.cx(0,2) qc.barrier() def decoding_x(qc): qc.cx(0,2) qc.cx(0,1) qc.barrier() def random_init(qc,theta,phi,index): ## Prepare a random single-qubit state qc.ry(theta,index) qc.rz(phi,index) qc.barrier() def random_init_inv(qc,theta,phi,index): ## Inverse of the random single-qubit state preparation qc.rz(-phi,index) qc.ry(-theta,index) qc.barrier() q = QuantumRegister(3) c = ClassicalRegister(1) qec = QuantumCircuit(q,c) # Initialize the first qubit in a random state theta = np.random.random()*np.pi phi = np.random.random()*2*np.pi random_init(qec,theta,phi,0) # QEC encoding for correcting a bit-flip error encoding_x(qec) # QEC decoding for correcting a bit-flip error decoding_x(qec) # Correction qec.ccx(1,2,0) # Insert inverse of the random initial state preparation # to check that the QEC has worked. random_init_inv(qec,theta,phi,0) qec.measure(q[0],c) qec.draw(output='mpl') # Use Aer's qasm_simulator backend_q = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. job_qec_ref = execute(qec, backend_q, shots=4096) # Grab the results from the job. result_qec_ref = job_qec_ref.result() plot_histogram(result_qec_ref.get_counts(qec)) # Define bit-flip errors with probability p def bitflip(qc,qubit,p): if np.random.binomial(1,p) == 1: qc.x(qubit) q = QuantumRegister(3) c = ClassicalRegister(1) qec = QuantumCircuit(q,c) # Initialize the first qubit in a random state theta = np.random.random()*np.pi phi = np.random.random()*2*np.pi random_init(qec,theta,phi,0) # QEC encoding for correcting a bit-flip error encoding_x(qec) # Insert error p=1 bitflip(qec,0,p) # bitflip(qec,1,p) # bitflip(qec,2,p) qec.barrier() # QEC decoding for correcting a bit-flip error decoding_x(qec) # Correction qec.ccx(1,2,0) # Insert inverse of the random initial state preparation # to check that the QEC has worked. random_init_inv(qec,theta,phi,0) qec.measure(q[0],c) qec.draw(output='mpl') # Execute the circuit on the qasm simulator. job_qec = execute(qec, backend_q, shots=4096) # Grab the results from the job. result_qec = job_qec.result() plot_histogram(result_qec.get_counts(qec)) q = QuantumRegister(3) c = ClassicalRegister(1) qec = QuantumCircuit(q,c) # Initialize the first qubit in a random state theta = np.random.random()*np.pi phi = np.random.random()*2*np.pi random_init(qec,theta,phi,0) # QEC encoding for correcting a bit-flip error encoding_x(qec) # Insert error p=1 bitflip(qec,0,p) bitflip(qec,1,p) # bitflip(qec,2,p) qec.barrier() # QEC decoding for correcting a bit-flip error decoding_x(qec) # Correction qec.ccx(1,2,0) # Insert inverse of the random initial state preparation # to check that the QEC has worked. random_init_inv(qec,theta,phi,0) qec.measure(q[0],c) qec.draw(output='mpl') # Execute the circuit on the qasm simulator. job_qec = execute(qec, backend_q, shots=4096) # Grab the results from the job. result_qec = job_qec.result() plot_histogram(result_qec.get_counts(qec)) q = QuantumRegister(3) c = ClassicalRegister(1) qec = QuantumCircuit(q,c) # Initialize the first qubit in a random state theta = np.random.random()*np.pi phi = np.random.random()*2*np.pi random_init(qec,theta,phi,0) # QEC encoding for correcting a bit-flip error encoding_x(qec) # Insert error p=1 bitflip(qec,0,p) bitflip(qec,1,p) bitflip(qec,2,p) qec.barrier() # QEC decoding for correcting a bit-flip error decoding_x(qec) # Correction qec.ccx(1,2,0) # Insert inverse of the random initial state preparation # to check that the QEC has worked. random_init_inv(qec,theta,phi,0) qec.measure(q[0],c) qec.draw(output='mpl') # Execute the circuit on the qasm simulator. job_qec = execute(qec, backend_q, shots=4096) # Grab the results from the job. result_qec = job_qec.result() plot_histogram(result_qec.get_counts(qec)) import numpy as np from numpy import pi # importing Qiskit from qiskit import * from qiskit.visualization import * from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor from qiskit.tools.visualization import plot_gate_map, plot_error_map qftc = QuantumCircuit(3) qftc.h(0) qftc.draw(output='mpl') qftc.cu1(2*pi/(2**2), 1, 0) # CROT from qubit 1 to qubit 0 qftc.draw(output='mpl') qftc.cu1(2*pi/(2**3), 2, 0) # CROT from qubit 1 to qubit 0 qftc.draw(output='mpl') qftc.h(1) qftc.cu1(2*pi/(2**2), 2, 1) # CROT from qubit 2 to qubit 1 qftc.h(2) qftc.draw(output='mpl') # Complete the QFT circuit by reordering qubits (by exchanging qubit 1 and 3) qftc.swap(0,2) qftc.draw(output='mpl') def qft_rotations(circuit, n): if n == 0: # Exit function if circuit is empty print("The number of qubits must be greater than 0") return circuit index = 0 circuit.h(index) # Apply the H-gate to the most significant qubit index += 1 n -= 1 for qubit in range(n): # Apply the controlled rotations conditioned on n-1 qubits # For each less significant qubit, we need to do a # smaller-angled controlled rotation: circuit.cu1(2*pi/2**(2+qubit), index + qubit, 0) qc = QuantumCircuit(4) qft_rotations(qc,4) qc.draw(output = 'mpl') def qft_rotations(circuit, n, start): if n == 0: # Exit function if circuit is empty return circuit circuit.h(start) # Apply the H-gate to the most significant qubit if start == n-1: return circuit for qubit in range(n-1-start): # Apply the controlled rotations conditioned on n-1 qubits # For each less significant qubit, we need to do a # smaller-angled controlled rotation: circuit.cu1(2*pi/2**(2+qubit), start + 1 + qubit, start) start += 1 circuit.barrier() # Apply QFT recursively qft_rotations(circuit, n, start) qc = QuantumCircuit(5) qft_rotations(qc,5,0) qc.draw(output = 'mpl')
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/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
min_qubits=4 max_qubits=8 max_circuits=1 num_shots=1 backend_id="dm_simulator" #hub="ibm-q"; group="open"; project="main" provider_backend = None exec_options = {} # # ========================== # # *** If using IBMQ hardware, run this once to authenticate # from qiskit import IBMQ # IBMQ.save_account('YOUR_API_TOKEN_HERE') # # *** If you are part of an IBMQ group, set hub, group, and project name here # hub="YOUR_HUB_NAME"; group="YOUR_GROUP_NAME"; project="YOUR_PROJECT_NAME" # # *** This example shows how to specify an IBMQ backend using a known "backend_id" # exec_options = { "optimization_level":3, "use_sessions":True, "resilience_level":1} # backend_id="ibmq_belem" # # ========================== # # *** If using Azure Quantum, use this hub identifier and specify the desired backend_id # # Identify your resources with env variables AZURE_QUANTUM_RESOURCE_ID and AZURE_QUANTUM_LOCATION # hub="azure-quantum"; group="open"; project="QED-C App-Oriented Benchmarks - Qiskit Version" # backend_id="<YOUR_BACKEND_NAME_HERE>" # # ========================== # The remaining examples create a provider instance and get a backend from it # # An example using IonQ provider # from qiskit_ionq import IonQProvider # provider = IonQProvider() # Be sure to set the QISKIT_IONQ_API_TOKEN environment variable # provider_backend = provider.get_backend("ionq_qpu") # backend_id="ionq_qpu" # # An example using BlueQubit provider # import sys # sys.path.insert(1, "../..") # import os, bluequbit, _common.executors.bluequbit_executor as bluequbit_executor # provider_backend = bluequbit.init() # backend_id="BlueQubit-CPU" # exec_options = { "executor": bluequbit_executor.run, "device":'cpu' } # # *** Here's an example of using a typical custom provider backend (e.g. AQT simulator) # import os # from qiskit_aqt_provider import AQTProvider # provider = AQTProvider(os.environ.get('AQT_ACCESS_KEY')) # get your key from environment # provider_backend = provider.backends.aqt_qasm_simulator_noise_1 # backend_id="aqt_qasm_simulator_noise_1" # Custom optimization options can be specified in this cell (below is an example) import sys sys.path.insert(1, "../../") # # Example of pytket Transformer # import _common.transformers.tket_optimiser as tket_optimiser # exec_options.update({ "optimization_level": 0, "layout_method":'sabre', "routing_method":'sabre', "transformer": tket_optimiser.high_optimisation }) # # Define a custom noise model to be used during execution # import _common.custom.custom_qiskit_noise_model as custom_qiskit_noise_model # exec_options.update({ "noise_model": custom_qiskit_noise_model.my_noise_model() }) # # Example of mthree error mitigation # import _common.postprocessors.mthree.mthree_em as mthree_em # exec_options.update({ "postprocessor": mthree_em.get_mthree_handlers(backend_id, provider_backend) }) import sys sys.path.insert(1, "maxcut/qsim") import maxcut_benchmark # set noise to None for testing # import execute # execute.set_noise_model(None) maxcut_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=1, rounds=1, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options ) import sys sys.path.insert(1, "maxcut/qsim") import maxcut_benchmark # # set noise to None for testing # import execute # execute.set_noise_model(None) # execute and display options objective_func_type = 'approx_ratio' score_metric=['approx_ratio', 'cvar_ratio'] x_metric=['cumulative_elapsed_time', 'cumulative_exec_time', 'cumulative_opt_exec_time'] # Note: the plots produced by this benchmark only use the last of the problems at each width maxcut_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, rounds=2, degree=3, do_fidelities=True, parameterized=False, use_fixed_angles=False, score_metric=score_metric, x_metric=x_metric, save_res_to_file=True, comfort=True, objective_func_type = objective_func_type, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options ) import os, maxcut_benchmark backend_id = "dm_simulator" maxcut_benchmark.load_data_and_plot(os.path.join('__results', backend_id, 'approx_ratio'), score_metric=['approx_ratio', 'cvar_ratio'], x_metric=['cumulative_elapsed_time', 'cumulative_exec_time', 'cumulative_opt_exec_time']) import sys sys.path.insert(1, "maxcut/qsim") import maxcut_benchmark # set noise to None for testing import execute execute.set_noise_model(None) objective_func_type = 'cvar_ratio' score_metric=[objective_func_type] x_metric=['cumulative_exec_time'] # Note: the plots produced by this benchmark only use the last of the problems at each width maxcut_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, rounds=2, degree=3, alpha = 0.1, objective_func_type = objective_func_type, do_fidelities = False, score_metric=score_metric, x_metric=x_metric, num_x_bins=15, max_iter=30, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options ) import sys sys.path.insert(1, "maxcut/qsim") import maxcut_benchmark # set noise to None for testing import execute execute.set_noise_model(None) objective_func_type = 'gibbs_ratio' score_metric=[objective_func_type] #, 'fidelity' x_metric=['cumulative_exec_time'] #, , 'cumulative_create_time' 'cumulative_opt_exec_time' # Note: the plots produced by this benchmark only use the last of the problems at each width maxcut_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, rounds=2, degree=3, eta=0.5, score_metric=score_metric, x_metric=x_metric, num_x_bins=15, max_iter=30, objective_func_type = objective_func_type, do_fidelities = False, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options ) import sys sys.path.insert(1, "maxcut/qsim") import maxcut_benchmark # set noise to None for testing import execute execute.set_noise_model(None) score_metric=['approx_ratio', 'fidelity'] x_metric=['cumulative_create_time', 'cumulative_exec_time', 'cumulative_opt_exec_time'] # Note: the plots produced by this benchmark only use the last of the problems at each width maxcut_benchmark.run( min_qubits=min_qubits, max_qubits=max_qubits, max_circuits=max_circuits, num_shots=num_shots, method=2, rounds=1, degree=-3, score_metric=score_metric, x_metric=x_metric, num_x_bins=15, max_iter=30, backend_id=backend_id, provider_backend=provider_backend, # hub=hub, group=group, project=project, exec_options=exec_options ) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister beta = 0.08 gamma = -0.094 cycle_time = 0 qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr, name="main") qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.cx(qr[0], qr[1]) qc.rz(2*3.14159*gamma, qr[1]) qc.cx(qr[0], qr[1]) qc.cx(qr[0], qr[3]) qc.rz(2*3.14159*gamma, qr[3]) qc.cx(qr[0], qr[3]) qc.cx(qr[0], qr[2]) qc.rz(2*3.14159*gamma, qr[2]) qc.cx(qr[0], qr[2]) qc.cx(qr[1], qr[2]) qc.rz(2*3.14159*gamma, qr[2]) qc.cx(qr[1], qr[2]) qc.cx(qr[1], qr[3]) qc.rz(2*3.14159*gamma, qr[3]) qc.cx(qr[1], qr[3]) qc.cx(qr[2], qr[3]) qc.rz(2*3.14159*gamma, qr[3]) qc.cx(qr[2], qr[3]) qc.rx(2*3.14159*beta, qr[0]) qc.rx(2*3.14159*beta, qr[1]) qc.rx(2*3.14159*beta, qr[2]) qc.rx(2*3.14159*beta, qr[3]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) qc.measure(qr[3], cr[3]) from qiskit import execute, BasicAer backend = BasicAer.get_backend("dm_simulator") # Use BasicAer dm_simulator job = execute(qc, backend, shots=1000) result = job.result() if result.backend_name == 'dm_simulator': try: probs = result.results[0].data.partial_probability # get results as measured probability except AttributeError: try: probs = result.results[0].data.ensemble_probability except AttributeError: probs = None else: probs = result.get_counts(qc) # get results as measured counts print("\nprobability ===== ",probs) # Draw the circuit print(qc) # Plot a histogram from qiskit.visualization import plot_histogram plot_histogram(probs)
https://github.com/xtophe388/QISKIT
xtophe388
#import all the packages # Checking the version of PYTHON import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') #append to system path so qiskit and Qconfig can be found from home directory sys.path.append('../qiskit-sdk-py/') # Import the QuantumProgram and configuration from qiskit import QuantumProgram #import Qconfig #other useful packages import math #Super secret message mes = 'hello world' print('Your super secret message: ',mes) #initial size of key n = len(mes)*3 #break up message into smaller parts if length > 10 nlist = [] for i in range(int(n/10)): nlist.append(10) if n%10 != 0: nlist.append(n%10) print('Initial key length: ',n) # Make random strings of length string_length def randomStringGen(string_length): #output variables used to access quantum computer results at the end of the function output_list = [] output = '' #start up your quantum program qp = QuantumProgram() backend = 'local_qasm_simulator' circuits = ['rs'] #run circuit in batches of 10 qubits for fastest results. The results #from each run will be appended and then clipped down to the right n size. n = string_length temp_n = 10 temp_output = '' for i in range(math.ceil(n/temp_n)): #initialize quantum registers for circuit q = qp.create_quantum_register('q',temp_n) c = qp.create_classical_register('c',temp_n) rs = qp.create_circuit('rs',[q],[c]) #create temp_n number of qubits all in superpositions for i in range(temp_n): rs.h(q[i]) #the .h gate is the Hadamard gate that makes superpositions rs.measure(q[i],c[i]) #execute circuit and extract 0s and 1s from key result = qp.execute(circuits, backend, shots=1) counts = result.get_counts('rs') result_key = list(result.get_counts('rs').keys()) temp_output = result_key[0] output += temp_output #return output clipped to size of desired string length return output[:n] key = randomStringGen(n) print('Initial key: ',key) #generate random rotation strings for Alice and Bob Alice_rotate = randomStringGen(n) Bob_rotate = randomStringGen(n) print("Alice's rotation string:",Alice_rotate) print("Bob's rotation string: ",Bob_rotate) #start up your quantum program backend = 'local_qasm_simulator' shots = 1 circuits = ['send_over'] Bob_result = '' for ind,l in enumerate(nlist): #define temp variables used in breaking up quantum program if message length > 10 if l < 10: key_temp = key[10*ind:10*ind+l] Ar_temp = Alice_rotate[10*ind:10*ind+l] Br_temp = Bob_rotate[10*ind:10*ind+l] else: key_temp = key[l*ind:l*(ind+1)] Ar_temp = Alice_rotate[l*ind:l*(ind+1)] Br_temp = Bob_rotate[l*ind:l*(ind+1)] #start up the rest of your quantum program qp2 = QuantumProgram() q = qp2.create_quantum_register('q',l) c = qp2.create_classical_register('c',l) send_over = qp2.create_circuit('send_over',[q],[c]) #prepare qubits based on key; add Hadamard gates based on Alice's and Bob's #rotation strings for i,j,k,n in zip(key_temp,Ar_temp,Br_temp,range(0,len(key_temp))): i = int(i) j = int(j) k = int(k) if i > 0: send_over.x(q[n]) #Look at Alice's rotation string if j > 0: send_over.h(q[n]) #Look at Bob's rotation string if k > 0: send_over.h(q[n]) send_over.measure(q[n],c[n]) #execute quantum circuit result_so = qp2.execute(circuits, backend, shots=shots) counts_so = result_so.get_counts('send_over') result_key_so = list(result_so.get_counts('send_over').keys()) Bob_result += result_key_so[0][::-1] print("Bob's results: ", Bob_result) def makeKey(rotation1,rotation2,results): key = '' count = 0 for i,j in zip(rotation1,rotation2): if i == j: key += results[count] count += 1 return key Akey = makeKey(Bob_rotate,Alice_rotate,key) Bkey = makeKey(Bob_rotate,Alice_rotate,Bob_result) print("Alice's key:",Akey) print("Bob's key: ",Bkey) #make key same length has message shortened_Akey = Akey[:len(mes)] encoded_m='' #encrypt message mes using encryption key final_key for m,k in zip(mes,shortened_Akey): encoded_c = chr(ord(m) + 2*ord(k) % 256) encoded_m += encoded_c print('encoded message: ',encoded_m) #make key same length has message shortened_Bkey = Bkey[:len(mes)] #decrypt message mes using encryption key final_key result = '' for m,k in zip(encoded_m,shortened_Bkey): encoded_c = chr(ord(m) - 2*ord(k) % 256) result += encoded_c print('recovered message:',result) #start up your quantum program backend = 'local_qasm_simulator' shots = 1 circuits = ['Eve'] Eve_result = '' for ind,l in enumerate(nlist): #define temp variables used in breaking up quantum program if message length > 10 if l < 10: key_temp = key[10*ind:10*ind+l] Ar_temp = Alice_rotate[10*ind:10*ind+l] else: key_temp = key[l*ind:l*(ind+1)] Ar_temp = Alice_rotate[l*ind:l*(ind+1)] #start up the rest of your quantum program qp3 = QuantumProgram() q = qp3.create_quantum_register('q',l) c = qp3.create_classical_register('c',l) Eve = qp3.create_circuit('Eve',[q],[c]) #prepare qubits based on key; add Hadamard gates based on Alice's and Bob's #rotation strings for i,j,n in zip(key_temp,Ar_temp,range(0,len(key_temp))): i = int(i) j = int(j) if i > 0: Eve.x(q[n]) if j > 0: Eve.h(q[n]) Eve.measure(q[n],c[n]) #execute result_eve = qp3.execute(circuits, backend, shots=shots) counts_eve = result_eve.get_counts('Eve') result_key_eve = list(result_eve.get_counts('Eve').keys()) Eve_result += result_key_eve[0][::-1] print("Eve's results: ", Eve_result) #start up your quantum program backend = 'local_qasm_simulator' shots = 1 circuits = ['Eve2'] Bob_badresult = '' for ind,l in enumerate(nlist): #define temp variables used in breaking up quantum program if message length > 10 if l < 10: key_temp = key[10*ind:10*ind+l] Eve_temp = Eve_result[10*ind:10*ind+l] Br_temp = Bob_rotate[10*ind:10*ind+l] else: key_temp = key[l*ind:l*(ind+1)] Eve_temp = Eve_result[l*ind:l*(ind+1)] Br_temp = Bob_rotate[l*ind:l*(ind+1)] #start up the rest of your quantum program qp4 = QuantumProgram() q = qp4.create_quantum_register('q',l) c = qp4.create_classical_register('c',l) Eve2 = qp4.create_circuit('Eve2',[q],[c]) #prepare qubits for i,j,n in zip(Eve_temp,Br_temp,range(0,len(key_temp))): i = int(i) j = int(j) if i > 0: Eve2.x(q[n]) if j > 0: Eve2.h(q[n]) Eve2.measure(q[n],c[n]) #execute result_eve = qp4.execute(circuits, backend, shots=shots) counts_eve = result_eve.get_counts('Eve2') result_key_eve = list(result_eve.get_counts('Eve2').keys()) Bob_badresult += result_key_eve[0][::-1] print("Bob's previous results (w/o Eve):",Bob_result) print("Bob's results from Eve:\t\t ",Bob_badresult) #make keys for Alice and Bob Akey = makeKey(Bob_rotate,Alice_rotate,key) Bkey = makeKey(Bob_rotate,Alice_rotate,Bob_badresult) print("Alice's key: ",Akey) print("Bob's key: ",Bkey) check_key = randomStringGen(len(Akey)) print('spots to check:',check_key) #find which values in rotation string were used to make the key Alice_keyrotate = makeKey(Bob_rotate,Alice_rotate,Alice_rotate) Bob_keyrotate = makeKey(Bob_rotate,Alice_rotate,Bob_rotate) # Detect Eve's interference #extract a subset of Alice's key sub_Akey = '' sub_Arotate = '' count = 0 for i,j in zip(Alice_rotate,Akey): if int(check_key[count]) == 1: sub_Akey += Akey[count] sub_Arotate += Alice_keyrotate[count] count += 1 #extract a subset of Bob's key sub_Bkey = '' sub_Brotate = '' count = 0 for i,j in zip(Bob_rotate,Bkey): if int(check_key[count]) == 1: sub_Bkey += Bkey[count] sub_Brotate += Bob_keyrotate[count] count += 1 print("subset of Alice's key:",sub_Akey) print("subset of Bob's key: ",sub_Bkey) #compare Alice and Bob's key subsets secure = True for i,j in zip(sub_Akey,sub_Bkey): if i == j: secure = True else: secure = False break; if not secure: print('Eve detected!') else: print('Eve escaped detection!') #sub_Akey and sub_Bkey are public knowledge now, so we remove them from Akey and Bkey if secure: new_Akey = '' new_Bkey = '' for index,i in enumerate(check_key): if int(i) == 0: new_Akey += Akey[index] new_Bkey += Bkey[index] print('new A and B keys: ',new_Akey,new_Bkey) if(len(mes)>len(new_Akey)): print('Your new key is not long enough.') #!!! you may need to execute this cell twice in order to see the output due to an problem with matplotlib import matplotlib.pyplot as plt import numpy as np x = np.arange(0., 30.0) y = 1-(3/4)**x plt.plot(y) plt.title('Probablity of detecting Eve') plt.xlabel('# of key bits compared') plt.ylabel('Probablity of detecting Eve') plt.show()
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/animeshnanda1/my_QAOA_qiskit
animeshnanda1
import qiskit qiskit.__qiskit_version__ # import warnings; warnings.filterwarnings("ignore") import numpy as np import networkx as nx import matplotlib.pyplot as plt from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer from qiskit.visualization import plot_histogram G = nx.Graph() Lx=6 G.add_nodes_from([i for i in range(Lx)]) G.add_edges_from([[i,i+1] for i in range(Lx-1)]) G.add_edges_from([[Lx-1,0]]) options = { 'node_color': 'y', 'node_size': 1000, 'width': 3, } nx.draw(G, with_labels=True,pos=nx.circular_layout(G),**options) print(list(G.edges())) print(G.number_of_nodes()) def ham_rot(G,gamma): L=G.number_of_nodes() qc=QuantumCircuit(L,L) for i,j in list(G.edges()): qc.cx(i,j) qc.rz(2*gamma,j) qc.cx(i,j) return qc qc = ham_rot(G, np.pi/3) print(G.edges()) qc.draw() def x_field_rot(G, beta): N = G.number_of_nodes() qc = QuantumCircuit(N,N) for n in G.nodes(): qc.rx(2*beta, n) return qc qc = x_field_rot(G, np.pi/3) qc.draw() def qaoa_circuit(G,beta,gamma): assert(len(beta)==len(gamma)) layer=len(beta) L=G.number_of_nodes() qc=QuantumCircuit(L,L) qc.h(range(L)) for k in range(layer): qc=qc+ham_rot(G,gamma[k]) qc=qc+x_field_rot(G,beta[k]) qc.measure(range(L), range(L)) return qc qc = qaoa_circuit(G,[np.pi/3], [np.pi/2]) qc.draw() def invert_counts(counts): return {k[::-1]:v for k, v in counts.items()} backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend,shots=2048) # this is just a test run for the above circuit result = job.result() print(result.get_counts()) def ising_energy(x,G): ener = 0 for i, j in G.edges(): if x[i] != x[j]: # the edge is cut ener -= 1 elif x[i] == x[j]: # the edge is cut ener += 1 return ener ising_energy('010101', G),ising_energy('111110', G) def compute_ising_energy(counts, G): energy = 0 total_counts = 0 for meas, meas_count in counts.items(): # meas and meas_count are the state and freq # print(type(meas),meas_count) obj_for_meas = ising_energy(meas, G) # calling the state to compute the energy energy += obj_for_meas * meas_count total_counts += meas_count # energy is total energy of all the states return energy / total_counts # total_counts is total number of sampling compute_ising_energy(invert_counts(result.get_counts()), G) invert_counts(result.get_counts()); # here p is the number of layer used for the optimize def get_black_box_objective(G,p,list1): backend = Aer.get_backend('qasm_simulator') def f(theta): # let's assume first half is betas, second half is gammas # theta is a 2*p length array, first 'p' entries are gamma and rest are beta beta = theta[:p] gamma = theta[p:] qc = qaoa_circuit(G,beta, gamma) counts = execute(qc, backend,shots=1024, seed_simulator=100).result().get_counts() # return the energy ener=compute_ising_energy(invert_counts(counts), G) list1.append(ener) return ener, list1 return f # p is the number of QAOA alternating operators p = 5 energy_qasm=[] obj = get_black_box_objective(G, p, energy_qasm) init_point = np.array([0.81069872, 2.2067517 , 1.83830696, 2.15579759, 0.37060699, 2.42068091, 6.1575306 , 2.2453419 , 0.85060091, 3.137845 ]) # We are going to limit the number of iterations to 2500 res_sample = minimize(obj, init_point, method='COBYLA', options={'maxiter':2500, 'disp': True}) res_sample # Once we have gotten the optimum beta and gamma we run the circuit again with the optimal_theta = res_sample['x'] qc = qaoa_circuit(G, optimal_theta[:p], optimal_theta[p:]) counts = invert_counts(execute(qc, backend,shots=2048).result().get_counts()) counts plot_histogram(counts,figsize=(12,4)) # get the best solution: best_cut, best_solution = min([(ising_energy(x,G),x) for x in counts.keys()], key=itemgetter(0)) print(f"Best string: {best_solution} with cut: {-best_cut}") # color the graph nodes by part colors = ['c' if best_solution[node] == '0' else 'y' for node in G] options = { 'node_size': 1000, 'width': 3, } nx.draw(G, with_labels=True,node_color = colors,pos=nx.circular_layout(G),**options) len(energy_qasm); def state_to_ampl_counts(vec, eps=1e-15): """Converts a statevector to a dictionary of bitstrings and corresponding amplitudes """ qubit_dims = np.log2(vec.shape[0]) if qubit_dims % 1: raise ValueError("Input vector is not a valid statevector for qubits.") qubit_dims = int(qubit_dims) counts = {} str_format = '0{}b'.format(qubit_dims) for kk in range(vec.shape[0]): val = vec[kk] if val.real**2+val.imag**2 > eps: counts[format(kk, str_format)] = val return counts def compute_ising_energy_sv(sv, G): """Compute objective from statevector For large number of qubits, this is slow. """ counts = state_to_ampl_counts(sv) return sum(ising_energy(np.array([int(x) for x in k]), G) * (np.abs(v)**2) for k, v in counts.items()) def get_qaoa_circuit_sv(G, beta, gamma): assert(len(beta) == len(gamma)) p = len(beta) # infering number of QAOA steps from the parameters passed N = G.number_of_nodes() qc = QuantumCircuit(N,N) # first, apply a layer of Hadamards qc.h(range(N)) # second, apply p alternating operators for k in range(p): qc=qc+ham_rot(G,gamma[k]) qc=qc+x_field_rot(G,beta[k]) # no measurement in the end! return qc def get_black_box_objective_sv(G,p,list1): backend = Aer.get_backend('statevector_simulator') def f(theta): # let's assume first half is betas, second half is gammas beta = theta[:p] gamma = theta[p:] qc = get_qaoa_circuit_sv(G,beta, gamma) sv = execute(qc, backend).result().get_statevector() # the sv is np.array with complex entries # return the energy ener=compute_ising_energy_sv(sv, G) list1.append(ener) return ener, list1 return f # p is the number of QAOA alternating operators energy_sv=[] obj = get_black_box_objective_sv(G, p, energy_sv) init_point = np.array([0.81069872, 2.2067517 , 0.83830696, 2.15579759, 0.37060699, 2.42068091, 6.1575306 , 2.2453419 , 3.85060091, 6.137845 ]) p = len(init_point)//2 # We are going to limit the number of iterations to 2500 res_sv = minimize(obj, init_point, method='COBYLA', options={'maxiter':2500, 'disp': True}) res_sv # Once we have gotten the optimum beta and gamma we run the circuit again with the backend = Aer.get_backend('qasm_simulator') optimal_theta = res_sv['x'] qc = qaoa_circuit(G, optimal_theta[:p], optimal_theta[p:]) counts = invert_counts(execute(qc, backend,shots=2048).result().get_counts()) counts plot_histogram(counts,figsize=(8,4)) len(energy_sv); ms=6 x_sv=np.arange(1,len(energy_sv)+1) x_qasm=np.arange(1,len(energy_qasm)+1) plt.figure(figsize=(7,6)) plt.plot(x_sv,energy_sv,'b-',markersize=ms,label='Statevector') plt.plot(x_qasm,energy_qasm,'r--',markersize=ms,label='QASM') plt.xlabel('Iterations',fontsize=16) plt.ylabel('Energy',fontsize=16) plt.xticks(fontsize=16) plt.yticks(fontsize=16) plt.legend(fontsize=16) # plt.title('Plot of gap for different $t_2$, at $t_1=0$ ') plt.grid() plt.tight_layout() # plt.yscale('log') # plt.legend(loc='upper right',fontsize=16) # plt.savefig('%s/gap_t2.pdf'%(loc), bbox_inches='tight') plt.show() print(f"Angles found with samples: beta={res_sample['x'][:p]}, gamma={res_sample['x'][p:]}") print(f"Angles found with full state: beta={res_sv['x'][:p]}, gamma={res_sv['x'][p:]}")
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from random import randrange for experiment in [100,1000,10000,100000]: heads = tails = 0 for i in range(experiment): if randrange(2) == 0: heads = heads + 1 else: tails = tails + 1 print("experiment:",experiment) print("the ratio of #heads/#tails is",(heads/tails),"heads =",heads,"tails = ",tails) print() # empty line from random import randrange # let's pick a random number between {0,1,...,99} # it is expected to be less than 60 with probability 0.6 # and greater than or equal to 60 with probability 0.4 for experiment in [100,1000,10000,100000]: heads = tails = 0 for i in range(experiment): if randrange(100) <60: heads = heads + 1 # with probability 0.6 else: tails = tails + 1 # with probability 0.4 print("experiment:",experiment) print("the ratio of #heads/#tails is",(heads/tails),"heads =",heads,"tails = ",tails) print() # empty line
https://github.com/UST-QuAntiL/nisq-analyzer-content
UST-QuAntiL
import requests from qiskit import QuantumCircuit import json def get_circuit(**kwargs): adj_matrix = kwargs["adj_matrix"] betas = kwargs["betas"] gammas = kwargs["gammas"] data = json.dumps({"adj_matrix": adj_matrix, "betas": betas, "gammas": gammas, }) headers = {"Content-Type": "application/json"} response = requests.post('http://quantum-circuit-generator:5073/algorithms/qaoa/maxcut', data=data, headers=headers) response_dict = json.loads(response.text) if response_dict['circuit'] is not None: circuit = QuantumCircuit.from_qasm_str(response_dict['circuit']) return circuit else: return None def post_processing(**kwargs): adj_matrix = kwargs["adj_matrix"] counts = kwargs["counts"] data = json.dumps({"adj_matrix": adj_matrix, "counts": counts, "objFun": "Expectation", "visualization": "True"}) headers = {"Content-Type": "application/json"} response = requests.post('http://objective-evaluation-service:5072/objective/max-cut', data=data, headers=headers) return json.dumps(response.text)
https://github.com/xin-0/QC-jupyter
xin-0
# circuit construction and execution: # - circuit, register, classical bit, executor, simulator from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer # Visualization: # - basis amplitudes, bloch vector from qiskit.visualization import plot_histogram, plot_bloch_multivector # Input state initialization: # - initial psi from qiskit.extensions import Initialize # initialized state are numpy complex arrays import numpy as np # state vector presentation from qiskit_textbook.tools import array_to_latex, random_state # construct quantum teleportation circuit def qtel(state): # circuit initialization psi = QuantumRegister(1,name="psi") alice = QuantumRegister(1,name="alice") bob = QuantumRegister(1,name="bob") crx = ClassicalRegister(1, name="crx") crz = ClassicalRegister(1, name="crz") res = ClassicalRegister(1, name="result") qtel_circ = QuantumCircuit(psi,alice,bob,crx,crz,res) #step 0 initialize psi init_gate = Initialize(state) init_gate.label = "init" qtel_circ.append(init_gate, [0]) qtel_circ.barrier() # step 1 prepare bell state between alice and bob qtel_circ.h(alice) qtel_circ.cx(alice,bob) qtel_circ.barrier() # step 2 alice gate qtel_circ.cx(psi,alice) qtel_circ.h(psi) qtel_circ.barrier() #step 3 meaure as classical bits qtel_circ.measure(alice,crx) qtel_circ.measure(psi,crz) qtel_circ.barrier() #step 4 bob gate qtel_circ.x(bob).c_if(crx,1) qtel_circ.z(bob).c_if(crz,1) reverse_init = init_gate.gates_to_uncompute() qtel_circ.append(reverse_init,[2]) qtel_circ.measure(bob,res) return qtel_circ # state initialization psi = random_state(1) #viz array_to_latex(psi, pretext="\\vert\\psi\\rangle =") plot_bloch_multivector(psi) circ = qtel(psi) circ.draw("mpl") # set up simulator state_sim_back = BasicAer.get_backend("statevector_simulator") res_vetor = execute(circ, backend=state_sim_back).result().get_statevector() plot_bloch_multivector(res_vetor) circ_sim_back = BasicAer.get_backend("qasm_simulator") counts = execute(circ, backend=circ_sim_back, shots=1024).result().get_counts() plot_histogram(counts) def modified_qtel(state): qc = QuantumCircuit(3,1) init_gate =Initialize(state) init_gate.label = "init" qc.append(init_gate, [0]) qc.barrier() qc.h(1) qc.cx(1,2) qc.barrier() qc.cx(0,1) qc.h(0) qc.barrier() qc.cx(1,2) qc.cz(0,2) qc.barrier() reverse_init_gate = init_gate.gates_to_uncompute() qc.append(reverse_init_gate,[2]) qc.measure(2,0) return qc circ_hard = modified_qtel(psi) circ_hard.draw("mpl") from qiskit import IBMQ IBMQ.enable_account(token='') IBMQ.save_account(token='',overwrite=True) IBMQ.stored_account() IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') 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(circ_hard, backend=backend, shots=8192) from qiskit.tools.monitor import job_monitor job_monitor(job_exp) # displays job status under cell # Get the results and display them exp_result = job_exp.result() exp_measurement_result = exp_result.get_counts(circ_hard) print(exp_measurement_result) plot_histogram(exp_measurement_result)
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
MonitSharma
import pennylane as qml from pennylane import numpy as np dev_fock = qml.device("strawberryfields.fock", wires=2, cutoff_dim=2) @qml.qnode(dev_fock, diff_method="parameter-shift") def photon_redirection(params): qml.FockState(1, wires=0) qml.Beamsplitter(params[0], params[1], wires=[0, 1]) return qml.expval(qml.NumberOperator(1)) def cost(params): return -photon_redirection(params) init_params = np.array([0.01, 0.01], requires_grad=True) print(cost(init_params)) dphoton_redirection = qml.grad(photon_redirection, argnum=0) print(dphoton_redirection([0.0, 0.0])) # initialise the optimizer opt = qml.GradientDescentOptimizer(stepsize=0.4) # set the number of steps steps = 100 # set the initial parameter values params = init_params for i in range(steps): # update the circuit parameters params = opt.step(cost, params) if (i + 1) % 5 == 0: print("Cost after step {:5d}: {: .7f}".format(i + 1, cost(params))) print("Optimized rotation angles: {}".format(params)) # create the devices dev_qubit = qml.device("default.qubit", wires=1) dev_fock = qml.device("strawberryfields.fock", wires=2, cutoff_dim=10) @qml.qnode(dev_qubit) def qubit_rotation(phi1, phi2): """Qubit rotation QNode""" qml.RX(phi1, wires=0) qml.RY(phi2, wires=0) return qml.expval(qml.PauliZ(0)) @qml.qnode(dev_fock, diff_method="parameter-shift") def photon_redirection(params): """The photon redirection QNode""" qml.FockState(1, wires=0) qml.Beamsplitter(params[0], params[1], wires=[0, 1]) return qml.expval(qml.NumberOperator(1)) def squared_difference(x, y): """Classical node to compute the squared difference between two inputs""" return np.abs(x - y) ** 2 def cost(params, phi1=0.5, phi2=0.1): """Returns the squared difference between the photon-redirection and qubit-rotation QNodes, for fixed values of the qubit rotation angles phi1 and phi2""" qubit_result = qubit_rotation(phi1, phi2) photon_result = photon_redirection(params) return squared_difference(qubit_result, photon_result) # initialise the optimizer opt = qml.GradientDescentOptimizer(stepsize=0.4) # set the number of steps steps = 100 # set the initial parameter values params = np.array([0.01, 0.01], requires_grad=True) for i in range(steps): # update the circuit parameters params = opt.step(cost, params) if (i + 1) % 5 == 0: print("Cost after step {:5d}: {: .7f}".format(i + 1, cost(params))) print("Optimized rotation angles: {}".format(params)) result = [1.20671364, 0.01] print(photon_redirection(result)) print(qubit_rotation(0.5, 0.1))
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.cx(1,0) #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 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} = ") #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/qiskit-community/community.qiskit.org
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute def NOT(input): q = QuantumRegister(1) # a qubit in which to encode the inout c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # We encode '0' as the qubit state |0⟩, and '1' as |1⟩ # Since the qubit is initially |0⟩, we don't need to do anything for an input of '0' # For an input of '1', we do an x to rotate the |0⟩ to |1⟩ if input=='1': # qc.x( q[0] ) # Now we've encoded the input, we can do a NOT on it using x qc.x( q[0] ) # Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0] qc.measure( q[0], c[0] ) # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output def XOR(input1,input2): q = QuantumRegister(2) # a qubit in which to encode the inout c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes if input1=='1': qc.x( q[0] ) if input2=='1': qc.x( q[1] ) qc.cx(q[0],q[1]) # just needs a cnot qc.measure(q[1],c[0]) # output from qubit 1 is measured # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output def AND(input1,input2): q = QuantumRegister(3) # a qubit in which to encode the inout c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes if input1=='1': qc.x( q[0] ) if input2=='1': qc.x( q[1] ) qc.ccx(q[0],q[1],q[2]) # just needs a ccx controlled on qubits 0 and 1 and targeted on 2 qc.measure(q[2],c[0]) # output from qubit 2 is measured # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output def NAND(input1,input2): q = QuantumRegister(3) # a qubit in which to encode the inout c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes if input1=='1': qc.x( q[0] ) if input2=='1': qc.x( q[1] ) # can be done with an AND followed by a NOT qc.ccx(q[0],q[1],q[2]) # the AND just needs a ccx controlled on qubits 0 and 1 and targeted on 2 qc.x(q[2]) # the NOT is done to the qubit containing the output qc.measure(q[2],c[0]) # output from qubit 2 is measured # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output def OR(input1,input2): q = QuantumRegister(3) # a qubit in which to encode the inout c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes if input1=='1': qc.x( q[0] ) if input2=='1': qc.x( q[1] ) # can be done with NOTs on the inputs and output of an AND qc.x(q[0]) qc.x(q[1]) qc.ccx(q[0],q[1],q[2]) # the AND just needs a ccx controlled on qubits 0 and 1 and targeted on 2 qc.x(q[2]) # the NOT is done to the qubit containing the output qc.measure(q[2],c[0]) # output from qubit 2 is measured # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output print('\nResults for the NOT gate') for input in ['0','1']: print(' NOT with input',input,'gives output',NOT(input)) print('\nResults for the XOR gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' NOT with inputs',input1,input2,'gives output',XOR(input1,input2)) print('\nResults for the AND gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' NOT with inputs',input1,input2,'gives output',AND(input1,input2)) print('\nResults for the NAND gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' NOT with inputs',input1,input2,'gives output',NAND(input1,input2)) print('\nResults for the OR gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' NOT with inputs',input1,input2,'gives output',OR(input1,input2))
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
# # Copyright 2019 the original author or authors. # # 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. # import numpy as np from qiskit import QuantumCircuit, QuantumRegister from model import circuit_node_types as node_types class CircuitGridModel(): """Grid-based model that is built when user interacts with circuit""" def __init__(self, max_wires, max_columns): self.max_wires = max_wires self.max_columns = max_columns self.nodes = np.empty((max_wires, max_columns), dtype = CircuitGridNode) def __str__(self): retval = '' for wire_num in range(self.max_wires): retval += '\n' for column_num in range(self.max_columns): # retval += str(self.nodes[wire_num][column_num]) + ', ' retval += str(self.get_node_gate_part(wire_num, column_num)) + ', ' return 'CircuitGridModel: ' + retval # def set_node(self, wire_num, column_num, node_type, radians=0, ctrl_a=-1, ctrl_b=-1, swap=-1): def set_node(self, wire_num, column_num, circuit_grid_node): self.nodes[wire_num][column_num] = \ CircuitGridNode(circuit_grid_node.node_type, circuit_grid_node.radians, circuit_grid_node.ctrl_a, circuit_grid_node.ctrl_b, circuit_grid_node.swap) # TODO: Decide whether to protect as shown below # if not self.nodes[wire_num][column_num]: # self.nodes[wire_num][column_num] = CircuitGridNode(node_type, radians) # else: # print('Node ', wire_num, column_num, ' not empty') def get_node(self, wire_num, column_num): return self.nodes[wire_num][column_num] def get_node_gate_part(self, wire_num, column_num): requested_node = self.nodes[wire_num][column_num] if requested_node and requested_node.node_type != node_types.EMPTY: # Node is occupied so return its gate return requested_node.node_type else: # Check for control nodes from gates in other nodes in this column nodes_in_column = self.nodes[:, column_num] for idx in range(self.max_wires): if idx != wire_num: other_node = nodes_in_column[idx] if other_node: if other_node.ctrl_a == wire_num or other_node.ctrl_b == wire_num: return node_types.CTRL elif other_node.swap == wire_num: return node_types.SWAP return node_types.EMPTY def get_gate_wire_for_control_node(self, control_wire_num, column_num): """Get wire for gate that belongs to a control node on the given wire""" gate_wire_num = -1 nodes_in_column = self.nodes[:, column_num] for wire_idx in range(self.max_wires): if wire_idx != control_wire_num: other_node = nodes_in_column[wire_idx] if other_node: if other_node.ctrl_a == control_wire_num or \ other_node.ctrl_b == control_wire_num: gate_wire_num = wire_idx print("Found gate: ", self.get_node_gate_part(gate_wire_num, column_num), " on wire: " , gate_wire_num) return gate_wire_num # def avail_gate_parts_for_node(self, wire_num, column_num): # retval = np.empty(0, dtype = np.int8) # node_gate_part = self.get_node_gate_part(wire_num, column_num) # if node_gate_part == node_types.EMPTY: # # No gate part in this node def compute_circuit(self): qr = QuantumRegister(self.max_wires, 'q') qc = QuantumCircuit(qr) for column_num in range(self.max_columns): for wire_num in range(self.max_wires): node = self.nodes[wire_num][column_num] if node: if node.node_type == node_types.IDEN: # Identity gate qc.iden(qr[wire_num]) elif node.node_type == node_types.X: if node.radians == 0: if node.ctrl_a != -1: if node.ctrl_b != -1: # Toffoli gate qc.ccx(qr[node.ctrl_a], qr[node.ctrl_b], qr[wire_num]) else: # Controlled X gate qc.cx(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-X gate qc.x(qr[wire_num]) else: # Rotation around X axis qc.rx(node.radians, qr[wire_num]) elif node.node_type == node_types.Y: if node.radians == 0: if node.ctrl_a != -1: # Controlled Y gate qc.cy(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Y gate qc.y(qr[wire_num]) else: # Rotation around Y axis qc.ry(node.radians, qr[wire_num]) elif node.node_type == node_types.Z: if node.radians == 0: if node.ctrl_a != -1: # Controlled Z gate qc.cz(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Z gate qc.z(qr[wire_num]) else: if node.ctrl_a != -1: # Controlled rotation around the Z axis qc.crz(node.radians, qr[node.ctrl_a], qr[wire_num]) else: # Rotation around Z axis qc.rz(node.radians, qr[wire_num]) elif node.node_type == node_types.S: # S gate qc.s(qr[wire_num]) elif node.node_type == node_types.SDG: # S dagger gate qc.sdg(qr[wire_num]) elif node.node_type == node_types.T: # T gate qc.t(qr[wire_num]) elif node.node_type == node_types.TDG: # T dagger gate qc.tdg(qr[wire_num]) elif node.node_type == node_types.H: if node.ctrl_a != -1: # Controlled Hadamard qc.ch(qr[node.ctrl_a], qr[wire_num]) else: # Hadamard gate qc.h(qr[wire_num]) elif node.node_type == node_types.SWAP: if node.ctrl_a != -1: # Controlled Swap qc.cswap(qr[node.ctrl_a], qr[wire_num], qr[node.swap]) else: # Swap gate qc.swap(qr[wire_num], qr[node.swap]) return qc class CircuitGridNode(): """Represents a node in the circuit grid""" def __init__(self, node_type, radians=0.0, ctrl_a=-1, ctrl_b=-1, swap=-1): self.node_type = node_type self.radians = radians self.ctrl_a = ctrl_a self.ctrl_b = ctrl_b self.swap = swap def __str__(self): string = 'type: ' + str(self.node_type) string += ', radians: ' + str(self.radians) if self.radians != 0 else '' string += ', ctrl_a: ' + str(self.ctrl_a) if self.ctrl_a != -1 else '' string += ', ctrl_b: ' + str(self.ctrl_b) if self.ctrl_b != -1 else '' return string
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/unitaryfund/mitiq
unitaryfund
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Unit tests for PEC.""" import warnings from functools import partial from typing import List, Optional import cirq import numpy as np import pyquil import pytest import qiskit from mitiq import QPROGRAM, SUPPORTED_PROGRAM_TYPES, Observable, PauliString from mitiq.interface import convert_from_mitiq, convert_to_mitiq, mitiq_cirq from mitiq.interface.mitiq_cirq import compute_density_matrix from mitiq.pec import ( NoisyOperation, OperationRepresentation, execute_with_pec, mitigate_executor, pec_decorator, ) from mitiq.pec.representations import ( represent_operations_in_circuit_with_local_depolarizing_noise, ) # Noisy representations of Pauli and CNOT operations for testing. def get_pauli_and_cnot_representations( base_noise: float, qubits: Optional[List[cirq.Qid]] = None, ) -> List[OperationRepresentation]: if qubits is None: qreg = cirq.LineQubit.range(2) else: qreg = qubits # Generate all ideal single-qubit Pauli operations for both qubits pauli_gates = [cirq.X, cirq.Y, cirq.Z] ideal_operations = [] for gate in pauli_gates: for qubit in qreg: ideal_operations.append(gate(qubit)) # Add CNOT operation too ideal_operations.append(cirq.CNOT(*qreg)) # Generate all representations return represent_operations_in_circuit_with_local_depolarizing_noise( ideal_circuit=cirq.Circuit(ideal_operations), noise_level=base_noise, ) BASE_NOISE = 0.02 pauli_representations = get_pauli_and_cnot_representations(BASE_NOISE) noiseless_pauli_representations = get_pauli_and_cnot_representations(0.0) def serial_executor(circuit: QPROGRAM, noise: float = BASE_NOISE) -> float: """A noisy executor function which executes the input circuit with `noise` depolarizing noise and returns the expectation value of the ground state projector. Simulation will be slow for "large circuits" (> a few qubits). """ circuit, _ = convert_to_mitiq(circuit) return compute_density_matrix( circuit, noise_model_function=cirq.depolarize, noise_level=(noise,) )[0, 0].real def batched_executor(circuits) -> List[float]: return [serial_executor(circuit) for circuit in circuits] def noiseless_serial_executor(circuit: QPROGRAM) -> float: return serial_executor(circuit, noise=0.0) def fake_executor(circuit: cirq.Circuit, random_state: np.random.RandomState): """A fake executor which just samples from a normal distribution.""" return random_state.randn() # Simple circuits for testing. q0, q1 = cirq.LineQubit.range(2) oneq_circ = cirq.Circuit(cirq.Z.on(q0), cirq.Z.on(q0)) twoq_circ = cirq.Circuit(cirq.Y.on(q1), cirq.CNOT.on(q0, q1), cirq.Y.on(q1)) def test_execute_with_pec_cirq_trivial_decomposition(): circuit = cirq.Circuit(cirq.H.on(cirq.LineQubit(0))) rep = OperationRepresentation( circuit, [NoisyOperation(circuit)], [1.0], ) unmitigated = serial_executor(circuit) mitigated = execute_with_pec( circuit, serial_executor, representations=[rep], num_samples=10, random_state=1, ) assert np.isclose(unmitigated, mitigated) def test_execute_with_pec_pyquil_trivial_decomposition(): circuit = pyquil.Program(pyquil.gates.H(0)) rep = OperationRepresentation( circuit, [NoisyOperation(circuit)], [1.0], ) unmitigated = serial_executor(circuit) mitigated = execute_with_pec( circuit, serial_executor, representations=[rep], num_samples=10, random_state=1, ) assert np.isclose(unmitigated, mitigated) def test_execute_with_pec_qiskit_trivial_decomposition(): qreg = qiskit.QuantumRegister(1) circuit = qiskit.QuantumCircuit(qreg) _ = circuit.x(qreg) rep = OperationRepresentation( circuit, [NoisyOperation(circuit)], [1.0], ) unmitigated = serial_executor(circuit) mitigated = execute_with_pec( circuit, serial_executor, representations=[rep], num_samples=10, random_state=1, ) assert np.isclose(unmitigated, mitigated) @pytest.mark.parametrize("circuit", [oneq_circ, twoq_circ]) def test_execute_with_pec_cirq_noiseless_decomposition(circuit): unmitigated = noiseless_serial_executor(circuit) mitigated = execute_with_pec( circuit, noiseless_serial_executor, representations=noiseless_pauli_representations, num_samples=10, random_state=1, ) assert np.isclose(unmitigated, mitigated) @pytest.mark.parametrize("nqubits", [1, 2]) def test_pyquil_noiseless_decomposition_multiqubit(nqubits): circuit = pyquil.Program(pyquil.gates.H(q) for q in range(nqubits)) # Decompose H(q) for each qubit q into Paulis. representations = [] for q in range(nqubits): representation = OperationRepresentation( pyquil.Program(pyquil.gates.H(q)), [ NoisyOperation(pyquil.Program(pyquil.gates.X(q))), NoisyOperation(pyquil.Program(pyquil.gates.Z(q))), ], coeffs=[0.5, 0.5], ) representations.append(representation) exact = noiseless_serial_executor(circuit) pec_value = execute_with_pec( circuit, noiseless_serial_executor, representations=representations, num_samples=500, random_state=1, force_run_all=False, ) assert np.isclose(pec_value, exact, atol=0.1) @pytest.mark.parametrize("nqubits", [1, 2]) def test_qiskit_noiseless_decomposition_multiqubit(nqubits): qreg = [qiskit.QuantumRegister(1) for _ in range(nqubits)] circuit = qiskit.QuantumCircuit(*qreg) for q in qreg: circuit.h(q) # Decompose H(q) for each qubit q into Paulis. representations = [] for q in qreg: opcircuit = qiskit.QuantumCircuit(q) opcircuit.h(q) xcircuit = qiskit.QuantumCircuit(q) xcircuit.x(q) zcircuit = qiskit.QuantumCircuit(q) zcircuit.z(q) representation = OperationRepresentation( opcircuit, [ NoisyOperation(circuit=xcircuit), NoisyOperation(circuit=zcircuit), ], [0.5, 0.5], ) representations.append(representation) exact = noiseless_serial_executor(circuit) pec_value = execute_with_pec( circuit, noiseless_serial_executor, representations=representations, num_samples=500, random_state=1, force_run_all=False, ) assert np.isclose(pec_value, exact, atol=0.1) @pytest.mark.parametrize("circuit", [oneq_circ, twoq_circ]) @pytest.mark.parametrize("executor", [serial_executor, batched_executor]) @pytest.mark.parametrize("circuit_type", SUPPORTED_PROGRAM_TYPES.keys()) def test_execute_with_pec_mitigates_noise(circuit, executor, circuit_type): """Tests that execute_with_pec mitigates the error of a noisy expectation value. """ circuit = convert_from_mitiq(circuit, circuit_type) true_noiseless_value = 1.0 unmitigated = serial_executor(circuit) if circuit_type in ["qiskit", "pennylane", "qibo"]: # Note this is an important subtlety necessary because of conversions. reps = get_pauli_and_cnot_representations( base_noise=BASE_NOISE, qubits=[cirq.NamedQubit(name) for name in ("q_0", "q_1")], ) # TODO: PEC with Qiskit is slow. # See https://github.com/unitaryfund/mitiq/issues/507. circuit, _ = convert_to_mitiq(circuit) else: reps = pauli_representations mitigated = execute_with_pec( circuit, executor, representations=reps, num_samples=100, force_run_all=False, random_state=101, ) error_unmitigated = abs(unmitigated - true_noiseless_value) error_mitigated = abs(mitigated - true_noiseless_value) assert error_mitigated < error_unmitigated assert np.isclose(mitigated, true_noiseless_value, atol=0.1) def test_execute_with_pec_with_observable(): circuit = twoq_circ obs = Observable(PauliString("ZZ")) executor = partial( mitiq_cirq.compute_density_matrix, noise_model_function=cirq.depolarize, noise_level=(BASE_NOISE,), ) true_value = 1.0 noisy_value = obs.expectation(circuit, mitiq_cirq.compute_density_matrix) pec_value = execute_with_pec( circuit, executor, observable=obs, representations=pauli_representations, num_samples=100, force_run_all=False, random_state=101, ) assert abs(pec_value - true_value) < abs(noisy_value - true_value) assert np.isclose(pec_value, true_value, atol=0.1) def test_execute_with_pec_partial_representations(): # Only use the CNOT representation. reps = [pauli_representations[-1]] pec_value = execute_with_pec( twoq_circ, executor=partial( mitiq_cirq.compute_density_matrix, noise_model_function=cirq.depolarize, noise_level=(BASE_NOISE,), ), observable=Observable(PauliString("ZZ")), representations=reps, num_samples=100, force_run_all=False, random_state=101, ) assert isinstance(pec_value, float) @pytest.mark.parametrize("circuit", [oneq_circ, twoq_circ]) @pytest.mark.parametrize("seed", (2, 3)) def test_execute_with_pec_with_different_samples(circuit, seed): """Tests that, on average, the error decreases as the number of samples is increased. """ small_sample_number = 10 large_sample_number = 100 errors = [] for num_samples in (small_sample_number, large_sample_number): mitigated = execute_with_pec( circuit, serial_executor, representations=pauli_representations, num_samples=num_samples, force_run_all=True, random_state=seed, ) errors.append(abs(mitigated - 1.0)) assert np.average(errors[1]) < np.average(errors[0]) @pytest.mark.parametrize("num_samples", [100, 500]) def test_execute_with_pec_error_scaling(num_samples: int): """Tests that the error associated to the PEC value scales as 1/sqrt(num_samples). """ _, pec_data = execute_with_pec( oneq_circ, partial(fake_executor, random_state=np.random.RandomState(0)), representations=pauli_representations, num_samples=num_samples, force_run_all=True, full_output=True, ) # The error should scale as 1/sqrt(num_samples) normalized_error = pec_data["pec_error"] * np.sqrt(num_samples) assert np.isclose(normalized_error, 1.0, atol=0.1) @pytest.mark.parametrize("precision", [0.2, 0.1]) def test_precision_option_in_execute_with_pec(precision: float): """Tests that the 'precision' argument is used to deduce num_samples.""" # For a noiseless circuit we expect num_samples = 1/precision^2: _, pec_data = execute_with_pec( oneq_circ, partial(fake_executor, random_state=np.random.RandomState(0)), representations=pauli_representations, precision=precision, force_run_all=True, full_output=True, random_state=1, ) # The error should scale as precision assert np.isclose(pec_data["pec_error"] / precision, 1.0, atol=0.15) # Check precision is ignored when num_samples is given. num_samples = 1 _, pec_data = execute_with_pec( oneq_circ, partial(fake_executor, random_state=np.random.RandomState(0)), representations=pauli_representations, precision=precision, num_samples=num_samples, force_run_all=False, full_output=True, ) assert pec_data["num_samples"] == num_samples @pytest.mark.parametrize("bad_value", (0, -1, 2)) def test_bad_precision_argument(bad_value: float): """Tests that if 'precision' is not within (0, 1] an error is raised.""" with pytest.raises(ValueError, match="The value of 'precision' should"): execute_with_pec( oneq_circ, serial_executor, representations=pauli_representations, precision=bad_value, ) def test_large_sample_size_warning(): """Tests whether a warning is raised when PEC sample size is greater than 10 ** 5. """ warnings.simplefilter("error") with pytest.raises( Warning, match="The number of PEC samples is very large.", ): execute_with_pec( oneq_circ, partial(fake_executor, random_state=np.random.RandomState(0)), representations=pauli_representations, num_samples=100001, force_run_all=False, ) def test_pec_data_with_full_output(): """Tests that execute_with_pec mitigates the error of a noisy expectation value. """ precision = 0.5 pec_value, pec_data = execute_with_pec( twoq_circ, serial_executor, precision=precision, representations=pauli_representations, full_output=True, random_state=102, ) # Get num samples from precision norm = 1.0 for op in twoq_circ.all_operations(): for rep in pauli_representations: if rep.ideal == cirq.Circuit(op): norm *= rep.norm num_samples = int((norm / precision) ** 2) # Manually get raw expectation values exp_values = [serial_executor(c) for c in pec_data["sampled_circuits"]] assert pec_data["num_samples"] == num_samples assert pec_data["precision"] == precision assert np.isclose(pec_data["pec_value"], pec_value) assert np.isclose( pec_data["pec_error"], np.std(pec_data["unbiased_estimators"]) / np.sqrt(num_samples), ) assert np.isclose(np.average(pec_data["unbiased_estimators"]), pec_value) assert np.allclose(pec_data["measured_expectation_values"], exp_values) def decorated_serial_executor(circuit: QPROGRAM) -> float: """Returns a decorated serial executor for use with other tests. The serial executor is decorated with the same representations as those that are used in the tests for trivial decomposition. """ rep = OperationRepresentation( circuit, [NoisyOperation(circuit)], [1.0], ) @pec_decorator(representations=[rep], precision=0.08, force_run_all=False) def decorated_executor(qp): return serial_executor(qp) return decorated_executor(circuit) def test_mitigate_executor_qiskit(): """Performs the same test as test_execute_with_pec_qiskit_trivial_decomposition(), but using mitigate_executor() instead of execute_with_pec(). """ qreg = qiskit.QuantumRegister(1) circuit = qiskit.QuantumCircuit(qreg) _ = circuit.x(qreg) rep = OperationRepresentation( circuit, [NoisyOperation(circuit)], [1.0], ) unmitigated = serial_executor(circuit) mitigated_executor = mitigate_executor( serial_executor, representations=[rep], num_samples=10, random_state=1, ) mitigated = mitigated_executor(circuit) assert np.isclose(unmitigated, mitigated) batched_unmitigated = batched_executor([circuit] * 3) batched_mitigated_executor = mitigate_executor( batched_executor, representations=[rep], num_samples=10, random_state=1, ) batched_mitigated = batched_mitigated_executor([circuit] * 3) assert [ np.isclose(batched_unmitigated_value, batched_mitigated_value) for batched_unmitigated_value, batched_mitigated_value in zip( batched_unmitigated, batched_mitigated ) ] def test_pec_decorator_qiskit(): """Performs the same test as test_mitigate_executor_qiskit(), but using pec_decorator() instead of mitigate_executor(). """ qreg = qiskit.QuantumRegister(1) circuit = qiskit.QuantumCircuit(qreg) _ = circuit.x(qreg) unmitigated = serial_executor(circuit) mitigated = decorated_serial_executor(circuit) assert np.isclose(unmitigated, mitigated) def test_mitigate_executor_cirq(): """Performs the same test as test_execute_with_pec_cirq_trivial_decomposition(), but using mitigate_executor() instead of execute_with_pec(). """ circuit = cirq.Circuit(cirq.H.on(cirq.LineQubit(0))) rep = OperationRepresentation( circuit, [NoisyOperation(circuit)], [1.0], ) unmitigated = serial_executor(circuit) mitigated_executor = mitigate_executor( serial_executor, representations=[rep], num_samples=10, random_state=1, ) mitigated = mitigated_executor(circuit) assert np.isclose(unmitigated, mitigated) def test_pec_decorator_cirq(): """Performs the same test as test_mitigate_executor_cirq(), but using pec_decorator() instead of mitigate_executor(). """ circuit = cirq.Circuit(cirq.H.on(cirq.LineQubit(0))) unmitigated = serial_executor(circuit) mitigated = decorated_serial_executor(circuit) assert np.isclose(unmitigated, mitigated) def test_mitigate_executor_pyquil(): """Performs the same test as test_execute_with_pec_pyquil_trivial_decomposition(), but using mitigate_executor() instead of execute_with_pec(). """ circuit = pyquil.Program(pyquil.gates.H(0)) rep = OperationRepresentation( circuit, [NoisyOperation(circuit)], [1.0], ) unmitigated = serial_executor(circuit) mitigated_executor = mitigate_executor( serial_executor, representations=[rep], num_samples=10, random_state=1, ) mitigated = mitigated_executor(circuit) assert np.isclose(unmitigated, mitigated) def test_pec_decorator_pyquil(): """Performs the same test as test_mitigate_executor_pyquil(), but using pec_decorator() instead of mitigate_executor(). """ circuit = pyquil.Program(pyquil.gates.H(0)) unmitigated = serial_executor(circuit) mitigated = decorated_serial_executor(circuit) assert np.isclose(unmitigated, mitigated) def test_doc_is_preserved(): """Tests that the doc of the original executor is preserved.""" representations = get_pauli_and_cnot_representations(0) def first_executor(circuit): """Doc of the original executor.""" return 0 mit_executor = mitigate_executor( first_executor, representations=representations ) assert mit_executor.__doc__ == first_executor.__doc__ @pec_decorator(representations=representations) def second_executor(circuit): """Doc of the original executor.""" return 0 assert second_executor.__doc__ == first_executor.__doc__ @pytest.mark.parametrize("circuit_type", SUPPORTED_PROGRAM_TYPES.keys()) def test_executed_circuits_have_the_expected_type(circuit_type): circuit = convert_from_mitiq(oneq_circ, circuit_type) circuit_type = type(circuit) # Fake executor just for testing types def type_detecting_executor(circuit: QPROGRAM): assert type(circuit) is circuit_type return 0.0 mitigated = execute_with_pec( circuit, executor=type_detecting_executor, representations=pauli_representations, num_samples=1, ) assert np.isclose(mitigated, 0.0)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test evolver problem class.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt from numpy.testing import assert_raises from qiskit import QuantumCircuit from qiskit_algorithms import TimeEvolutionProblem from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector from qiskit.circuit import Parameter from qiskit.opflow import Y, Z, One, X, Zero, PauliSumOp @ddt class TestTimeEvolutionProblem(QiskitAlgorithmsTestCase): """Test evolver problem class.""" def test_init_default(self): """Tests that all default fields are initialized correctly.""" hamiltonian = Y time = 2.5 initial_state = One evo_problem = TimeEvolutionProblem(hamiltonian, time, initial_state) expected_hamiltonian = Y expected_time = 2.5 expected_initial_state = One expected_aux_operators = None expected_t_param = None expected_param_value_dict = None self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian) self.assertEqual(evo_problem.time, expected_time) self.assertEqual(evo_problem.initial_state, expected_initial_state) self.assertEqual(evo_problem.aux_operators, expected_aux_operators) self.assertEqual(evo_problem.t_param, expected_t_param) self.assertEqual(evo_problem.param_value_map, expected_param_value_dict) @data(QuantumCircuit(1), Statevector([1, 0])) def test_init_all(self, initial_state): """Tests that all fields are initialized correctly.""" t_parameter = Parameter("t") with self.assertWarns(DeprecationWarning): hamiltonian = t_parameter * Z + Y time = 2 aux_operators = [X, Y] param_value_dict = {t_parameter: 3.2} evo_problem = TimeEvolutionProblem( hamiltonian, time, initial_state, aux_operators, t_param=t_parameter, param_value_map=param_value_dict, ) with self.assertWarns(DeprecationWarning): expected_hamiltonian = Y + t_parameter * Z expected_time = 2 expected_type = QuantumCircuit expected_aux_operators = [X, Y] expected_t_param = t_parameter expected_param_value_dict = {t_parameter: 3.2} with self.assertWarns(DeprecationWarning): self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian) self.assertEqual(evo_problem.time, expected_time) self.assertEqual(type(evo_problem.initial_state), expected_type) self.assertEqual(evo_problem.aux_operators, expected_aux_operators) self.assertEqual(evo_problem.t_param, expected_t_param) self.assertEqual(evo_problem.param_value_map, expected_param_value_dict) def test_validate_params(self): """Tests expected errors are thrown on parameters mismatch.""" param_x = Parameter("x") with self.subTest(msg="Parameter missing in dict."): with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Y")]), param_x) evolution_problem = TimeEvolutionProblem(hamiltonian, 2, Zero) with assert_raises(ValueError): evolution_problem.validate_params() if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw()
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb from qiskit import * nshots = 8192 IBMQ.load_account() provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main') device = provider.get_backend('ibm_nairobi') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor from qiskit.tools.visualization import plot_histogram q0 = QuantumRegister(1); q1 = QuantumRegister(1); q2 = QuantumRegister(1); q3 = QuantumRegister(1) c0 = ClassicalRegister(1); c1 = ClassicalRegister(1); c2 = ClassicalRegister(1); c3 = ClassicalRegister(1) qc = QuantumCircuit(q0,q1,q2,q3,c0,c1,c2,c3) # q0 e q1 estao com Alice, q2 com Charlies e q3 com Bob qc.h(q1); qc.cx(q1,q2); qc.cx(q2,q3) # prepara o estado GHZ qc.barrier() #qc.sdg(q0); qc.h(q0) # prepara o estado a ser teletransportado (y+) # prepara o estado |0> qc.barrier() qc.cx(q0,q1); qc.h(q0); qc.measure(q0,c0); qc.measure(q1,c1) # Medida de Alice na base de Bell qc.h(q2); qc.measure(q2,c2) # medida de Charlie na base +,- qc.barrier() qc.z(q3).c_if(c0, 1) # acao de Bob condicionada no 1º cbit enviado por Alice qc.x(q3).c_if(c1, 1) # acao de Bob condicionada no 2º cbit enviado por Alice qc.z(q3).c_if(c2, 1) # acao de Bob condicionada no cbit enviado por Charlie qc.barrier() #qc.sdg(q3); qc.h(q3); qc.measure(q3,c3) # passa da base circular pra computacional qc.measure(q3,c3) # mede na base computacional qc.draw(output='mpl') jobS = execute(qc, backend = simulator, shots = nshots) plot_histogram(jobS.result().get_counts(qc)) jobE = execute(qc, backend = device, shots = nshots) job_monitor(jobE) tqc = transpile(qc, device) jobE = device.run(tqc) job_monitor(jobE) plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)], bar_labels = False, legend = ['sim', 'exp'])
https://github.com/Rassska/QuantumPack
Rassska
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi qreg_q = QuantumRegister(2, 'q') creg_c = ClassicalRegister(2, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.h(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.cx(qreg_q[0], qreg_q[1]) circuit.measure(qreg_q[0], creg_c[0]) circuit.measure(qreg_q[1], creg_c[1])
https://github.com/quantum-melbourne/qiskit-challenge-22
quantum-melbourne
import matplotlib.pyplot as plt import numpy as np from qiskit.utils import algorithm_globals seed = 12345 algorithm_globals.random_seed = seed from qiskit_machine_learning.datasets import ad_hoc_data train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data( training_size=20, test_size=5, n=2, gap=0.3, plot_data=False, one_hot=False, include_sample_total=True ) def plot_adhoc_dataset(train_features, train_labels, test_features, test_labels, adhoc_total): plt.figure(figsize=(8, 8)) 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(train_features[np.where(train_labels[:] == 0), 0], train_features[np.where(train_labels[:] == 0), 1], marker='s', facecolors='w', edgecolors='b', label="A train") plt.scatter(train_features[np.where(train_labels[:] == 1), 0], train_features[np.where(train_labels[:] == 1), 1], marker='o', facecolors='w', edgecolors='r', label="B train") plt.scatter(test_features[np.where(test_labels[:] == 0), 0], test_features[np.where(test_labels[:] == 0), 1], marker='s', facecolors='b', edgecolors='w', label="A test") plt.scatter(test_features[np.where(test_labels[:] == 1), 0], test_features[np.where(test_labels[:] == 1), 1], marker='o', facecolors='r', edgecolors='w', label="B test") plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.) plt.title("Ad hoc dataset for classification") plt.show() plot_adhoc_dataset(train_features, train_labels, test_features, test_labels, adhoc_total) print(train_features[0], train_labels[0]) print(train_features[20], train_labels[20]) from qiskit.circuit.library import EfficientSU2 circuit = EfficientSU2(num_qubits=3, reps=1, insert_barriers=True) circuit.decompose().draw(output='mpl') x = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2] encode = circuit.bind_parameters(x) encode.decompose().draw(output='mpl') from qiskit.circuit.library import ZZFeatureMap circuit = ZZFeatureMap(3, reps=1, insert_barriers=True) circuit.decompose().draw(output='mpl') x = [0.1,0.2,0.3] encode = circuit.bind_parameters(x) encode.decompose().draw(output='mpl') from qiskit import Aer from qiskit.utils import QuantumInstance quantum_instance = QuantumInstance(Aer.get_backend('qasm_simulator'), shots=1024, seed_simulator=seed, seed_transpiler=seed) from qiskit.circuit.library import ZZFeatureMap from qiskit_machine_learning.kernels import QuantumKernel zz_feature_map = ZZFeatureMap(feature_dimension=2, reps=2) zz_kernel = QuantumKernel(feature_map=zz_feature_map, quantum_instance=quantum_instance) train_matrix = zz_kernel.evaluate(x_vec=train_features) test_matrix = zz_kernel.evaluate(x_vec=test_features, y_vec=train_features) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(train_matrix), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(test_matrix), interpolation='nearest', origin='upper', cmap='Reds') axs[1].set_title("testing kernel matrix") plt.show() from sklearn.svm import SVC zzpc_svc = SVC(kernel='precomputed') zzpc_svc.fit(train_matrix, train_labels) zzpc_score = zzpc_svc.score(test_matrix, test_labels) print(f'Precomputed kernel classification test score: {zzpc_score}') zzcb_svc = SVC(kernel=zz_kernel.evaluate) zzcb_svc.fit(train_features, train_labels) zzcb_score = zzcb_svc.score(test_features, test_labels) print(f'Callable kernel classification test score: {zzcb_score}') from sklearn.preprocessing import OneHotEncoder encoder = OneHotEncoder() train_labels_oh = encoder.fit_transform(train_labels.reshape(-1, 1)).toarray() test_labels_oh = encoder.fit_transform(test_labels.reshape(-1, 1)).toarray() feature_map = ZZFeatureMap(feature_dimension=2, reps=2) feature_map.decompose().draw('mpl') from qiskit.circuit.library import RealAmplitudes var_form = RealAmplitudes(2, reps=2) var_form.decompose().draw('mpl') # Optimizer callback function for plotting purposes def store_intermediate_result(evaluation, parameter, cost, stepsize, accept): evaluations.append(evaluation) parameters.append(parameter) costs.append(cost) #initial_point = np.random.random(var_form.num_parameters) initial_point = np.array([0.78969092, 0.50252316, 0.45244703, 0.83243915, 0.79595478, 0.42169888]) from qiskit_machine_learning.algorithms.classifiers import VQC from qiskit.algorithms.optimizers import SPSA vqc = VQC(feature_map=feature_map, ansatz=var_form, loss='cross_entropy', optimizer=SPSA(callback=store_intermediate_result), initial_point=initial_point, quantum_instance=Aer.get_backend('statevector_simulator')) parameters = [] costs = [] evaluations = [] vqc.fit(train_features, train_labels_oh) fig = plt.figure() plt.plot(evaluations, costs) plt.xlabel('Steps') plt.ylabel('Cost') plt.show() vqc.score(test_features, test_labels_oh) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/Chibikuri/Quantum-Othello
Chibikuri
import kivy from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.screenmanager import ScreenManager, Screen from kivy.graphics import * from kivy.uix.splitter import Splitter from kivy.uix.widget import Widget from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute kivy.require('1.11.1') class OthelloBoard(GridLayout): def __init__(self, **kwargs): super(OthelloBoard, self).__init__(**kwargs) self.cols = 3 self.add_widget(Label(text='qubit 1'), index=0) self.add_widget(Label(text='qubit 2'), index=1) self.add_widget(Label(text='qubit 3'), index=2) self.add_widget(Label(text='qubit 4'), index=0) self.add_widget(Label(text='qubit 5'), index=1) self.add_widget(Label(text='qubit 6'), index=2) self.add_widget(Label(text='qubit 7'), index=0) self.add_widget(Label(text='qubit 8'), index=1) self.add_widget(Label(text='qubit 9'), index=2) class CircuitLiner(Screen): def __init__(self, **kwargs): self.canvas = Canvas with self.canvas: Line(points=[10, 10, 20, 20, 30, 30], width=10) # class PlayScreen: # def __init__(self, **kwargs): # self.splitter = Splitter(sizable_from='right') # self.splitter.add_widget(OthelloBoard()) # self.splitter.add_widget(CircuitLiner()) class QuantumOthello(App): def build(self): sm = ScreenManager() # sm.add_widget(OthelloBoard) sm.add_widget(CircuitLiner) return OthelloBoard() if __name__ == '__main__': QuantumOthello().run()
https://github.com/tuf65651/quantum-research
tuf65651
# %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from datetime import datetime # import math # Loading your IBM Q account(s) # IBMQ.load_account() def get_results_of_last_test(): for bit in range(len(n_reg)): qc.measure(n_reg[bit], class_reg[bit]) simulate = execute(qc, backend=backend, shots=1024).result() return simulate.get_counts() def verify_results(expected): time_stamp = str(datetime.now()) if [expected] == list(results.keys()): print("PASSING - {}", test_timestamp) else: print("FAILING - {}", test_timestamp) print(f'Got - {results}') n_reg = QuantumRegister(3, 'n') m_reg = QuantumRegister(3, 'm') scratch_a = QuantumRegister(3, 'sca') scratch_b = QuantumRegister(3, 'scb') scratch_y = QuantumRegister(3, 'accm') class_reg = ClassicalRegister(3, 'y') qc = QuantumCircuit(n_reg, m_reg, scratch_a, scratch_b, scratch_y, class_reg) # Register n set to 5 qc.x(n_reg[0]) qc.x(n_reg[1]) # qc.x(n_reg[2]) # Register m set to # qc.x(m_reg[0]) qc.x(m_reg[1]) # global n_reg # global m_reg # global scratch_a # global class_reg # global backend # global qc # global test_timestamp # def before_tests(): n_reg = QuantumRegister(3, 'n') m_reg = QuantumRegister(2, 'm') scratch_reg = QuantumRegister(3, 'sca') class_reg = ClassicalRegister(3, 'y') qc = QuantumCircuit(n_reg, m_reg, scratch_reg, class_reg) backend = Aer.get_backend('qasm_simulator') test_timestamp = str(datetime.now()) from ArithmaticFunctions import * def before_each_ripple_borrow_test(): n_reg = QuantumRegister(3, 'n') m_reg = QuantumRegister(2, 'm') scratch_a = QuantumRegister(3, 'sca') qc = QuantumCircuit(n_reg, m_reg, scratch_a, class_reg) # Set control bits qc.x(m_reg[1]) return {'n_reg': n_reg, 'm_reg': m_reg, 'scratch_a': scratch_a, 'class_reg': class_reg, 'qc': qc } # global n_reg # global m_reg # global scratch_a # global class_reg # global backend # global qc # global test_timestamp # def before_tests(): n_reg = QuantumRegister(3, 'n') m_reg = QuantumRegister(2, 'm') scratch_reg = QuantumRegister(3, 'sca') class_reg = ClassicalRegister(3, 'y') qc = QuantumCircuit(n_reg, m_reg, scratch_reg, class_reg) backend = Aer.get_backend('qasm_simulator') test_timestamp = str(datetime.now()) from ArithmaticFunctions import * # global n_reg # global m_reg # global scratch_a # global class_reg # global backend # global qc # global test_timestamp # def before_tests(): n_reg = QuantumRegister(3, 'n') m_reg = QuantumRegister(2, 'm') scratch_reg = QuantumRegister(3, 'sca') class_reg = ClassicalRegister(3, 'y') qc = QuantumCircuit(n_reg, m_reg, scratch_reg, class_reg) backend = Aer.get_backend('qasm_simulator') test_timestamp = str(datetime.now()) from ArithmaticFunctions import * # 1 - 1 = 0 """ PASSED July 29 10:58am Pacific Time """ test_components = before_each_ripple_borrow_test() qc = test_components['qc'] qc.x(n_reg[0]) qc.barrier() c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[1], scratch_reg=scratch_a, start_shifting_at=0) results = get_results_of_last_test() # qc.draw() verify_results(expected='000') # 2 - 1 = 1 """ PASSED July 29 10:58am Pacific Time """ test_components = before_each_ripple_borrow_test() qc = test_components['qc'] qc.x(n_reg[1]) # qc.barrier() c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=0) results = get_results_of_last_test() # qc.draw() verify_results(expected='001') # 4 - 1 = 3 """ PASSED July 29 10:58am Pacific Time """ test_components = before_each_ripple_borrow_test() qc = test_components['qc'] qc.x(n_reg[2]) c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=0) results = get_results_of_last_test() # qc.draw() verify_results(expected='011') # 6 - 1 = 5 """ PASSED July 29 10:58am Pacific Time """ test_components = before_each_ripple_borrow_test() qc = test_components['qc'] qc.x(n_reg[1]) qc.x(n_reg[2]) # qc.barrier() c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=0) results = get_results_of_last_test() qc.draw() verify_results(expected='101') # 5 - 1 = 4 """ PASSED July 29 10:58am Pacific Time """ test_components = before_each_ripple_borrow_test() qc = test_components['qc'] qc.x(n_reg[0]) qc.x(n_reg[2]) c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=0) results = get_results_of_last_test() # qc.draw() verify_results(expected='100') # 5 - 2 = 3 """ PASSED July 29 10:58am Pacific Time """ test_components = before_each_ripple_borrow_test() qc = test_components['qc'] qc.x(n_reg[0]) qc.x(n_reg[2]) c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=1) results = get_results_of_last_test() # qc.draw() verify_results(expected='011') # 7 - 2 = 5 test_components = before_each_ripple_borrow_test() qc = test_components['qc'] qc.x(n_reg[0]) qc.x(n_reg[1]) qc.x(n_reg[2]) c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=1) results = get_results_of_last_test() # qc.draw() verify_results(expected='101') # NO-OP(7) = 7 test_components = before_each_ripple_borrow_test() qc = test_components['qc'] qc.x(n_reg[0]) qc.x(n_reg[1]) qc.x(n_reg[2]) qc.barrier() c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[False], scratch_reg=scratch_a, start_shifting_at=1) results = get_results_of_last_test() qc.draw() verify_results(expected='111') # 1 - 2 + 2 = ? test_components = before_each_ripple_borrow_test() qc = test_components['qc'] qc.x(n_reg[0]) c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=2) # ripple_carry_bits(circuit=qc, acc_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=1) qc.barrier() undo_ripple_borrow(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=2) results = get_results_of_last_test() qc.draw() # print(results) verify_results('001') # 0 - 2 + 2 = ? test_components = before_each_ripple_borrow_test() qc = test_components['qc'] c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=2) # ripple_carry_bits(circuit=qc, acc_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=1) qc.barrier() undo_ripple_borrow(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=2) results = get_results_of_last_test() qc.draw() # print(results) verify_results('000') def sub_once_mod(circuit, ) # global n_reg # global m_reg # global scratch_a # global class_reg # global backend # global qc # global test_timestamp # def before_tests(): n_reg = QuantumRegister(3, 'n') m_reg = QuantumRegister(2, 'm') scratch_reg = QuantumRegister(3, 'sca') class_reg = ClassicalRegister(3, 'y') qc = QuantumCircuit(n_reg, m_reg, scratch_reg, class_reg) backend = Aer.get_backend('qasm_simulator') test_timestamp = str(datetime.now()) from ArithmaticFunctions import * def before_each_subtraction_test(): n_reg = QuantumRegister(3, 'n') m_reg = QuantumRegister(3, 'm') scratch_reg = QuantumRegister(3, 'sca') qc = QuantumCircuit(n_reg, m_reg, scratch_reg, class_reg) return {'n_reg': n_reg, 'm_reg': m_reg, 'scratch_reg': scratch_reg, 'class_reg': class_reg, 'qc': qc } test_components = before_each_subtraction_test() qc = test_components['qc'] # Set n_reg to 00...1 qc.x(n_reg[0]) # m_reg is | 0 > sub_b_from_a_in_place(circuit=qc, minnd_reg=test_components['n_reg'], subtrhnd_reg=test_components['m_reg'], scratch_reg=test_components['scratch_reg']) results = get_results_of_last_test() # qc.draw() # print(results) verify_results('001') # Get test components comps = before_each_subtraction_test() qc = comps['qc'] # Set n_reg to 00...1 qc.x(comps['n_reg'][0]) # Set m_reg to 00...1 qc.x(comps['m_reg'][0]) qc.barrier() sub_b_from_a_in_place(circuit=qc, minnd_reg=comps['n_reg'], subtrhnd_reg=comps['m_reg'], scratch_reg=comps['scratch_reg']) results = get_results_of_last_test() qc.draw() # print(results) verify_results('000') # Get test components comps = before_each_subtraction_test() qc = comps['qc'] # Set n_reg to ...110 qc.x(comps['n_reg'][1]) qc.x(comps['n_reg'][2]) # Set m_reg to ...011 qc.x(comps['m_reg'][0]) qc.x(comps['m_reg'][1]) qc.barrier() sub_b_from_a_in_place(circuit=qc, minnd_reg=comps['n_reg'], subtrhnd_reg=comps['m_reg'], scratch_reg=comps['scratch_reg']) results = get_results_of_last_test() qc.draw() # print(results) verify_results('011') verify_results('011') # Get test components comps = before_each_subtraction_test() qc = comps['qc'] # Set n_reg to ...10 qc.x(comps['n_reg'][1]) # Set m_reg to ...01 qc.x(comps['m_reg'][0]) qc.barrier() sub_b_from_a_in_place(circuit=qc, minnd_reg=comps['n_reg'], subtrhnd_reg=comps['m_reg'], scratch_reg=comps['scratch_reg']) results = get_results_of_last_test() qc.draw() # print(results) verify_results('001') # Get test components comps = before_each_subtraction_test() qc = comps['qc'] # Set n_reg to ...110 qc.x(comps['n_reg'][0]) qc.x(comps['n_reg'][1]) # Set m_reg to ...011 qc.x(comps['m_reg'][0]) qc.x(comps['m_reg'][1]) qc.barrier() sub_b_from_a_in_place(circuit=qc, minnd_reg=comps['n_reg'], subtrhnd_reg=comps['m_reg'], scratch_reg=comps['scratch_reg']) results = get_results_of_last_test() # qc.draw() # print(results) verify_results('000') # Get test components comps = before_each_subtraction_test() qc = comps['qc'] # Set n_reg to ...110 qc.x(comps['n_reg'][0]) qc.x(comps['n_reg'][1]) qc.x(comps['n_reg'][2]) # Set m_reg to ...011 qc.x(comps['m_reg'][1]) qc.x(comps['m_reg'][2]) qc.barrier() sub_b_from_a_in_place(circuit=qc, minnd_reg=comps['n_reg'], subtrhnd_reg=comps['m_reg'], scratch_reg=comps['scratch_reg']) results = get_results_of_last_test() # qc.draw() # print(results) verify_results('001') # Get test components comps = before_each_subtraction_test() qc = comps['qc'] # Set n_reg to ...110 qc.x(comps['n_reg'][1]) qc.x(comps['n_reg'][2]) # Set m_reg to ...011 qc.x(comps['m_reg'][1]) qc.x(comps['m_reg'][0]) qc.barrier() sub_b_from_a_in_place(circuit=qc, minnd_reg=comps['n_reg'], subtrhnd_reg=comps['m_reg'], scratch_reg=comps['scratch_reg']) results = get_results_of_last_test() # qc.draw() # print(results) verify_results('011') # Get test components comps = before_each_subtraction_test() qc = comps['qc'] # Set n_reg to ...110 qc.x(comps['n_reg'][2]) # Set m_reg to ...011 qc.x(comps['m_reg'][0]) qc.barrier() sub_b_from_a_in_place(circuit=qc, minnd_reg=comps['n_reg'], subtrhnd_reg=comps['m_reg'], scratch_reg=comps['scratch_reg']) results = get_results_of_last_test() # qc.draw() # print(results) verify_results('011') # Get test components comps = before_each_subtraction_test() qc = comps['qc'] qc.x(comps['n_reg'][0]) qc.x(comps['m_reg'][1]) qc.barrier() sub_b_from_a_in_place(circuit=qc, minnd_reg=comps['n_reg'], subtrhnd_reg=comps['m_reg'], scratch_reg=comps['scratch_reg']) for bit in range(len(comps['scratch_reg'])): qc.measure(comps['scratch_reg'], comps['class_reg']) results = execute(qc, backend=backend, shots=1024).result() print(results.get_counts()) # Get test components comps = before_each_subtraction_test() qc = comps['qc'] qc.x(comps['n_reg'][0]) qc.x(comps['m_reg'][1]) qc.barrier() sub_b_from_a_in_place(circuit=qc, minnd_reg=comps['n_reg'], subtrhnd_reg=comps['m_reg'], scratch_reg=comps['scratch_reg']) results = get_results_of_last_test() print(results) # Get test components comps = before_each_subtraction_test() qc = comps['qc'] qc.x(comps['n_reg'][1]) qc.x(comps['m_reg'][1]) qc.x(comps['m_reg'][2]) qc.barrier() sub_b_from_a_in_place(circuit=qc, minnd_reg=comps['n_reg'], subtrhnd_reg=comps['m_reg'], scratch_reg=comps['scratch_reg']) results = execute(qc, backend=backend, shots=1024).result() print(results)
https://github.com/ohadlev77/sat-circuits-engine
ohadlev77
# Copyright 2022-2023 Ohad Lev. # 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, # or in the root directory of this package("LICENSE.txt"). # 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. """ `SATInterface` class. """ import os import json from typing import List, Tuple, Union, Optional, Dict, Any from sys import stdout from datetime import datetime from hashlib import sha256 from qiskit import transpile, QuantumCircuit, qpy from qiskit.result.counts import Counts from qiskit.visualization.circuit.text import TextDrawing from qiskit.providers.backend import Backend from qiskit.transpiler.passes import RemoveBarriers from IPython import display from matplotlib.figure import Figure from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit from sat_circuits_engine.constraints_parse import ParsedConstraints from sat_circuits_engine.interface.circuit_decomposition import decompose_operator from sat_circuits_engine.interface.counts_visualization import plot_histogram from sat_circuits_engine.interface.translator import ConstraintsTranslator from sat_circuits_engine.classical_processing import ( find_iterations_unknown, calc_iterations, ClassicalVerifier, ) from sat_circuits_engine.interface.interactive_inputs import ( interactive_operator_inputs, interactive_solutions_num_input, interactive_run_input, interactive_backend_input, interactive_shots_input, ) # Local globlas for visualization of charts and diagrams IFRAME_WIDTH = "100%" IFRAME_HEIGHT = "700" class SATInterface: """ An interface for building, running and mining data from n-SAT problems quantum circuits. There are 2 options to use this class: (1) Using an interactive interface (intuitive but somewhat limited) - for this just initiate a bare instance of this class: `SATInterface()`. (2) Using the API defined by this class, that includes the following methods: * The following descriptions are partial, for full annotations see the methods' docstrings. - `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination: (a) (high_level_constraints_string + high_level_vars) - for constraints in a high-level format. (b) (num_input_qubits + constraints_string) - for constraints in a low-level foramt. * For formats annotations see `constriants_format.ipynb` in the main directory. - `obtain_grover_operator`: obtains the suitable grover operator for the constraints. - `save_display_grover_operator`: saves and displays data generated by the `obtain_grover_operator` method. - `obtain_overall_circuit`: obtains the suitable overall SAT circuit. - `save_display_overall_circuit: saves and displays data generated by the `obtain_overall_circuit` method. - `run_overall_circuit`: executes the overall SAT circuit. - `save_display_results`: saves and displays data generated by the `run_overall_circuit` method. It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses of this class, in addition to reading `constraints_format.ipynb`, which is a must for using this package properly. Both notebooks are in ther main directory. """ def __init__( self, num_input_qubits: Optional[int] = None, constraints_string: Optional[str] = None, high_level_constraints_string: Optional[str] = None, high_level_vars: Optional[Dict[str, int]] = None, name: Optional[str] = None, save_data: Optional[bool] = True, ) -> None: """ Accepts the combination of paramters: (high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string). Exactly one combination is accepted. In other cases either an iteractive user interface will be called to take user's inputs, or an exception will be raised due to misuse of the API. Args: num_input_qubits (Optional[int] = None): number of input qubits. constraints_string (Optional[str] = None): a string of constraints in a low-level format. high_level_constraints_string (Optional[str] = None): a string of constraints in a high-level format. high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures the high-level variables - keys are names and values are bits-lengths. name (Optional[str] = None): a name for this object, if None than the generic name "SAT" is given automatically. save_data (Optional[bool] = True): if True, saves all data and metadata generated by this class to a unique data folder (by using the `save_XXX` methods of this class). Raises: SyntaxError - if a forbidden combination of arguments has been provided. """ if name is None: name = "SAT" self.name = name # Creating a directory for data to be saved if save_data: self.time_created = timestamp(datetime.now()) self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/" os.mkdir(self.dir_path) print(f"Data will be saved into '{self.dir_path}'.") # Initial metadata, more to be added by this class' `save_XXX` methods self.metadata = { "name": self.name, "datetime": self.time_created, "num_input_qubits": num_input_qubits, "constraints_string": constraints_string, "high_level_constraints_string": high_level_constraints_string, "high_level_vars": high_level_vars, } self.update_metadata() # Identifying user's platform, for visualization purposes self.identify_platform() # In the case of low-level constraints format, that is the default value self.high_to_low_map = None # Case A - interactive interface if (num_input_qubits is None or constraints_string is None) and ( high_level_constraints_string is None or high_level_vars is None ): self.interactive_interface() # Case B - API else: self.high_level_constraints_string = high_level_constraints_string self.high_level_vars = high_level_vars # Case B.1 - high-level format constraints inputs if num_input_qubits is None or constraints_string is None: self.num_input_qubits = sum(self.high_level_vars.values()) self.high_to_low_map, self.constraints_string = ConstraintsTranslator( self.high_level_constraints_string, self.high_level_vars ).translate() # Case B.2 - low-level format constraints inputs elif num_input_qubits is not None and constraints_string is not None: self.num_input_qubits = num_input_qubits self.constraints_string = constraints_string # Misuse else: raise SyntaxError( "SATInterface accepts the combination of paramters:" "(high_level_constraints_string + high_level_vars) or " "(num_input_qubits + constraints_string). " "Exactly one combination is accepted, not both." ) self.parsed_constraints = ParsedConstraints( self.constraints_string, self.high_level_constraints_string ) def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None: """ Updates the metadata file (in the unique data folder of a given `SATInterface` instance). Args: update_metadata (Optional[Dict[str, Any]] = None): - If None - just dumps `self.metadata` into the metadata JSON file. - If defined - updates the `self.metadata` attribute and then dumps it. """ if update_metadata is not None: self.metadata.update(update_metadata) with open(f"{self.dir_path}metadata.json", "w") as metadata_file: json.dump(self.metadata, metadata_file, indent=4) def identify_platform(self) -> None: """ Identifies user's platform. Writes True to `self.jupyter` for Jupyter notebook, False for terminal. """ # If True then the platform is a terminal/command line/shell if stdout.isatty(): self.jupyter = False # If False, we assume the platform is a Jupyter notebook else: self.jupyter = True def output_to_platform( self, *, title: str, output_terminal: Union[TextDrawing, str], output_jupyter: Union[Figure, str], display_both_on_jupyter: Optional[bool] = False, ) -> None: """ Displays output to user's platform. Args: title (str): a title for the output. output_terminal (Union[TextDrawing, str]): text to print for a terminal platform. output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform. can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file, e.g PDF files. display_both_on_jupyter (Optional[bool] = False): if True, displays both `output_terminal` and `output_jupyter` in a Jupyter notebook platform. Raises: TypeError - in the case of misusing the `output_jupyter` argument. """ print() print(title) if self.jupyter: if isinstance(output_jupyter, str): display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT)) elif isinstance(output_jupyter, Figure): display.display(output_jupyter) else: raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.") if display_both_on_jupyter: print(output_terminal) else: print(output_terminal) def interactive_interface(self) -> None: """ An interactive CLI that allows exploiting most (but not all) of the package's features. Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module. Divided into 3 main stages: 1. Obtaining Grover's operator for the SAT problem. 2. Obtaining the overall SAT cirucit. 3. Executing the circuit and parsing the results. The interface is built in a modular manner such that a user can halt at any stage. The defualt settings for the interactive user intreface are: 1. `name = "SAT"`. 2. `save_data = True`. 3. `display = True`. 4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`. 5. Backends are limited to those defined in the global-constant-like function `BACKENDS`: - Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now. Due to these default settings the interactive CLI is somewhat restrictive, for full flexibility a user should use the API and not the CLI. """ # Handling operator part operator_inputs = interactive_operator_inputs() self.num_input_qubits = operator_inputs["num_input_qubits"] self.high_to_low_map = operator_inputs["high_to_low_map"] self.constraints_string = operator_inputs["constraints_string"] self.high_level_constraints_string = operator_inputs["high_level_constraints_string"] self.high_level_vars = operator_inputs["high_level_vars"] self.parsed_constraints = ParsedConstraints( self.constraints_string, self.high_level_constraints_string ) self.update_metadata( { "num_input_qubits": self.num_input_qubits, "constraints_string": self.constraints_string, "high_level_constraints_string": self.high_level_constraints_string, "high_level_vars": self.high_level_vars, } ) obtain_grover_operator_output = self.obtain_grover_operator() self.save_display_grover_operator(obtain_grover_operator_output) # Handling overall circuit part solutions_num = interactive_solutions_num_input() if solutions_num is not None: backend = None if solutions_num == -1: backend = interactive_backend_input() overall_circuit_data = self.obtain_overall_sat_circuit( obtain_grover_operator_output["operator"], solutions_num, backend ) self.save_display_overall_circuit(overall_circuit_data) # Handling circuit execution part if interactive_run_input(): if backend is None: backend = interactive_backend_input() shots = interactive_shots_input() counts_parsed = self.run_overall_sat_circuit( overall_circuit_data["circuit"], backend, shots ) self.save_display_results(counts_parsed) print() print(f"Done saving data into '{self.dir_path}'.") def obtain_grover_operator( self, transpile_kwargs: Optional[Dict[str, Any]] = None ) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]: """ Obtains the suitable `GroverConstraintsOperator` object for the constraints, decomposes it using the `circuit_decomposition.py` module and transpiles it according to `transpile_kwargs`. Args: transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function. The defualt is set to the global constant `TRANSPILE_KWARGS`. Returns: (Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]): - 'operator' (GroverConstraintsOperator):the high-level blocks operator. - 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator. * For annotations regarding the decomposition method see the `circuit_decomposition` module. - 'transpiled_operator' (QuantumCircuit): the transpiled operator. *** The high-level operator and the decomposed operator are generated with barriers between constraints as default for visualizations purposes. The barriers are stripped off before transpiling so the the transpiled operator object contains no barriers. *** - 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None): A map of high-level variables with their allocated bit-indexes in the input register. """ print() print( "The system synthesizes and transpiles a Grover's " "operator for the given constraints. Please wait.." ) if transpile_kwargs is None: transpile_kwargs = TRANSPILE_KWARGS self.transpile_kwargs = transpile_kwargs operator = GroverConstraintsOperator( self.parsed_constraints, self.num_input_qubits, insert_barriers=True ) decomposed_operator = decompose_operator(operator) no_baerriers_operator = RemoveBarriers()(operator) transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs) print("Done.") return { "operator": operator, "decomposed_operator": decomposed_operator, "transpiled_operator": transpiled_operator, "high_level_to_bit_indexes_map": self.high_to_low_map, } def save_display_grover_operator( self, obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]], display: Optional[bool] = True, ) -> None: """ Handles saving and displaying data generated by the `self.obtain_grover_operator` method. Args: obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]): the dictionary returned upon calling the `self.obtain_grover_operator` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ # Creating a directory to save operator's data operator_dir_path = f"{self.dir_path}grover_operator/" os.mkdir(operator_dir_path) # Titles for displaying objects, by order of `obtain_grover_operator_output` titles = [ "The operator diagram - high level blocks:", "The operator diagram - decomposed:", f"The transpiled operator diagram saved into '{operator_dir_path}'.\n" f"It's not presented here due to its complexity.\n" f"Please note that barriers appear in the high-level diagrams above only for convenient\n" f"visual separation between constraints.\n" f"Before transpilation all barriers are removed to avoid redundant inefficiencies.", ] for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()): # Generic path and name for files to be saved files_path = f"{operator_dir_path}{op_name}" # Generating a circuit diagrams figure figure_path = f"{files_path}.pdf" op_obj.draw("mpl", filename=figure_path, fold=-1) # Generating a QPY serialization file for the circuit object qpy_file_path = f"{files_path}.qpy" with open(qpy_file_path, "wb") as qpy_file: qpy.dump(op_obj, qpy_file) # Original high-level operator and decomposed operator if index < 2 and display: # Displaying to user self.output_to_platform( title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path ) # Transpiled operator elif index == 2: # Output to user, not including the circuit diagram print() print(titles[index]) print() print(f"The transpilation kwargs are: {self.transpile_kwargs}.") transpiled_operator_depth = op_obj.depth() transpiled_operator_gates_count = op_obj.count_ops() print(f"Transpiled operator depth: {transpiled_operator_depth}.") print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.") print(f"Total number of qubits: {op_obj.num_qubits}.") # Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator qasm_file_path = f"{files_path}.qasm" flatten_circuit(op_obj).qasm(filename=qasm_file_path) # Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop break # Mapping from high-level variables to bit-indexes will be displayed as well mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"] if mapping: print() print(f"The high-level variables mapping to bit-indexes:\n{mapping}") print() print( f"Saved into '{operator_dir_path}':\n", " Circuit diagrams for all levels.\n", " QPY serialization exports for all levels.\n", " QASM 2.0 export only for the transpiled level.", ) with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file: operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest() self.update_metadata( { "high_level_to_bit_indexes_map": self.high_to_low_map, "transpile_kwargs": self.transpile_kwargs, "transpiled_operator_depth": transpiled_operator_depth, "transpiled_operator_gates_count": transpiled_operator_gates_count, "operator_qpy_sha256": operator_qpy_sha256, } ) def obtain_overall_sat_circuit( self, grover_operator: GroverConstraintsOperator, solutions_num: int, backend: Optional[Backend] = None, ) -> Dict[str, SATCircuit]: """ Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem. Args: grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem. solutions_num (int): number of solutions for the SAT problem. In the case the number of solutions is unknown, specific negative values are accepted: * '-1' - for launching a classical iterative stochastic process that finds an adequate number of iterations - by calling the `find_iterations_unknown` function (see its docstrings for more information). * '-2' - for generating a dynamic circuit that iterates over Grover's iterator until a solution is obtained, using weak measurements. TODO - this feature isn't ready yet. backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`, a backend object to execute the depicted iterative prcess upon should be provided. Returns: (Dict[str, SATCircuit]): - 'circuit' key for the overall SAT circuit. - 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's iterator (operator + diffuser). Useful for visualization purposes. *** The concise circuit is generated with barriers between segments as default for visualizations purposes. In the actual circuit there no barriers. *** """ # -1 = Unknown number of solutions - iterative stochastic process print() if solutions_num == -1: assert backend is not None, "Need to specify a backend if `solutions_num == -1`." print("Please wait while the system checks various solutions..") circuit, iterations = find_iterations_unknown( self.num_input_qubits, grover_operator, self.parsed_constraints, precision=10, backend=backend, ) print() print(f"An adequate number of iterations found = {iterations}.") # -2 = Unknown number of solutions - implement a dynamic circuit # TODO this feature isn't fully implemented yet elif solutions_num == -2: print("The system builds a dynamic circuit..") circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None) circuit.add_input_reg_measurement() iterations = None # Known number of solutions else: print("The system builds the overall circuit..") iterations = calc_iterations(self.num_input_qubits, solutions_num) print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.") circuit = SATCircuit( self.num_input_qubits, grover_operator, iterations, insert_barriers=False ) circuit.add_input_reg_measurement() self.iterations = iterations # Obtaining a SATCircuit object with one iteration for concise representation concise_circuit = SATCircuit( self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True ) concise_circuit.add_input_reg_measurement() return {"circuit": circuit, "concise_circuit": concise_circuit} def save_display_overall_circuit( self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True ) -> None: """ Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method. Args: obtain_overall_sat_circuit_output(Dict[str, SATCircuit]): the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ circuit = obtain_overall_sat_circuit_output["circuit"] concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"] # Creating a directory to save overall circuit's data overall_circuit_dir_path = f"{self.dir_path}overall_circuit/" os.mkdir(overall_circuit_dir_path) # Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise") concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf" concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1) # Displaying the concise circuit to user if display: if self.iterations: self.output_to_platform( title=( f"The high level circuit contains {self.iterations}" f" iterations of the following form:" ), output_terminal=concise_circuit.draw("text"), output_jupyter=concise_circuit_fig_path, ) # Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET else: dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf" circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1) self.output_to_platform( title="The dynamic circuit diagram:", output_terminal=circuit.draw("text"), output_jupyter=dynamic_circuit_fig_path, ) if self.iterations: transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs) print() print(f"The transpilation kwargs are: {self.transpile_kwargs}.") transpiled_overall_circuit_depth = transpiled_overall_circuit.depth() transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops() print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.") print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.") print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.") print() print("Exporting the full overall SAT circuit object..") export_files_path = f"{overall_circuit_dir_path}overall_circuit" with open(f"{export_files_path}.qpy", "wb") as qpy_file: qpy.dump(circuit, qpy_file) if self.iterations: transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm") print() print( f"Saved into '{overall_circuit_dir_path}':\n", " A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n", " QPY serialization export for the full overall SAT circuit object.", ) if self.iterations: print(" QASM 2.0 export for the transpiled full overall SAT circuit object.") metadata_update = { "num_total_qubits": circuit.num_qubits, "num_iterations": circuit.iterations, } if self.iterations: metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,) metadata_update[ "transpiled_overall_circuit_gates_count" ] = transpiled_overall_circuit_gates_count self.update_metadata(metadata_update) @timer_dec("Circuit simulation execution time = ") def run_overall_sat_circuit( self, circuit: QuantumCircuit, backend: Backend, shots: int ) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]: """ Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times. Args: circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`) to execute. backend (Backend): backend to execute `circuit` upon. shots (int): number of execution shots. Returns: (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): dict object returned by `self.parse_counts` - see this method's docstrings for annotations. """ # Defines also instance attributes to use in other methods self.backend = backend self.shots = shots print() print(f"The system is running the circuit {shots} times on {backend}, please wait..") print("This process might take a while.") job = backend.run(transpile(circuit, backend), shots=shots) counts = job.result().get_counts() print("Done.") parsed_counts = self.parse_counts(counts) return parsed_counts def parse_counts( self, counts: Counts ) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]: """ Parses a `Counts` object into several desired datas (see 'Returns' section). Args: counts (Counts): the `Counts` object to parse. Returns: (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): 'counts' (Counts) - the original `Counts` object. 'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order. 'distilled_solutions' (List[str]): list of solutions (bitstrings). 'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a dictionary with variable-names as keys and their integer values as values). """ # Sorting results in an a descending order counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True) # Generating a set of distilled verified-only solutions verifier = ClassicalVerifier(self.parsed_constraints) distilled_solutions = set() for count_item in counts_sorted: if not verifier.verify(count_item[0]): break distilled_solutions.add(count_item[0]) # In the case of high-level format in use, translating `distilled_solutions` into integer values high_level_vars_values = None if self.high_level_constraints_string and self.high_level_vars: # Container for dictionaries with variables integer values high_level_vars_values = [] for solution in distilled_solutions: # Keys are variable-names and values are their integer values solution_vars = {} for var, bits_bundle in self.high_to_low_map.items(): reversed_solution = solution[::-1] var_bitstring = "" for bit_index in bits_bundle: var_bitstring += reversed_solution[bit_index] # Translating to integer value solution_vars[var] = int(var_bitstring, 2) high_level_vars_values.append(solution_vars) return { "counts": counts, "counts_sorted": counts_sorted, "distilled_solutions": distilled_solutions, "high_level_vars_values": high_level_vars_values, } def save_display_results( self, run_overall_sat_circuit_output: Dict[ str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]] ], display: Optional[bool] = True, ) -> None: """ Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method. Args: run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): the dictionary returned upon calling the `self.run_overall_sat_circuit` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ counts = run_overall_sat_circuit_output["counts"] counts_sorted = run_overall_sat_circuit_output["counts_sorted"] distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"] high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"] # Creating a directory to save results data results_dir_path = f"{self.dir_path}results/" os.mkdir(results_dir_path) # Defining custom dimensions for the custom `plot_histogram` of this package histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7) histogram_fig_height = 5 histogram_figsize = (histogram_fig_width, histogram_fig_height) histogram_path = f"{results_dir_path}histogram.pdf" plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path) if display: # Basic output text output_text = ( f"All counts:\n{counts_sorted}\n" f"\nDistilled solutions ({len(distilled_solutions)} total):\n" f"{distilled_solutions}" ) # Additional outputs for a high-level constraints format if high_level_vars_values: # Mapping from high-level variables to bit-indexes will be displayed as well output_text += ( f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}" ) # Actual integer solutions will be displayed as well additional_text = "" for solution_index, solution in enumerate(high_level_vars_values): additional_text += f"Solution {solution_index + 1}: " for var_index, (var, value) in enumerate(solution.items()): additional_text += f"{var} = {value}" if var_index != len(solution) - 1: additional_text += ", " else: additional_text += "\n" output_text += f"\n\nHigh-level format solutions: \n{additional_text}" self.output_to_platform( title=f"The results for {self.shots} shots are:", output_terminal=output_text, output_jupyter=histogram_path, display_both_on_jupyter=True, ) results_dict = { "high_level_to_bit_indexes_map": self.high_to_low_map, "solutions": list(distilled_solutions), "high_level_solutions": high_level_vars_values, "counts": counts_sorted, } with open(f"{results_dir_path}results.json", "w") as results_file: json.dump(results_dict, results_file, indent=4) self.update_metadata( { "num_solutions": len(distilled_solutions), "backend": str(self.backend), "shots": self.shots, } )
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import datetime import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt plt.rcParams.update({"text.usetex": True}) plt.rcParams["figure.figsize"] = (6,4) mpl.rcParams["figure.dpi"] = 200 from qiskit_ibm_runtime import Estimator, Session, QiskitRuntimeService, Options from qiskit.quantum_info import SparsePauliOp from qiskit import QuantumCircuit service = QiskitRuntimeService() backend_simulator = "backend_simulator" backend = "ibmq_montreal" qubits = 4 trotter_layer = QuantumCircuit(qubits) trotter_layer.rx(0.1, range(qubits)) trotter_layer.cx(0, 1) trotter_layer.cx(2, 3) trotter_layer.rz(-0.2, [1, 3]) trotter_layer.cx(0, 1) trotter_layer.cx(2, 3) trotter_layer.cx(1, 2) trotter_layer.rz(-0.2, 2) trotter_layer.cx(1, 2) num_steps = 6 trotter_circuit_list = [] for i in range(1, num_steps): trotter_circuit = QuantumCircuit(qubits) for _ in range(i): trotter_circuit = trotter_circuit.compose(trotter_layer) trotter_circuit_list.append(trotter_circuit) print(f'Trotter circuit with {i} Trotter steps`) display(trotter_circuit.draw(fold=-1)) obs = SparsePauliOp("Z"*qubits) obs_list = [obs]*len(trotter_circuit_list) options = Options() options.execution.shots = 1000 options.optimization_level = 0 # No optimization options.resilience_level = 0 # No mitigation with Session(service=service, backend=backend_simulator) as session: estimator_sim = Estimator(session=session, options=options) job_sim = estimator_sim.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_sim.job_id) print(job_sim.result()) expvals_ideal = job_sim.result().values expvals_ideal_variance = [metadata['variance']/metadata['shots'] for metadata in job_sim.result().metadata] std_error_ideal = np.sqrt(expvals_ideal_variance) options = Options() options.execution.shots = 1000 options.optimization_level = 0 # No optimization options.resilience_level = 0 # No error mitigation with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job.job_id) print(job.result()) expvals_unmit = job.result().values expvals_unmit_variance = [metadata['variance']/metadata['shots'] for metadata in job.result().metadata] std_error_unmit = np.sqrt(expvals_unmit_variance) options = Options() options.execution.shots = 1000 options.optimization_level = 3 # Dynamical decoupling options.resilience_level = 0 # No error mitigation with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job_dd = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_dd.job_id) print(job_dd.result()) expvals_unmit_dd = job_dd.result().values expvals_unmit_dd_variance = [metadata['variance']/metadata['shots'] for metadata in job_dd.result().metadata] std_error_dd = np.sqrt(expvals_unmit_dd_variance) plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_dd, std_error_dd, fmt = 'o', linestyle = '-', capsize=4, c='blue', label='Dynamical decoupling') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() options = Options() options.resilience_level = 1 # T-REx options.optimization_level = 0 # No optimization options.execution.shots = 1000 with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job_trex = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_trex.job_id) print(job_trex.result()) expvals_unmit_trex = job_trex.result().values expvals_unmit_trex_variance = [metadata['variance']/metadata['shots'] for metadata in job_trex.result().metadata] std_error_trex = np.sqrt(expvals_unmit_trex_variance) plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() options = Options() options.execution.shots = 1000 options.optimization_level = 0 # No optimization options.resilience_level = 2 # ZNE with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job_zne = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_zne.job_id) print(job_zne.result()) expvals_unmit_zne = job_zne.result().values # Standard error: coming soon! plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE') plt.xlabel('No. Trotter Steps') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() def interim_results_callback(job_id, result): now = datetime.datetime.now() print(now, "*** Callback ***", result, "\n") options = Options() options.optimization_level = 0 # No optimization options.execution.shots = 100 options.resilience_level = 3 # PEC options.environment.callback = interim_results_callback with Session(service=service, backend=backend) as session: estimator_pec = Estimator(session=session, options=options) job_pec = estimator_pec.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_pec.job_id) expvals_pec = job_pec.result().values std_error_pec = [metadata['standard_error'] for metadata in job_pec.result().metadata] plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() print(job_pec.result()) pec_metadata = job_pec.result().metadata fig, ax = plt.subplots() fig.subplots_adjust(right=0.75) twin1 = ax.twinx() twin2 = ax.twinx() twin3 = ax.twinx() twin2.spines.right.set_position(("axes", 1.2)) twin3.spines.right.set_position(("axes", 1.4)) p1, = ax.plot(range(1, num_steps), [m["total_mitigated_layers"] for m in pec_metadata] , "b-", label="Total mitigated layers") p2, = twin1.plot(range(1, num_steps), [m["sampling_overhead"] for m in pec_metadata], "r-", label="Sampling overhead") p3, = twin2.plot(range(1, num_steps), [m["samples"] for m in pec_metadata], "g-", label="Samples") p4, = twin3.plot(range(1, num_steps), [m["shots"] for m in pec_metadata], "c-", label="Shots") ax.set_ylim(0, 20) twin1.set_ylim(0, 2.8) twin2.set_ylim(0, 300) twin3.set_ylim(0, 35000) ax.set_xlabel("No. Trotter Steps") ax.set_ylabel("Total mitigated layers") twin1.set_ylabel("Sampling overhead") twin2.set_ylabel("Samples") twin3.set_ylabel("Shots") ax.yaxis.label.set_color(p1.get_color()) twin1.yaxis.label.set_color(p2.get_color()) twin2.yaxis.label.set_color(p3.get_color()) twin3.yaxis.label.set_color(p4.get_color()) tkw = dict(size=4, width=1.5) ax.tick_params(axis='y', colors=p1.get_color(), **tkw) twin1.tick_params(axis='y', colors=p2.get_color(), **tkw) twin2.tick_params(axis='y', colors=p3.get_color(), **tkw) twin3.tick_params(axis='y', colors=p4.get_color(), **tkw) plt.xticks([1, 2, 3, 4, 5]) ax.legend(handles=[p1, p2, p3, p4]) plt.title('PEC metadata') plt.show() from matplotlib.pyplot import figure plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx') plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE') plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC') plt.title('Trotter circuits expectation value') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() options = Options() options.execution.shots = 1000 options.optimization_level = 0 # no optimization options.resilience_level = 2 # ZNE options.resilience.noise_factors = [1, 2, 3, 4] options.resilience.noise_amplifier = "LocalFoldingAmplifier" options.resilience.extrapolator = "QuadraticExtrapolator" with Session(service=service, backend='ibmq_montreal') as session: estimator = Estimator(session=session, options=options) job_zne_options = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_zne_options.job_id) print(job_zne_options.result()) from qiskit.tools import jupyter %qiskit_version_table %qiskit_copyright
https://github.com/jtiosue/QAOAPython
jtiosue
import qiskit, time from numpy import pi # define pi so that in string gates we can have pi as an angle. # Because we use eval for string gates. For example, gate = "rz(pi/2, 1)". name = "IBM" simulators = simulator, unitary_simulator, state_simulator = ( "qasm_simulator", "unitary_simulator", "statevector_simulator" ) quantum_computer = "ibmqx4" def apply_credentials(): print("\nApplying credentials...\n") # with open("qSonify/qc/APItoken.txt") as f: APItoken = f.read().strip() try: # qiskit.IBMQ.enable_account(APItoken) qiskit.IBMQ.load_accounts() print('Available backends:') print(qiskit.IBMQ.backends()) print(qiskit.Aer.backends()) print("\nCredientials applied\n") except: print('Something went wrong.\nDid you enter a correct token?') #### String algorithm methods #### # With this, we can write an algorithm as a list with any of the keys in # GATE_ARGUMENTS. So, for example, # alg = ["H(0)", "RX(pi/2, 1)", "CX(1, 2)", "u3(pi/2, pi/4, .2, 0)"] # then apply it to a qiskit.QuantumCircuit and qiskit.QuantumRegister qc and r # respectively by calling # apply_string_algorithm(alg, r, qc). p = lambda x: ("reg[%d]",)*x a = lambda x: ("%g",)*x b = lambda x, y: "(" + ", ".join(a(x)+p(y)) + ")" GATE_PARAMS = { ## The first number is the number of parameters, ## The second number is the number of qubit arguments. "ccx": (0, 3), "ch": (0, 2), "crz": (1, 2), "cswap": (0, 3), "cu1": (1, 2), "cu3": (3, 2), "cx": (0, 2), "cx_base": (0, 2), "cy": (0, 2), "cz": (0, 2), "h": (0, 1), "iden": (0, 1), "rx": (1, 1), "ry": (1, 1), "rz": (1, 1), "rzz": (1, 2), "s": (0, 1), "sdg": (0, 1), "swap": (0, 2), "t": (0, 1), "tdg": (0, 1), "u0": (1, 1), "u1": (1, 1), "u2": (2, 1), "u3": (3, 1), "u_base": (3, 1), "x": (0, 1), "y": (0, 1), "z": (0, 1), } GATE_ARGUMENTS = {gate: b(*args) for gate, args in GATE_PARAMS.items()} GATE_ARGUMENTS["measure"] = "(reg[%d], c_reg[%d])" def get_gate_info(gate): """ gate: str, string gate. ie H(0), or "cx(1, 0)". returns: tuple, (gate_name (str), gate_args (tuple)). """ gate = gate.strip().lower().replace("cnot", "cx") i = gate.index("(") gate_name, gate_args = gate[:i], eval(gate[i:]) try: len(gate_args) except TypeError: gate_args = gate_args, return gate_name, gate_args def get_num_qubits(algorithm): """ Determine the max qubit value used in the algorithm. algorithm: iterable, each element must be a string gate, as in apply_string_gate above. ie, algorithm = ["h(0)", "cx(0, 1)", "rx(pi/4, 1)",..] returns: int, max qubit value in algorithm. """ n = -1 for gate in algorithm: gate_name, gate_args = get_gate_info(gate) if gate_name == "measure": m = gate_args[0] # elif sum(GATE_PARAMS[gate_name]) == 1: m = gate_args else: m = max(gate_args[GATE_PARAMS[gate_name][0]:]) n = max(n, m) return n + 1 def apply_string_gate(gate, reg, cir, c_reg=None): """ gate: str, one of the elements in GATE_ARGUMENTS.keys() + a tuple of arguments. ie, for a rx rotation by pi/2 radians on qubit 0, gate = "rx(pi/2, 0)". reg: qiskit.QuantumRegister, register to apply gate to. cir: qiskit.QuantumCircuit, circuit to add gate to. c_reg: qiskit.ClassicalRegister, must be supplied if gate is a measurement. Classical register to measure to. returns: int, if gate is a measure gate, then return the integer corresponding to the classical register to measure to, otherwise returns -1. """ gate_name, gate_args = get_gate_info(gate) # apply gate eval("cir." + gate_name + GATE_ARGUMENTS[gate_name] % gate_args) # value of the classical register to measure to if "measure" in gate: return gate_args[-1] else: return -1 def apply_string_algorithm(algorithm, reg, cir, c_reg=None): """ algorithm: iterable, each element must be a string gate, as in apply_string_gate above. ie, algorithm = ["h(0)", "cx(0, 1)", "rx(pi/4, 1)",..] reg: qiskit.QuantumRegister, register to apply algorithm to. cir: qiskit.QuantumCircuit, circuit to add gates in algorithm to. c_reg: qiskit.ClassicalRegister, must be supplied if gate is a measurement. Classical register to measure to. returns: int, if the algorithm has any measure gates, then returns the integer corresponding to the largest index of the classical register that is measured to, otherwise returns -1. """ if not algorithm: return -1 return max(apply_string_gate(gate, reg, cir, c_reg) for gate in algorithm) def _make_job(qc, backend, num_samples): """ Begin the execution of the circuit qc on the backend with shots=num_samples qc: qiskit.QuantumCircuit or list of circuits, circuits to run. backend: str, IBM backend to run circuit on. Can be 'ibmqx4', 'ibmqx5', 'local_qasm_simulator', 'local_unitary_simulator', etc. num_samples: int, number of samples to take from the quantum computer in in order to determine the probabilities for each state. returns: qiskit Job object from qiskit.backends. """ if backend in simulators: f = qiskit.Aer else: f = qiskit.IBMQ try: return qiskit.execute(qc, backend=f.get_backend(backend), shots=num_samples, max_credits=3) except LookupError: apply_credentials() return qiskit.execute(qc, backend=f.get_backend(backend), shots=num_samples, max_credits=3) class Result(dict): """ Just a dictionary that automatically gives default values = 0.0 """ def __getitem__(self, key): """ Return 0.0 if key not in result dictionary """ return self.get(key, 0.0) def run(algorithm, num_qubits=None, num_samples=8000, backend=simulator): """ Create a quantum circuit, run the algorithm, return the resulting probability distribution. algorithm: algorithm (list of strings) or list of algorithms, each string is a gate in GATE_ARGUMENTS.keys() with whatever arguments required to define the gate. num_qubits: int, number of qubits to run each algorithm on. Can be None, in which case the algorithm will be run on the minimum number of qubits required. num_samples: int, number of samples to take from the quantum computer in in order to determine the probabilities for each state. backend: str, IBM backend to run the algorithm on. If backend is not a local simulator then credentials must have already been applied. returns: dict (common.Result), keys are states, values are probabilities found to be in that state. """ multiple = bool(algorithm and isinstance(algorithm[0], list)) if not multiple: algorithm = [algorithm] n = len(algorithm) if num_qubits is None: num_qubits = max(get_num_qubits(a) for a in algorithm) q = qiskit.QuantumRegister(num_qubits) c = [qiskit.ClassicalRegister(num_qubits) for _ in range(n)] qc = [qiskit.QuantumCircuit(q, c[j]) for j in range(n)] for j in range(n): i = apply_string_algorithm(algorithm[j], q, qc[j], c[j]) if i == -1: qc[j].measure(q, c[j]) else: c[j].size = i + 1 job_exp = _make_job(qc, backend, num_samples) # Often there are random queue errors that have happened to # me that cause the job to never complete. Two things I have # encountered: I lose connection or something, and I get an # error, or for some reason their server tells me that the # job is running indefinitely, ie it just get stuck running. # So if either of those things happen, we reset and # reinitialize our job(s) into the queue. if backend not in simulators: lapse, interval = 0, 30 done = False while not done: str_status = str(job_exp.status()) queue_position = job_exp.queue_position() error = job_exp.error_message() print('\nStatus @ %d seconds' % (interval * lapse)) print("queue position =", queue_position) print(str_status) done = queue_position is not None and queue_position < 1 if error: print("\nEncountered an error") print(error) print("reentering job into queue\n") job_exp.cancel() job_exp = _make_job(qc, backend, num_samples) lapse = 0 lapse += 1 time.sleep(interval) res = job_exp.result() ## qiskit orders their bits opposite to Cirq nad ProjectQ, and in my ## opinion in a much less intuitive way. So I flip the order of the bits ## here. if multiple: return [ Result( {k[::-1]: v/num_samples for k, v in res.get_counts(cir).items()} ) for cir in qc ] else: return Result( {k[::-1]: v/num_samples for k, v in res.get_counts(qc[0]).items()} ) def algorithm_unitary(algorithm, num_qubits=None): """ Find the unitary corresponding to the algorithm. algorithm: list of strings, each string is a gate in GATE_ARGUMENTS.keys() with whatever arguments required to define the gate. num_qubits: int, number of qubits to run the algorithm on. returns: np.array, unitary matrix corresponding to the algorithm. """ if num_qubits is None: num_qubits = get_num_qubits(algorithm) if not algorithm: algorithm = ["iden(0)"] ## qiskit orders their bits opposite to Cirq nad ProjectQ, and in my ## opinion in a much less intuitive way. So I flip the order of the bits ## here. a = [] for gate in algorithm: gate_name, gate_args = get_gate_info(gate) i = GATE_PARAMS[gate_name][0] params = gate_args[:i] qubits = gate_args[i:] qubits = tuple(num_qubits-q-1 for q in qubits) a.append(gate_name + str(params + qubits)) q = qiskit.QuantumRegister(num_qubits) qc = qiskit.QuantumCircuit(q) apply_string_algorithm(a, q, qc) return qiskit.execute( qc, backend=qiskit.Aer.get_backend(unitary_simulator) ).result().get_data(qc)["unitary"] def prepare_state(state): """ state: string, string of 0's and 1's. returns: algorithm (list of strings), algorithm to prepare the state. """ return ["x(%d)" % i for i in range(len(state)) if state[i] == "1"] def sample(algorithm, num_qubits=None, num_samples=1, backend=simulator): """ Get a list of all the outputs from an algorithm. Differs from `run` because `run` returns the determined probabilities of each state, but `sample` returns a list of the outputs. algorithm: algorithm (list of strings), NOT a list of algorithms, each string is a gate in GATE_ARGUMENTS.keys() with whatever arguments required to define the gate. num_qubits: int, number of qubits to run each algorithm on. num_samples: int, number of samples to take from the quantum computer. backend: str, IBM backend to run the algorithm on. If backend is not a local simulator then credentials must have already been applied. returns: list, each element is the measured state. """ d = run([algorithm]*num_samples, num_qubits=num_qubits, num_samples=1, backend=backend) return [list(x.keys())[0] for x in d] def single_sample(algorithm, num_qubits=None, backend=simulator): """ Same as `sample` with one sample, but returns a state instead of a list of one state. """ return sample(algorithm, num_qubits, 1, backend)[0] def markovian_sample(algorithm, num_qubits=None, num_samples=1, backend=simulator): """ Get a list of all the outputs from an algorithm, where the previous output is prepared as the starting point for the next algorithm; ie the measurement of the algorithm is input to run the algorithm again. algorithm: algorithm (list of strings), NOT a list of algorithms, each string is a gate in GATE_ARGUMENTS.keys() with whatever arguments required to define the gate. num_qubits: int, number of qubits to run each algorithm on. num_samples: int, number of samples to take from the quantum computer. backend: str, IBM backend to run the algorithm on. If backend is not a local simulator then credentials must have already been applied. returns: list, each element is the measured state. """ if num_samples < 1: raise ValueError("Must have >= 1 sample") if num_qubits is None: num_qubits = get_num_qubits(algorithm) args = num_qubits, backend res = [single_sample(algorithm, *args)] for _ in range(num_samples-1): res.append(single_sample(prepare_state(res[-1])+algorithm, *args)) return res if __name__ == "__main__": ## Examples # `run` returns a dictionary mapping states to probabilities, ie # run(["h(0)", "cx(0, 1)"]) should return {"00":0.5, "11": 0.5}. # if no "measure" is included in alg, then by default everything will # be measured. alg = ["H(0)", "CX(0, 1)", "u3(pi, pi/2, pi/4, 0)"] print(run(alg, 3, num_samples=10000)) # since a measure is included, only that register will be measured. alg = ["H(0)", "CX(0, 1)", "u3(pi, pi/2, pi/4, 0)", "measure(0, 0)"] # print(run(alg, 3, num_samples=1000, backend="ibmqx4")) # run multiple circuits at once alg0 = ["h(0)", "cx(0, 1)", "measure(0, 0)", "measure(1, 1)"] alg1 = ["x(0)", "H(1)", "ccx(0, 1, 2)"] print(run([alg0, alg1])) # convert alg to its unitary respresentation. alg = ["h(0)", "cx(0, 1)"] print(algorithm_unitary(alg, 2))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Variational Quantum Real Time Evolution algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterVector from qiskit_algorithms.gradients import LinCombQGT, DerivativeType, LinCombEstimatorGradient from qiskit.primitives import Estimator from qiskit.utils import algorithm_globals from qiskit.quantum_info import SparsePauliOp, Pauli, Statevector from qiskit_algorithms import TimeEvolutionProblem, VarQRTE from qiskit_algorithms.time_evolvers.variational import ( RealMcLachlanPrinciple, ) from qiskit.circuit.library import EfficientSU2 @ddt class TestVarQRTE(QiskitAlgorithmsTestCase): """Test Variational Quantum Real Time Evolution algorithm.""" def setUp(self): super().setUp() self.seed = 11 np.random.seed(self.seed) def test_time_dependent_hamiltonian(self): """Simple test case with a time dependent Hamiltonian.""" t_param = Parameter("t") hamiltonian = SparsePauliOp(["Z"], np.array(t_param)) x = ParameterVector("x", 3) circuit = QuantumCircuit(1) circuit.rz(x[0], 0) circuit.ry(x[1], 0) circuit.rz(x[2], 0) initial_parameters = np.array([0, np.pi / 2, 0]) def expected_state(time): # possible with pen and paper as the Hamiltonian is diagonal return 1 / np.sqrt(2) * np.array([np.exp(-0.5j * time**2), np.exp(0.5j * time**2)]) final_time = 0.75 evolution_problem = TimeEvolutionProblem(hamiltonian, t_param=t_param, time=final_time) estimator = Estimator() varqrte = VarQRTE(circuit, initial_parameters, estimator=estimator) result = varqrte.evolve(evolution_problem) final_parameters = result.parameter_values[-1] final_state = Statevector(circuit.bind_parameters(final_parameters)).to_dict() final_expected_state = expected_state(final_time) for key, expected_value in final_state.items(): self.assertTrue(np.allclose(final_expected_state[int(key)], expected_value, 1e-02)) def test_run_d_1_with_aux_ops(self): """Test VarQRTE for d = 1 and t = 0.1 with evaluating auxiliary operators and the Forward Euler solver.""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) aux_ops = [Pauli("XX"), Pauli("YZ")] d = 1 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 2 init_param_values[0] = 1 time = 0.1 evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) thetas_expected = [ 0.886841151529636, 1.53852629218265, 1.57099556659882, 1.5889216657174, 1.5996487153364, 1.57018939515742, 1.63950719260698, 1.53853696496673, ] thetas_expected_shots = [ 0.886975892820015, 1.53822607733397, 1.57058096749141, 1.59023223608564, 1.60105707043745, 1.57018042397236, 1.64010900210835, 1.53959523034133, ] with self.subTest(msg="Test exact backend."): algorithm_globals.random_seed = self.seed estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qrte.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] expected_aux_ops = [0.06836996703935797, 0.7711574493422457] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=2 ) np.testing.assert_array_almost_equal( [result[0] for result in aux_ops], expected_aux_ops ) with self.subTest(msg="Test shot-based backend."): algorithm_globals.random_seed = self.seed estimator = Estimator(options={"shots": 4 * 4096, "seed": self.seed}) qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qrte.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] expected_aux_ops = [ 0.070436, 0.777938, ] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected_shots[i], decimal=2 ) np.testing.assert_array_almost_equal( [result[0] for result in aux_ops], expected_aux_ops, decimal=2 ) def test_run_d_2(self): """Test VarQRTE for d = 2 and t = 1 with RK45 ODE solver.""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) d = 2 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 4 estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) param_dict = dict(zip(parameters, init_param_values)) time = 1 var_qrte = VarQRTE(ansatz, param_dict, var_principle, ode_solver="RK45", num_timesteps=25) thetas_expected = [ 0.348407744196573, 0.919404626262464, 1.18189219371626, 0.771011177789998, 0.734384256533924, 0.965289520781899, 1.14441687204195, 1.17231927568571, 1.03014771379412, 0.867266309056347, 0.699606368428206, 0.610788576398685, ] self._test_helper(observable, thetas_expected, time, var_qrte) def test_run_d_1_time_dependent(self): """Test VarQRTE for d = 1 and a time-dependent Hamiltonian with the Forward Euler solver.""" t_param = Parameter("t") time = 1 observable = SparsePauliOp(["I", "Z"], np.array([0, t_param])) x, y, z = [Parameter(s) for s in "xyz"] ansatz = QuantumCircuit(1) ansatz.rz(x, 0) ansatz.ry(y, 0) ansatz.rz(z, 0) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) x_val = 0 y_val = np.pi / 2 z_val = 0 init_param_values[0] = x_val init_param_values[1] = y_val init_param_values[2] = z_val evolution_problem = TimeEvolutionProblem(observable, time, t_param=t_param) thetas_expected = [1.27675647831902e-18, 1.5707963267949, 0.990000000000001] thetas_expected_shots = [0.00534345821469238, 1.56260960200375, 0.990017403734316] # the expected final state is Statevector([0.62289306-0.33467034j, 0.62289306+0.33467034j]) with self.subTest(msg="Test exact backend."): algorithm_globals.random_seed = self.seed estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=100 ) evolution_result = var_qrte.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=2 ) with self.subTest(msg="Test shot-based backend."): algorithm_globals.random_seed = self.seed estimator = Estimator(options={"shots": 4 * 4096, "seed": self.seed}) qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=100 ) evolution_result = var_qrte.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected_shots[i], decimal=2 ) def _test_helper(self, observable, thetas_expected, time, var_qrte): evolution_problem = TimeEvolutionProblem(observable, time) evolution_result = var_qrte.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal(float(parameter_value), thetas_expected[i], decimal=4) if __name__ == "__main__": unittest.main()
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb 1 + cos(2*pi/3) + 1j*sin(2*pi/3) + cos(4*pi/3) + 1j*sin(4*pi/3) 1 + cos(4*pi/3) + 1j*sin(4*pi/3) + cos(8*pi/3) + 1j*sin(8*pi/3) cos(2*pi/3), cos(4*pi/3)
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# 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. """A module for visualizing device coupling maps.""" import math from typing import List import numpy as np from qiskit.exceptions import MissingOptionalLibraryError, QiskitError from qiskit.providers.backend import BackendV2 from qiskit.tools.visualization import HAS_MATPLOTLIB, VisualizationError from qiskit.visualization.utils import matplotlib_close_if_inline def plot_gate_map( backend, figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="w", ax=None, filename=None, qubit_coordinates=None, ): """Plots the gate map of a device. Args: backend (BaseBackend): The backend instance that will be used to plot the device gate map. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: QiskitError: if tried to pass a simulator, or if the backend is None, but one of num_qubits, mpl_data, or cmap is None. MissingOptionalLibraryError: if matplotlib not installed. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import QuantumCircuit, execute, IBMQ from qiskit.visualization import plot_gate_map %matplotlib inline provider = IBMQ.load_account() accountProvider = IBMQ.get_provider(hub='ibm-q') backend = accountProvider.get_backend('ibmq_vigo') plot_gate_map(backend) """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_gate_map", pip_install="pip install matplotlib", ) if isinstance(backend, BackendV2): pass elif backend.configuration().simulator: raise QiskitError("Requires a device backend, not simulator.") qubit_coordinates_map = {} qubit_coordinates_map[1] = [[0, 0]] qubit_coordinates_map[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]] qubit_coordinates_map[7] = [[0, 0], [0, 1], [0, 2], [1, 1], [2, 0], [2, 1], [2, 2]] qubit_coordinates_map[20] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4], ] qubit_coordinates_map[15] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], ] qubit_coordinates_map[16] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], ] qubit_coordinates_map[27] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], [3, 6], [0, 7], [1, 7], [3, 7], [4, 7], [1, 8], [3, 8], [1, 9], [2, 9], [3, 9], [3, 10], ] qubit_coordinates_map[28] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], ] qubit_coordinates_map[53] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [5, 2], [5, 6], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [7, 0], [7, 4], [7, 8], [8, 0], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [9, 2], [9, 6], ] qubit_coordinates_map[65] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [1, 0], [1, 4], [1, 8], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 9], [2, 10], [3, 2], [3, 6], [3, 10], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 10], [5, 0], [5, 4], [5, 8], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [6, 9], [6, 10], [7, 2], [7, 6], [7, 10], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [8, 9], [8, 10], ] if isinstance(backend, BackendV2): num_qubits = backend.num_qubits coupling_map = backend.plot_coupling_map else: config = backend.configuration() num_qubits = config.n_qubits coupling_map = config.coupling_map # don't reference dictionary if provided as a parameter if qubit_coordinates is None: qubit_coordinates = qubit_coordinates_map.get(num_qubits) # try to adjust num_qubits to match the next highest hardcoded grid size if qubit_coordinates is None: if any([num_qubits < key for key in qubit_coordinates_map.keys()]): num_qubits_roundup = max(qubit_coordinates_map.keys()) for key in qubit_coordinates_map.keys(): if key < num_qubits_roundup and key > num_qubits: num_qubits_roundup = key qubit_coordinates = qubit_coordinates_map.get(num_qubits_roundup) return plot_coupling_map( num_qubits, qubit_coordinates, coupling_map, figsize, plot_directed, label_qubits, qubit_size, line_width, font_size, qubit_color, qubit_labels, line_color, font_color, ax, filename, ) def plot_coupling_map( num_qubits: int, qubit_coordinates: List[List[int]], coupling_map: List[List[int]], figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="w", ax=None, filename=None, ): """Plots an arbitrary coupling map of qubits (embedded in a plane). Args: num_qubits (int): The number of qubits defined and plotted. qubit_coordinates (List[List[int]]): A list of two-element lists, with entries of each nested list being the planar coordinates in a 0-based square grid where each qubit is located. coupling_map (List[List[int]]): A list of two-element lists, with entries of each nested list being the qubit numbers of the bonds to be plotted. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: MissingOptionalLibraryError: if matplotlib not installed. QiskitError: If length of qubit labels does not match number of qubits. Example: .. jupyter-execute:: from qiskit.visualization import plot_coupling_map %matplotlib inline num_qubits = 8 coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]] qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]] plot_coupling_map(num_qubits, coupling_map, qubit_coordinates) """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_coupling_map", pip_install="pip install matplotlib", ) import matplotlib.patches as mpatches import matplotlib.pyplot as plt input_axes = False if ax: input_axes = True if font_size is None: font_size = 12 if qubit_size is None: qubit_size = 24 if num_qubits > 20: qubit_size = 28 font_size = 10 if qubit_labels is None: qubit_labels = list(range(num_qubits)) else: if len(qubit_labels) != num_qubits: raise QiskitError("Length of qubit labels does not equal number of qubits.") if qubit_coordinates is not None: grid_data = qubit_coordinates else: if not input_axes: fig, ax = plt.subplots(figsize=(5, 5)) ax.axis("off") if filename: fig.savefig(filename) return fig x_max = max(d[1] for d in grid_data) y_max = max(d[0] for d in grid_data) max_dim = max(x_max, y_max) if figsize is None: if num_qubits == 1 or (x_max / max_dim > 0.33 and y_max / max_dim > 0.33): figsize = (5, 5) else: figsize = (9, 3) if ax is None: fig, ax = plt.subplots(figsize=figsize) ax.axis("off") # set coloring if qubit_color is None: qubit_color = ["#648fff"] * num_qubits if line_color is None: line_color = ["#648fff"] * len(coupling_map) if coupling_map else [] # Add lines for couplings if num_qubits != 1: for ind, edge in enumerate(coupling_map): is_symmetric = False if edge[::-1] in coupling_map: is_symmetric = True y_start = grid_data[edge[0]][0] x_start = grid_data[edge[0]][1] y_end = grid_data[edge[1]][0] x_end = grid_data[edge[1]][1] if is_symmetric: if y_start == y_end: x_end = (x_end - x_start) / 2 + x_start elif x_start == x_end: y_end = (y_end - y_start) / 2 + y_start else: x_end = (x_end - x_start) / 2 + x_start y_end = (y_end - y_start) / 2 + y_start ax.add_artist( plt.Line2D( [x_start, x_end], [-y_start, -y_end], color=line_color[ind], linewidth=line_width, zorder=0, ) ) if plot_directed: dx = x_end - x_start dy = y_end - y_start if is_symmetric: x_arrow = x_start + dx * 0.95 y_arrow = -y_start - dy * 0.95 dx_arrow = dx * 0.01 dy_arrow = -dy * 0.01 head_width = 0.15 else: x_arrow = x_start + dx * 0.5 y_arrow = -y_start - dy * 0.5 dx_arrow = dx * 0.2 dy_arrow = -dy * 0.2 head_width = 0.2 ax.add_patch( mpatches.FancyArrow( x_arrow, y_arrow, dx_arrow, dy_arrow, head_width=head_width, length_includes_head=True, edgecolor=None, linewidth=0, facecolor=line_color[ind], zorder=1, ) ) # Add circles for qubits for var, idx in enumerate(grid_data): # add check if num_qubits had been rounded up if var >= num_qubits: break _idx = [idx[1], -idx[0]] ax.add_artist( mpatches.Ellipse( _idx, qubit_size / 48, qubit_size / 48, # This is here so that the changes color=qubit_color[var], zorder=1, ) ) # to how qubits are plotted does if label_qubits: # not affect qubit size kwarg. ax.text( *_idx, s=qubit_labels[var], horizontalalignment="center", verticalalignment="center", color=font_color, size=font_size, weight="bold", ) ax.set_xlim([-1, x_max + 1]) ax.set_ylim([-(y_max + 1), 1]) ax.set_aspect("equal") if not input_axes: matplotlib_close_if_inline(fig) if filename: fig.savefig(filename) return fig return None def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None): """Plot the layout of a circuit transpiled for a given target backend. Args: circuit (QuantumCircuit): Input quantum circuit. backend (BaseBackend): Target backend. view (str): Layout view: either 'virtual' or 'physical'. Returns: Figure: A matplotlib figure showing layout. Raises: QiskitError: Invalid view type given. VisualizationError: Circuit has no layout attribute. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: import numpy as np from qiskit import QuantumCircuit, IBMQ, transpile from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt %matplotlib inline IBMQ.load_account() ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend) """ if circuit._layout is None: raise QiskitError("Circuit has no layout. Perhaps it has not been transpiled.") if isinstance(backend, BackendV2): num_qubits = backend.num_qubits else: num_qubits = backend.configuration().n_qubits qubits = [] qubit_labels = [None] * num_qubits bit_locations = { bit: {"register": register, "index": index} for register in circuit._layout.get_registers() for index, bit in enumerate(register) } for index, qubit in enumerate(circuit._layout.get_virtual_bits()): if qubit not in bit_locations: bit_locations[qubit] = {"register": None, "index": index} if view == "virtual": for key, val in circuit._layout.get_virtual_bits().items(): bit_register = bit_locations[key]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(val) qubit_labels[val] = bit_locations[key]["index"] elif view == "physical": for key, val in circuit._layout.get_physical_bits().items(): bit_register = bit_locations[val]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(key) qubit_labels[key] = key else: raise VisualizationError("Layout view must be 'virtual' or 'physical'.") qcolors = ["#648fff"] * num_qubits for k in qubits: qcolors[k] = "k" if isinstance(backend, BackendV2): cmap = backend.plot_coupling_map else: cmap = backend.configuration().coupling_map lcolors = ["#648fff"] * len(cmap) for idx, edge in enumerate(cmap): if edge[0] in qubits and edge[1] in qubits: lcolors[idx] = "k" fig = plot_gate_map( backend, qubit_color=qcolors, qubit_labels=qubit_labels, line_color=lcolors, qubit_coordinates=qubit_coordinates, ) return fig def plot_error_map(backend, figsize=(12, 9), show_title=True): """Plots the error map of a given backend. Args: backend (IBMQBackend): Given backend. figsize (tuple): Figure size in inches. show_title (bool): Show the title or not. Returns: Figure: A matplotlib figure showing error map. Raises: VisualizationError: Input is not IBMQ backend. VisualizationError: The backend does not provide gate errors for the 'sx' gate. MissingOptionalLibraryError: If seaborn is not installed Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import QuantumCircuit, execute, IBMQ from qiskit.visualization import plot_error_map %matplotlib inline IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') plot_error_map(backend) """ try: import seaborn as sns except ImportError as ex: raise MissingOptionalLibraryError( libname="seaborn", name="plot_error_map", pip_install="pip install seaborn", ) from ex if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_error_map", pip_install="pip install matplotlib", ) import matplotlib import matplotlib.pyplot as plt from matplotlib import gridspec, ticker color_map = sns.cubehelix_palette(reverse=True, as_cmap=True) props = backend.properties().to_dict() config = backend.configuration().to_dict() num_qubits = config["n_qubits"] # sx error rates single_gate_errors = [0] * num_qubits for gate in props["gates"]: if gate["gate"] == "sx": _qubit = gate["qubits"][0] for param in gate["parameters"]: if param["name"] == "gate_error": single_gate_errors[_qubit] = param["value"] break else: raise VisualizationError( f"Backend '{backend}' did not supply an error for the 'sx' gate." ) # Convert to percent single_gate_errors = 100 * np.asarray(single_gate_errors) avg_1q_err = np.mean(single_gate_errors) single_norm = matplotlib.colors.Normalize( vmin=min(single_gate_errors), vmax=max(single_gate_errors) ) q_colors = [color_map(single_norm(err)) for err in single_gate_errors] cmap = config["coupling_map"] directed = False line_colors = [] if cmap: directed = False if num_qubits < 20: for edge in cmap: if [edge[1], edge[0]] not in cmap: directed = True break cx_errors = [] for line in cmap: for item in props["gates"]: if item["qubits"] == line: cx_errors.append(item["parameters"][0]["value"]) break else: continue # Convert to percent cx_errors = 100 * np.asarray(cx_errors) avg_cx_err = np.mean(cx_errors) cx_norm = matplotlib.colors.Normalize(vmin=min(cx_errors), vmax=max(cx_errors)) line_colors = [color_map(cx_norm(err)) for err in cx_errors] # Measurement errors read_err = [] for qubit in range(num_qubits): for item in props["qubits"][qubit]: if item["name"] == "readout_error": read_err.append(item["value"]) read_err = 100 * np.asarray(read_err) avg_read_err = np.mean(read_err) max_read_err = np.max(read_err) fig = plt.figure(figsize=figsize) gridspec.GridSpec(nrows=2, ncols=3) grid_spec = gridspec.GridSpec( 12, 12, height_ratios=[1] * 11 + [0.5], width_ratios=[2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2], ) left_ax = plt.subplot(grid_spec[2:10, :1]) main_ax = plt.subplot(grid_spec[:11, 1:11]) right_ax = plt.subplot(grid_spec[2:10, 11:]) bleft_ax = plt.subplot(grid_spec[-1, :5]) if cmap: bright_ax = plt.subplot(grid_spec[-1, 7:]) qubit_size = 28 if num_qubits <= 5: qubit_size = 20 plot_gate_map( backend, qubit_color=q_colors, line_color=line_colors, qubit_size=qubit_size, line_width=5, plot_directed=directed, ax=main_ax, ) main_ax.axis("off") main_ax.set_aspect(1) if cmap: single_cb = matplotlib.colorbar.ColorbarBase( bleft_ax, cmap=color_map, norm=single_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) single_cb.locator = tick_locator single_cb.update_ticks() single_cb.update_ticks() bleft_ax.set_title(f"H error rate (%) [Avg. = {round(avg_1q_err, 3)}]") if cmap is None: bleft_ax.axis("off") bleft_ax.set_title(f"H error rate (%) = {round(avg_1q_err, 3)}") if cmap: cx_cb = matplotlib.colorbar.ColorbarBase( bright_ax, cmap=color_map, norm=cx_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) cx_cb.locator = tick_locator cx_cb.update_ticks() bright_ax.set_title(f"CNOT error rate (%) [Avg. = {round(avg_cx_err, 3)}]") if num_qubits < 10: num_left = num_qubits num_right = 0 else: num_left = math.ceil(num_qubits / 2) num_right = num_qubits - num_left left_ax.barh(range(num_left), read_err[:num_left], align="center", color="#DDBBBA") left_ax.axvline(avg_read_err, linestyle="--", color="#212121") left_ax.set_yticks(range(num_left)) left_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) left_ax.set_yticklabels([str(kk) for kk in range(num_left)], fontsize=12) left_ax.invert_yaxis() left_ax.set_title("Readout Error (%)", fontsize=12) for spine in left_ax.spines.values(): spine.set_visible(False) if num_right: right_ax.barh( range(num_left, num_qubits), read_err[num_left:], align="center", color="#DDBBBA", ) right_ax.axvline(avg_read_err, linestyle="--", color="#212121") right_ax.set_yticks(range(num_left, num_qubits)) right_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) right_ax.set_yticklabels( [str(kk) for kk in range(num_left, num_qubits)], fontsize=12 ) right_ax.invert_yaxis() right_ax.invert_xaxis() right_ax.yaxis.set_label_position("right") right_ax.yaxis.tick_right() right_ax.set_title("Readout Error (%)", fontsize=12) else: right_ax.axis("off") for spine in right_ax.spines.values(): spine.set_visible(False) if show_title: fig.suptitle(f"{backend.name()} Error Map", fontsize=24, y=0.9) matplotlib_close_if_inline(fig) return fig
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for PauliList class.""" import itertools import unittest from test import combine import numpy as np from ddt import ddt from scipy.sparse import csr_matrix from qiskit import QiskitError from qiskit.circuit.library import ( CXGate, CYGate, CZGate, HGate, IGate, SdgGate, SGate, SwapGate, XGate, YGate, ZGate, ) from qiskit.quantum_info.operators import ( Clifford, Operator, Pauli, PauliList, PauliTable, StabilizerTable, ) from qiskit.quantum_info.random import random_clifford, random_pauli_list from qiskit.test import QiskitTestCase from .test_pauli import pauli_group_labels def pauli_mat(label): """Return Pauli matrix from a Pauli label""" mat = np.eye(1, dtype=complex) if label[0:2] == "-i": mat *= -1j label = label[2:] elif label[0] == "-": mat *= -1 label = label[1:] elif label[0] == "i": mat *= 1j label = label[1:] for i in label: if i == "I": mat = np.kron(mat, np.eye(2, dtype=complex)) elif i == "X": mat = np.kron(mat, np.array([[0, 1], [1, 0]], dtype=complex)) elif i == "Y": mat = np.kron(mat, np.array([[0, -1j], [1j, 0]], dtype=complex)) elif i == "Z": mat = np.kron(mat, np.array([[1, 0], [0, -1]], dtype=complex)) else: raise QiskitError(f"Invalid Pauli string {i}") return mat class TestPauliListInit(QiskitTestCase): """Tests for PauliList initialization.""" def test_array_init(self): """Test array initialization.""" # Matrix array initialization with self.subTest(msg="Empty array"): x = np.array([], dtype=bool).reshape((1, 0)) z = np.array([], dtype=bool).reshape((1, 0)) pauli_list = PauliList.from_symplectic(x, z) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg="bool array"): z = np.array([[False], [True]]) x = np.array([[False], [True]]) pauli_list = PauliList.from_symplectic(z, x) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg="bool array no copy"): z = np.array([[False], [True]]) x = np.array([[True], [True]]) pauli_list = PauliList.from_symplectic(z, x) z[0, 0] = not z[0, 0] np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) def test_string_init(self): """Test string initialization.""" # String initialization with self.subTest(msg='str init "I"'): pauli_list = PauliList("I") z = np.array([[False]]) x = np.array([[False]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "X"'): pauli_list = PauliList("X") z = np.array([[False]]) x = np.array([[True]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "Y"'): pauli_list = PauliList("Y") z = np.array([[True]]) x = np.array([[True]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "Z"'): pauli_list = PauliList("Z") z = np.array([[True]]) x = np.array([[False]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "iZ"'): pauli_list = PauliList("iZ") z = np.array([[True]]) x = np.array([[False]]) phase = np.array([3]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) np.testing.assert_equal(pauli_list.phase, phase) with self.subTest(msg='str init "-Z"'): pauli_list = PauliList("-Z") z = np.array([[True]]) x = np.array([[False]]) phase = np.array([2]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) np.testing.assert_equal(pauli_list.phase, phase) with self.subTest(msg='str init "-iZ"'): pauli_list = PauliList("-iZ") z = np.array([[True]]) x = np.array([[False]]) phase = np.array([1]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) np.testing.assert_equal(pauli_list.phase, phase) with self.subTest(msg='str init "IX"'): pauli_list = PauliList("IX") z = np.array([[False, False]]) x = np.array([[True, False]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "XI"'): pauli_list = PauliList("XI") z = np.array([[False, False]]) x = np.array([[False, True]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "YZ"'): pauli_list = PauliList("YZ") z = np.array([[True, True]]) x = np.array([[False, True]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg='str init "iZY"'): pauli_list = PauliList("iZY") z = np.array([[True, True]]) x = np.array([[True, False]]) phase = np.array([3]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) np.testing.assert_equal(pauli_list.phase, phase) with self.subTest(msg='str init "XIZ"'): pauli_list = PauliList("XIZ") z = np.array([[True, False, False]]) x = np.array([[False, False, True]]) np.testing.assert_equal(pauli_list.z, z) np.testing.assert_equal(pauli_list.x, x) with self.subTest(msg="str init prevent broadcasting"): with self.assertRaises(ValueError): PauliList(["XYZ", "I"]) def test_list_init(self): """Test list initialization.""" with self.subTest(msg="PauliList"): target = PauliList(["iXI", "IX", "IZ"]) value = PauliList(target) self.assertEqual(value, target) with self.subTest(msg="PauliList no copy"): target = PauliList(["iXI", "IX", "IZ"]) value = PauliList(target) value[0] = "-iII" self.assertEqual(value, target) def test_pauli_table_init(self): """Test table initialization.""" with self.subTest(msg="PauliTable"): target = PauliTable.from_labels(["XI", "IX", "IZ"]) value = PauliList(target) self.assertEqual(value, target) with self.subTest(msg="PauliTable no copy"): target = PauliTable.from_labels(["XI", "IX", "IZ"]) value = PauliList(target) value[0] = "II" self.assertEqual(value, target) def test_stabilizer_table_init(self): """Test table initialization.""" with self.subTest(msg="PauliTable"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["+II", "-XZ"]) value = PauliList(target) self.assertEqual(value, target) with self.subTest(msg="PauliTable no copy"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["+YY", "-XZ", "XI"]) value = PauliList(target) value[0] = "II" self.assertEqual(value, target) def test_init_from_settings(self): """Test initializing from the settings dictionary.""" pauli_list = PauliList(["IX", "-iYZ", "YY"]) from_settings = PauliList(**pauli_list.settings) self.assertEqual(pauli_list, from_settings) @ddt class TestPauliListProperties(QiskitTestCase): """Tests for PauliList properties.""" def test_x_property(self): """Test X property""" with self.subTest(msg="X"): pauli = PauliList(["XI", "IZ", "YY"]) array = np.array([[False, True], [False, False], [True, True]], dtype=bool) self.assertTrue(np.all(pauli.x == array)) with self.subTest(msg="set X"): pauli = PauliList(["XI", "IZ"]) val = np.array([[False, False], [True, True]], dtype=bool) pauli.x = val self.assertEqual(pauli, PauliList(["II", "iXY"])) with self.subTest(msg="set X raises"): with self.assertRaises(Exception): pauli = PauliList(["XI", "IZ"]) val = np.array([[False, False, False], [True, True, True]], dtype=bool) pauli.x = val def test_z_property(self): """Test Z property""" with self.subTest(msg="Z"): pauli = PauliList(["XI", "IZ", "YY"]) array = np.array([[False, False], [True, False], [True, True]], dtype=bool) self.assertTrue(np.all(pauli.z == array)) with self.subTest(msg="set Z"): pauli = PauliList(["XI", "IZ"]) val = np.array([[False, False], [True, True]], dtype=bool) pauli.z = val self.assertEqual(pauli, PauliList(["XI", "ZZ"])) with self.subTest(msg="set Z raises"): with self.assertRaises(Exception): pauli = PauliList(["XI", "IZ"]) val = np.array([[False, False, False], [True, True, True]], dtype=bool) pauli.z = val def test_phase_property(self): """Test phase property""" with self.subTest(msg="phase"): pauli = PauliList(["XI", "IZ", "YY", "YI"]) array = np.array([0, 0, 0, 0], dtype=int) np.testing.assert_equal(pauli.phase, array) with self.subTest(msg="set phase"): pauli = PauliList(["XI", "IZ"]) val = np.array([2, 3], dtype=int) pauli.phase = val self.assertEqual(pauli, PauliList(["-XI", "iIZ"])) with self.subTest(msg="set Z raises"): with self.assertRaises(Exception): pauli = PauliList(["XI", "IZ"]) val = np.array([1, 2, 3], dtype=int) pauli.phase = val def test_shape_property(self): """Test shape property""" shape = (3, 4) pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape)) self.assertEqual(pauli.shape, shape) @combine(j=range(1, 10)) def test_size_property(self, j): """Test size property""" shape = (j, 4) pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape)) self.assertEqual(len(pauli), j) @combine(j=range(1, 10)) def test_n_qubit_property(self, j): """Test n_qubit property""" shape = (5, j) pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape)) self.assertEqual(pauli.num_qubits, j) def test_eq(self): """Test __eq__ method.""" pauli1 = PauliList(["II", "XI"]) pauli2 = PauliList(["XI", "II"]) self.assertEqual(pauli1, pauli1) self.assertNotEqual(pauli1, pauli2) def test_len_methods(self): """Test __len__ method.""" for j in range(1, 10): labels = j * ["XX"] pauli = PauliList(labels) self.assertEqual(len(pauli), j) def test_add_methods(self): """Test __add__ method.""" labels1 = ["XXI", "IXX"] labels2 = ["XXI", "ZZI", "ZYZ"] pauli1 = PauliList(labels1) pauli2 = PauliList(labels2) target = PauliList(labels1 + labels2) self.assertEqual(target, pauli1 + pauli2) def test_add_qargs(self): """Test add method with qargs.""" pauli1 = PauliList(["IIII", "YYYY"]) pauli2 = PauliList(["XY", "YZ"]) pauli3 = PauliList(["X", "Y", "Z"]) with self.subTest(msg="qargs=[0, 1]"): target = PauliList(["IIII", "YYYY", "IIXY", "IIYZ"]) self.assertEqual(pauli1 + pauli2([0, 1]), target) with self.subTest(msg="qargs=[0, 3]"): target = PauliList(["IIII", "YYYY", "XIIY", "YIIZ"]) self.assertEqual(pauli1 + pauli2([0, 3]), target) with self.subTest(msg="qargs=[2, 1]"): target = PauliList(["IIII", "YYYY", "IYXI", "IZYI"]) self.assertEqual(pauli1 + pauli2([2, 1]), target) with self.subTest(msg="qargs=[3, 1]"): target = PauliList(["IIII", "YYYY", "YIXI", "ZIYI"]) self.assertEqual(pauli1 + pauli2([3, 1]), target) with self.subTest(msg="qargs=[0]"): target = PauliList(["IIII", "YYYY", "IIIX", "IIIY", "IIIZ"]) self.assertEqual(pauli1 + pauli3([0]), target) with self.subTest(msg="qargs=[1]"): target = PauliList(["IIII", "YYYY", "IIXI", "IIYI", "IIZI"]) self.assertEqual(pauli1 + pauli3([1]), target) with self.subTest(msg="qargs=[2]"): target = PauliList(["IIII", "YYYY", "IXII", "IYII", "IZII"]) self.assertEqual(pauli1 + pauli3([2]), target) with self.subTest(msg="qargs=[3]"): target = PauliList(["IIII", "YYYY", "XIII", "YIII", "ZIII"]) self.assertEqual(pauli1 + pauli3([3]), target) def test_getitem_methods(self): """Test __getitem__ method.""" with self.subTest(msg="__getitem__ single"): labels = ["XI", "IY"] pauli = PauliList(labels) self.assertEqual(pauli[0], PauliList(labels[0])) self.assertEqual(pauli[1], PauliList(labels[1])) with self.subTest(msg="__getitem__ array"): labels = np.array(["XI", "IY", "IZ", "XY", "ZX"]) pauli = PauliList(labels) inds = [0, 3] self.assertEqual(pauli[inds], PauliList(labels[inds])) inds = np.array([4, 1]) self.assertEqual(pauli[inds], PauliList(labels[inds])) with self.subTest(msg="__getitem__ slice"): labels = np.array(["XI", "IY", "IZ", "XY", "ZX"]) pauli = PauliList(labels) self.assertEqual(pauli[:], pauli) self.assertEqual(pauli[1:3], PauliList(labels[1:3])) def test_setitem_methods(self): """Test __setitem__ method.""" with self.subTest(msg="__setitem__ single"): labels = ["XI", "IY"] pauli = PauliList(["XI", "IY"]) pauli[0] = "II" self.assertEqual(pauli[0], PauliList("II")) pauli[1] = "-iXX" self.assertEqual(pauli[1], PauliList("-iXX")) with self.assertRaises(Exception): # Wrong size Pauli pauli[0] = "XXX" with self.subTest(msg="__setitem__ array"): labels = np.array(["XI", "IY", "IZ"]) pauli = PauliList(labels) target = PauliList(["II", "ZZ"]) inds = [2, 0] pauli[inds] = target self.assertEqual(pauli[inds], target) with self.assertRaises(Exception): pauli[inds] = PauliList(["YY", "ZZ", "XX"]) with self.subTest(msg="__setitem__ slice"): labels = np.array(5 * ["III"]) pauli = PauliList(labels) target = PauliList(5 * ["XXX"]) pauli[:] = target self.assertEqual(pauli[:], target) target = PauliList(2 * ["ZZZ"]) pauli[1:3] = target self.assertEqual(pauli[1:3], target) class TestPauliListLabels(QiskitTestCase): """Tests PauliList label representation conversions.""" def test_from_labels_1q(self): """Test 1-qubit from_labels method.""" labels = ["I", "Z", "Z", "X", "Y"] target = PauliList.from_symplectic( np.array([[False], [True], [True], [False], [True]]), np.array([[False], [False], [False], [True], [True]]), ) value = PauliList(labels) self.assertEqual(target, value) def test_from_labels_1q_with_phase(self): """Test 1-qubit from_labels method with phase.""" labels = ["-I", "iZ", "iZ", "X", "-iY"] target = PauliList.from_symplectic( np.array([[False], [True], [True], [False], [True]]), np.array([[False], [False], [False], [True], [True]]), np.array([2, 3, 3, 0, 1]), ) value = PauliList(labels) self.assertEqual(target, value) def test_from_labels_2q(self): """Test 2-qubit from_labels method.""" labels = ["II", "YY", "XZ"] target = PauliList.from_symplectic( np.array([[False, False], [True, True], [True, False]]), np.array([[False, False], [True, True], [False, True]]), ) value = PauliList(labels) self.assertEqual(target, value) def test_from_labels_2q_with_phase(self): """Test 2-qubit from_labels method.""" labels = ["iII", "iYY", "-iXZ"] target = PauliList.from_symplectic( np.array([[False, False], [True, True], [True, False]]), np.array([[False, False], [True, True], [False, True]]), np.array([3, 3, 1]), ) value = PauliList(labels) self.assertEqual(target, value) def test_from_labels_5q(self): """Test 5-qubit from_labels method.""" labels = [5 * "I", 5 * "X", 5 * "Y", 5 * "Z"] target = PauliList.from_symplectic( np.array([[False] * 5, [False] * 5, [True] * 5, [True] * 5]), np.array([[False] * 5, [True] * 5, [True] * 5, [False] * 5]), ) value = PauliList(labels) self.assertEqual(target, value) def test_to_labels_1q(self): """Test 1-qubit to_labels method.""" pauli = PauliList.from_symplectic( np.array([[False], [True], [True], [False], [True]]), np.array([[False], [False], [False], [True], [True]]), ) target = ["I", "Z", "Z", "X", "Y"] value = pauli.to_labels() self.assertEqual(value, target) def test_to_labels_1q_with_phase(self): """Test 1-qubit to_labels method with phase.""" pauli = PauliList.from_symplectic( np.array([[False], [True], [True], [False], [True]]), np.array([[False], [False], [False], [True], [True]]), np.array([1, 3, 2, 3, 1]), ) target = ["-iI", "iZ", "-Z", "iX", "-iY"] value = pauli.to_labels() self.assertEqual(value, target) def test_to_labels_1q_array(self): """Test 1-qubit to_labels method w/ array=True.""" pauli = PauliList.from_symplectic( np.array([[False], [True], [True], [False], [True]]), np.array([[False], [False], [False], [True], [True]]), ) target = np.array(["I", "Z", "Z", "X", "Y"]) value = pauli.to_labels(array=True) self.assertTrue(np.all(value == target)) def test_to_labels_1q_array_with_phase(self): """Test 1-qubit to_labels method w/ array=True.""" pauli = PauliList.from_symplectic( np.array([[False], [True], [True], [False], [True]]), np.array([[False], [False], [False], [True], [True]]), np.array([2, 3, 0, 1, 0]), ) target = np.array(["-I", "iZ", "Z", "-iX", "Y"]) value = pauli.to_labels(array=True) self.assertTrue(np.all(value == target)) def test_labels_round_trip(self): """Test from_labels and to_labels round trip.""" target = ["III", "IXZ", "XYI", "ZZZ", "-iZIX", "-IYX"] value = PauliList(target).to_labels() self.assertEqual(value, target) def test_labels_round_trip_array(self): """Test from_labels and to_labels round trip w/ array=True.""" labels = ["III", "IXZ", "XYI", "ZZZ", "-iZIX", "-IYX"] target = np.array(labels) value = PauliList(labels).to_labels(array=True) self.assertTrue(np.all(value == target)) class TestPauliListMatrix(QiskitTestCase): """Tests PauliList matrix representation conversions.""" def test_to_matrix_1q(self): """Test 1-qubit to_matrix method.""" labels = ["X", "I", "Z", "Y"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix() self.assertTrue(isinstance(values, list)) for target, value in zip(targets, values): self.assertTrue(np.all(value == target)) def test_to_matrix_1q_array(self): """Test 1-qubit to_matrix method w/ array=True.""" labels = ["Z", "I", "Y", "X"] target = np.array([pauli_mat(i) for i in labels]) value = PauliList(labels).to_matrix(array=True) self.assertTrue(isinstance(value, np.ndarray)) self.assertTrue(np.all(value == target)) def test_to_matrix_1q_sparse(self): """Test 1-qubit to_matrix method w/ sparse=True.""" labels = ["X", "I", "Z", "Y"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix(sparse=True) for mat, targ in zip(values, targets): self.assertTrue(isinstance(mat, csr_matrix)) self.assertTrue(np.all(targ == mat.toarray())) def test_to_matrix_2q(self): """Test 2-qubit to_matrix method.""" labels = ["IX", "YI", "II", "ZZ"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix() self.assertTrue(isinstance(values, list)) for target, value in zip(targets, values): self.assertTrue(np.all(value == target)) def test_to_matrix_2q_array(self): """Test 2-qubit to_matrix method w/ array=True.""" labels = ["ZZ", "XY", "YX", "IZ"] target = np.array([pauli_mat(i) for i in labels]) value = PauliList(labels).to_matrix(array=True) self.assertTrue(isinstance(value, np.ndarray)) self.assertTrue(np.all(value == target)) def test_to_matrix_2q_sparse(self): """Test 2-qubit to_matrix method w/ sparse=True.""" labels = ["IX", "II", "ZY", "YZ"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix(sparse=True) for mat, targ in zip(values, targets): self.assertTrue(isinstance(mat, csr_matrix)) self.assertTrue(np.all(targ == mat.toarray())) def test_to_matrix_5q(self): """Test 5-qubit to_matrix method.""" labels = ["IXIXI", "YZIXI", "IIXYZ"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix() self.assertTrue(isinstance(values, list)) for target, value in zip(targets, values): self.assertTrue(np.all(value == target)) def test_to_matrix_5q_sparse(self): """Test 5-qubit to_matrix method w/ sparse=True.""" labels = ["XXXYY", "IXIZY", "ZYXIX"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix(sparse=True) for mat, targ in zip(values, targets): self.assertTrue(isinstance(mat, csr_matrix)) self.assertTrue(np.all(targ == mat.toarray())) def test_to_matrix_5q_with_phase(self): """Test 5-qubit to_matrix method with phase.""" labels = ["iIXIXI", "-YZIXI", "-iIIXYZ"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix() self.assertTrue(isinstance(values, list)) for target, value in zip(targets, values): self.assertTrue(np.all(value == target)) def test_to_matrix_5q_sparse_with_phase(self): """Test 5-qubit to_matrix method w/ sparse=True with phase.""" labels = ["iXXXYY", "-IXIZY", "-iZYXIX"] targets = [pauli_mat(i) for i in labels] values = PauliList(labels).to_matrix(sparse=True) for mat, targ in zip(values, targets): self.assertTrue(isinstance(mat, csr_matrix)) self.assertTrue(np.all(targ == mat.toarray())) class TestPauliListIteration(QiskitTestCase): """Tests for PauliList iterators class.""" def test_enumerate(self): """Test enumerate with PauliList.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] pauli = PauliList(labels) for idx, i in enumerate(pauli): self.assertEqual(i, PauliList(labels[idx])) def test_iter(self): """Test iter with PauliList.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] pauli = PauliList(labels) for idx, i in enumerate(iter(pauli)): self.assertEqual(i, PauliList(labels[idx])) def test_zip(self): """Test zip with PauliList.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] pauli = PauliList(labels) for label, i in zip(labels, pauli): self.assertEqual(i, PauliList(label)) def test_label_iter(self): """Test PauliList label_iter method.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] pauli = PauliList(labels) for idx, i in enumerate(pauli.label_iter()): self.assertEqual(i, labels[idx]) def test_matrix_iter(self): """Test PauliList dense matrix_iter method.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] pauli = PauliList(labels) for idx, i in enumerate(pauli.matrix_iter()): self.assertTrue(np.all(i == pauli_mat(labels[idx]))) def test_matrix_iter_sparse(self): """Test PauliList sparse matrix_iter method.""" labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"] pauli = PauliList(labels) for idx, i in enumerate(pauli.matrix_iter(sparse=True)): self.assertTrue(isinstance(i, csr_matrix)) self.assertTrue(np.all(i.toarray() == pauli_mat(labels[idx]))) @ddt class TestPauliListOperator(QiskitTestCase): """Tests for PauliList base operator methods.""" @combine(j=range(1, 10)) def test_tensor(self, j): """Test tensor method j={j}.""" labels1 = ["XX", "YY"] labels2 = [j * "I", j * "Z"] pauli1 = PauliList(labels1) pauli2 = PauliList(labels2) value = pauli1.tensor(pauli2) target = PauliList([l1 + l2 for l1 in labels1 for l2 in labels2]) self.assertEqual(value, target) @combine(j=range(1, 10)) def test_tensor_with_phase(self, j): """Test tensor method j={j} with phase.""" labels1 = ["XX", "iYY"] labels2 = [j * "I", "i" + j * "Z"] pauli1 = PauliList(labels1) pauli2 = PauliList(labels2) value = pauli1.tensor(pauli2) target = PauliList(["XX" + "I" * j, "iXX" + "Z" * j, "iYY" + "I" * j, "-YY" + "Z" * j]) self.assertEqual(value, target) @combine(j=range(1, 10)) def test_expand(self, j): """Test expand method j={j}.""" labels1 = ["XX", "YY"] labels2 = [j * "I", j * "Z"] pauli1 = PauliList(labels1) pauli2 = PauliList(labels2) value = pauli1.expand(pauli2) target = PauliList([j + i for j in labels2 for i in labels1]) self.assertEqual(value, target) @combine(j=range(1, 10)) def test_expand_with_phase(self, j): """Test expand method j={j}.""" labels1 = ["-XX", "iYY"] labels2 = ["i" + j * "I", "-i" + j * "Z"] pauli1 = PauliList(labels1) pauli2 = PauliList(labels2) value = pauli1.expand(pauli2) target = PauliList( ["-i" + "I" * j + "XX", "-" + "I" * j + "YY", "i" + "Z" * j + "XX", "Z" * j + "YY"] ) self.assertEqual(value, target) def test_compose_1q(self): """Test 1-qubit compose methods.""" # Test single qubit Pauli dot products pauli = PauliList(["I", "X", "Y", "Z"]) with self.subTest(msg="compose single I"): target = PauliList(["I", "X", "Y", "Z"]) value = pauli.compose("I") self.assertEqual(target, value) with self.subTest(msg="compose single X"): target = PauliList(["X", "I", "iZ", "-iY"]) value = pauli.compose("X") self.assertEqual(target, value) with self.subTest(msg="compose single Y"): target = PauliList(["Y", "-iZ", "I", "iX"]) value = pauli.compose("Y") self.assertEqual(target, value) with self.subTest(msg="compose single Z"): target = PauliList(["Z", "iY", "-iX", "I"]) value = pauli.compose("Z") self.assertEqual(target, value) def test_dot_1q(self): """Test 1-qubit dot method.""" # Test single qubit Pauli dot products pauli = PauliList(["I", "X", "Y", "Z"]) with self.subTest(msg="dot single I"): target = PauliList(["I", "X", "Y", "Z"]) value = pauli.dot("I") self.assertEqual(target, value) with self.subTest(msg="dot single X"): target = PauliList(["X", "I", "-iZ", "iY"]) value = pauli.dot("X") self.assertEqual(target, value) with self.subTest(msg="dot single Y"): target = PauliList(["Y", "iZ", "I", "-iX"]) value = pauli.dot("Y") self.assertEqual(target, value) with self.subTest(msg="dot single Z"): target = PauliList(["Z", "-iY", "iX", "I"]) value = pauli.dot("Z") self.assertEqual(target, value) def test_qargs_compose_1q(self): """Test 1-qubit compose method with qargs.""" pauli1 = PauliList(["III", "XXX"]) pauli2 = PauliList("Z") with self.subTest(msg="compose 1-qubit qargs=[0]"): target = PauliList(["IIZ", "iXXY"]) value = pauli1.compose(pauli2, qargs=[0]) self.assertEqual(value, target) with self.subTest(msg="compose 1-qubit qargs=[1]"): target = PauliList(["IZI", "iXYX"]) value = pauli1.compose(pauli2, qargs=[1]) self.assertEqual(value, target) with self.subTest(msg="compose 1-qubit qargs=[2]"): target = PauliList(["ZII", "iYXX"]) value = pauli1.compose(pauli2, qargs=[2]) self.assertEqual(value, target) def test_qargs_dot_1q(self): """Test 1-qubit dot method with qargs.""" pauli1 = PauliList(["III", "XXX"]) pauli2 = PauliList("Z") with self.subTest(msg="dot 1-qubit qargs=[0]"): target = PauliList(["IIZ", "-iXXY"]) value = pauli1.dot(pauli2, qargs=[0]) self.assertEqual(value, target) with self.subTest(msg="dot 1-qubit qargs=[1]"): target = PauliList(["IZI", "-iXYX"]) value = pauli1.dot(pauli2, qargs=[1]) self.assertEqual(value, target) with self.subTest(msg="dot 1-qubit qargs=[2]"): target = PauliList(["ZII", "-iYXX"]) value = pauli1.dot(pauli2, qargs=[2]) self.assertEqual(value, target) def test_qargs_compose_2q(self): """Test 2-qubit compose method with qargs.""" pauli1 = PauliList(["III", "XXX"]) pauli2 = PauliList("ZY") with self.subTest(msg="compose 2-qubit qargs=[0, 1]"): target = PauliList(["IZY", "XYZ"]) value = pauli1.compose(pauli2, qargs=[0, 1]) self.assertEqual(value, target) with self.subTest(msg="compose 2-qubit qargs=[1, 0]"): target = PauliList(["IYZ", "XZY"]) value = pauli1.compose(pauli2, qargs=[1, 0]) self.assertEqual(value, target) with self.subTest(msg="compose 2-qubit qargs=[0, 2]"): target = PauliList(["ZIY", "YXZ"]) value = pauli1.compose(pauli2, qargs=[0, 2]) self.assertEqual(value, target) with self.subTest(msg="compose 2-qubit qargs=[2, 0]"): target = PauliList(["YIZ", "ZXY"]) value = pauli1.compose(pauli2, qargs=[2, 0]) self.assertEqual(value, target) def test_qargs_dot_2q(self): """Test 2-qubit dot method with qargs.""" pauli1 = PauliList(["III", "XXX"]) pauli2 = PauliList("ZY") with self.subTest(msg="dot 2-qubit qargs=[0, 1]"): target = PauliList(["IZY", "XYZ"]) value = pauli1.dot(pauli2, qargs=[0, 1]) self.assertEqual(value, target) with self.subTest(msg="dot 2-qubit qargs=[1, 0]"): target = PauliList(["IYZ", "XZY"]) value = pauli1.dot(pauli2, qargs=[1, 0]) self.assertEqual(value, target) with self.subTest(msg="dot 2-qubit qargs=[0, 2]"): target = PauliList(["ZIY", "YXZ"]) value = pauli1.dot(pauli2, qargs=[0, 2]) self.assertEqual(value, target) with self.subTest(msg="dot 2-qubit qargs=[2, 0]"): target = PauliList(["YIZ", "ZXY"]) value = pauli1.dot(pauli2, qargs=[2, 0]) self.assertEqual(value, target) def test_qargs_compose_3q(self): """Test 3-qubit compose method with qargs.""" pauli1 = PauliList(["III", "XXX"]) pauli2 = PauliList("XYZ") with self.subTest(msg="compose 3-qubit qargs=None"): target = PauliList(["XYZ", "IZY"]) value = pauli1.compose(pauli2) self.assertEqual(value, target) with self.subTest(msg="compose 3-qubit qargs=[0, 1, 2]"): target = PauliList(["XYZ", "IZY"]) value = pauli1.compose(pauli2, qargs=[0, 1, 2]) self.assertEqual(value, target) with self.subTest(msg="compose 3-qubit qargs=[2, 1, 0]"): target = PauliList(["ZYX", "YZI"]) value = pauli1.compose(pauli2, qargs=[2, 1, 0]) self.assertEqual(value, target) with self.subTest(msg="compose 3-qubit qargs=[1, 0, 2]"): target = PauliList(["XZY", "IYZ"]) value = pauli1.compose(pauli2, qargs=[1, 0, 2]) self.assertEqual(value, target) def test_qargs_dot_3q(self): """Test 3-qubit dot method with qargs.""" pauli1 = PauliList(["III", "XXX"]) pauli2 = PauliList("XYZ") with self.subTest(msg="dot 3-qubit qargs=None"): target = PauliList(["XYZ", "IZY"]) value = pauli1.dot(pauli2, qargs=[0, 1, 2]) self.assertEqual(value, target) with self.subTest(msg="dot 3-qubit qargs=[0, 1, 2]"): target = PauliList(["XYZ", "IZY"]) value = pauli1.dot(pauli2, qargs=[0, 1, 2]) self.assertEqual(value, target) with self.subTest(msg="dot 3-qubit qargs=[2, 1, 0]"): target = PauliList(["ZYX", "YZI"]) value = pauli1.dot(pauli2, qargs=[2, 1, 0]) self.assertEqual(value, target) with self.subTest(msg="dot 3-qubit qargs=[1, 0, 2]"): target = PauliList(["XZY", "IYZ"]) value = pauli1.dot(pauli2, qargs=[1, 0, 2]) self.assertEqual(value, target) @ddt class TestPauliListMethods(QiskitTestCase): """Tests for PauliList utility methods class.""" def test_sort(self): """Test sort method.""" with self.subTest(msg="1 qubit standard order"): unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"] srt = ["I", "-iI", "-I", "iI", "X", "X", "Y", "-iY", "Z", "Z"] target = PauliList(srt) value = PauliList(unsrt).sort() self.assertEqual(target, value) with self.subTest(msg="1 qubit weight order"): unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"] srt = ["I", "-iI", "-I", "iI", "X", "X", "Y", "-iY", "Z", "Z"] target = PauliList(srt) value = PauliList(unsrt).sort(weight=True) self.assertEqual(target, value) with self.subTest(msg="1 qubit phase order"): unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"] srt = ["I", "X", "X", "Y", "Z", "Z", "-iI", "-iY", "-I", "iI"] target = PauliList(srt) value = PauliList(unsrt).sort(phase=True) self.assertEqual(target, value) with self.subTest(msg="1 qubit weight & phase order"): unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"] srt = ["I", "X", "X", "Y", "Z", "Z", "-iI", "-iY", "-I", "iI"] target = PauliList(srt) value = PauliList(unsrt).sort(weight=True, phase=True) self.assertEqual(target, value) with self.subTest(msg="2 qubit standard order"): srt = [ "II", "IX", "IX", "IY", "IZ", "iIZ", "XI", "XX", "XX", "iXX", "XY", "XZ", "iXZ", "YI", "YI", "-YI", "YX", "-iYX", "YY", "-iYY", "-YY", "iYY", "YZ", "ZI", "ZX", "ZX", "ZY", "ZZ", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort() self.assertEqual(target, value) with self.subTest(msg="2 qubit weight order"): srt = [ "II", "IX", "IX", "IY", "IZ", "iIZ", "XI", "YI", "YI", "-YI", "ZI", "XX", "XX", "iXX", "XY", "XZ", "iXZ", "YX", "-iYX", "YY", "YY", "-YY", "YZ", "ZX", "ZX", "ZY", "ZZ", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort(weight=True) self.assertEqual(target, value) with self.subTest(msg="2 qubit phase order"): srt = [ "II", "IX", "IX", "IY", "IZ", "XI", "XX", "XX", "XY", "XZ", "YI", "YI", "YX", "YY", "YY", "YZ", "ZI", "ZX", "ZX", "ZY", "ZZ", "-iYX", "-YI", "-YY", "iIZ", "iXX", "iXZ", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort(phase=True) self.assertEqual(target, value) with self.subTest(msg="2 qubit weight & phase order"): srt = [ "II", "IX", "IX", "IY", "IZ", "XI", "YI", "YI", "ZI", "XX", "XX", "XY", "XZ", "YX", "YY", "YY", "YZ", "ZX", "ZX", "ZY", "ZZ", "-iYX", "-YI", "-YY", "iIZ", "iXX", "iXZ", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort(weight=True, phase=True) self.assertEqual(target, value) with self.subTest(msg="3 qubit standard order"): srt = [ "III", "III", "IIX", "IIY", "-IIY", "IIZ", "IXI", "IXX", "IXY", "iIXY", "IXZ", "IYI", "IYX", "IYY", "IYZ", "IZI", "IZX", "IZY", "IZY", "IZZ", "XII", "XII", "XIX", "XIY", "XIZ", "XXI", "XXX", "-iXXX", "XXY", "XXZ", "XYI", "XYX", "iXYX", "XYY", "XYZ", "XYZ", "XZI", "XZX", "XZY", "XZZ", "YII", "YIX", "YIY", "YIZ", "YXI", "YXX", "YXY", "YXZ", "YXZ", "YYI", "YYX", "YYX", "YYY", "YYZ", "YZI", "YZX", "YZY", "YZZ", "ZII", "ZIX", "ZIY", "ZIZ", "ZXI", "ZXX", "iZXX", "ZXY", "ZXZ", "ZYI", "ZYI", "ZYX", "ZYY", "ZYZ", "ZZI", "ZZX", "ZZY", "ZZZ", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort() self.assertEqual(target, value) with self.subTest(msg="3 qubit weight order"): srt = [ "III", "III", "IIX", "IIY", "-IIY", "IIZ", "IXI", "IYI", "IZI", "XII", "XII", "YII", "ZII", "IXX", "IXY", "iIXY", "IXZ", "IYX", "IYY", "IYZ", "IZX", "IZY", "IZY", "IZZ", "XIX", "XIY", "XIZ", "XXI", "XYI", "XZI", "YIX", "YIY", "YIZ", "YXI", "YYI", "YZI", "ZIX", "ZIY", "ZIZ", "ZXI", "ZYI", "ZYI", "ZZI", "XXX", "-iXXX", "XXY", "XXZ", "XYX", "iXYX", "XYY", "XYZ", "XYZ", "XZX", "XZY", "XZZ", "YXX", "YXY", "YXZ", "YXZ", "YYX", "YYX", "YYY", "YYZ", "YZX", "YZY", "YZZ", "ZXX", "iZXX", "ZXY", "ZXZ", "ZYX", "ZYY", "ZYZ", "ZZX", "ZZY", "ZZZ", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort(weight=True) self.assertEqual(target, value) with self.subTest(msg="3 qubit phase order"): srt = [ "III", "III", "IIX", "IIY", "IIZ", "IXI", "IXX", "IXY", "IXZ", "IYI", "IYX", "IYY", "IYZ", "IZI", "IZX", "IZY", "IZY", "IZZ", "XII", "XII", "XIX", "XIY", "XIZ", "XXI", "XXX", "XXY", "XXZ", "XYI", "XYX", "XYY", "XYZ", "XYZ", "XZI", "XZX", "XZY", "XZZ", "YII", "YIX", "YIY", "YIZ", "YXI", "YXX", "YXY", "YXZ", "YXZ", "YYI", "YYX", "YYX", "YYY", "YYZ", "YZI", "YZX", "YZY", "YZZ", "ZII", "ZIX", "ZIY", "ZIZ", "ZXI", "ZXX", "ZXY", "ZXZ", "ZYI", "ZYI", "ZYX", "ZYY", "ZYZ", "ZZI", "ZZX", "ZZY", "ZZZ", "-iXXX", "-IIY", "iIXY", "iXYX", "iZXX", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort(phase=True) self.assertEqual(target, value) with self.subTest(msg="3 qubit weight & phase order"): srt = [ "III", "III", "IIX", "IIY", "IYI", "IZI", "XII", "XII", "YII", "ZII", "IXX", "IXY", "IXZ", "IYX", "IYY", "IYZ", "IZX", "IZY", "IZY", "IZZ", "XIX", "XIY", "XIZ", "XXI", "XYI", "XZI", "YIX", "YIY", "YIZ", "YYI", "YZI", "ZIX", "ZIY", "ZIZ", "ZXI", "ZYI", "ZYI", "ZZI", "XXX", "XXY", "XXZ", "XYX", "XYY", "XYZ", "XZX", "XZY", "XZZ", "YXX", "YXY", "YXZ", "YXZ", "YYX", "YYX", "YYY", "YYZ", "YZX", "YZY", "YZZ", "ZXX", "ZXY", "ZXZ", "ZYX", "ZYY", "ZYZ", "ZZX", "ZZY", "ZZZ", "-iZIZ", "-iXXX", "-IIY", "iIXI", "iIXY", "iYXI", "iXYX", "iXYZ", "iZXX", ] unsrt = srt.copy() np.random.shuffle(unsrt) target = PauliList(srt) value = PauliList(unsrt).sort(weight=True, phase=True) self.assertEqual(target, value) def test_unique(self): """Test unique method.""" with self.subTest(msg="1 qubit"): labels = ["X", "Z", "X", "X", "I", "Y", "I", "X", "Z", "Z", "X", "I"] unique = ["X", "Z", "I", "Y"] target = PauliList(unique) value = PauliList(labels).unique() self.assertEqual(target, value) with self.subTest(msg="2 qubit"): labels = ["XX", "IX", "XX", "II", "IZ", "ZI", "YX", "YX", "ZZ", "IX", "XI"] unique = ["XX", "IX", "II", "IZ", "ZI", "YX", "ZZ", "XI"] target = PauliList(unique) value = PauliList(labels).unique() self.assertEqual(target, value) with self.subTest(msg="10 qubit"): labels = [10 * "X", 10 * "I", 10 * "X"] unique = [10 * "X", 10 * "I"] target = PauliList(unique) value = PauliList(labels).unique() self.assertEqual(target, value) def test_delete(self): """Test delete method.""" with self.subTest(msg="single row"): for j in range(1, 6): pauli = PauliList([j * "X", j * "Y"]) self.assertEqual(pauli.delete(0), PauliList(j * "Y")) self.assertEqual(pauli.delete(1), PauliList(j * "X")) with self.subTest(msg="multiple rows"): for j in range(1, 6): pauli = PauliList([j * "X", "-i" + j * "Y", j * "Z"]) self.assertEqual(pauli.delete([0, 2]), PauliList("-i" + j * "Y")) self.assertEqual(pauli.delete([1, 2]), PauliList(j * "X")) self.assertEqual(pauli.delete([0, 1]), PauliList(j * "Z")) with self.subTest(msg="single qubit"): pauli = PauliList(["IIX", "iIYI", "ZII"]) value = pauli.delete(0, qubit=True) target = PauliList(["II", "iIY", "ZI"]) self.assertEqual(value, target) value = pauli.delete(1, qubit=True) target = PauliList(["IX", "iII", "ZI"]) self.assertEqual(value, target) value = pauli.delete(2, qubit=True) target = PauliList(["IX", "iYI", "II"]) self.assertEqual(value, target) with self.subTest(msg="multiple qubits"): pauli = PauliList(["IIX", "IYI", "-ZII"]) value = pauli.delete([0, 1], qubit=True) target = PauliList(["I", "I", "-Z"]) self.assertEqual(value, target) value = pauli.delete([1, 2], qubit=True) target = PauliList(["X", "I", "-I"]) self.assertEqual(value, target) value = pauli.delete([0, 2], qubit=True) target = PauliList(["I", "Y", "-I"]) self.assertEqual(value, target) def test_insert(self): """Test insert method.""" # Insert single row for j in range(1, 10): pauli = PauliList(j * "X") target0 = PauliList([j * "I", j * "X"]) target1 = PauliList([j * "X", j * "I"]) with self.subTest(msg=f"single row from str ({j})"): value0 = pauli.insert(0, j * "I") self.assertEqual(value0, target0) value1 = pauli.insert(1, j * "I") self.assertEqual(value1, target1) with self.subTest(msg=f"single row from PauliList ({j})"): value0 = pauli.insert(0, PauliList(j * "I")) self.assertEqual(value0, target0) value1 = pauli.insert(1, PauliList(j * "I")) self.assertEqual(value1, target1) target0 = PauliList(["i" + j * "I", j * "X"]) target1 = PauliList([j * "X", "i" + j * "I"]) with self.subTest(msg=f"single row with phase from str ({j})"): value0 = pauli.insert(0, "i" + j * "I") self.assertEqual(value0, target0) value1 = pauli.insert(1, "i" + j * "I") self.assertEqual(value1, target1) with self.subTest(msg=f"single row with phase from PauliList ({j})"): value0 = pauli.insert(0, PauliList("i" + j * "I")) self.assertEqual(value0, target0) value1 = pauli.insert(1, PauliList("i" + j * "I")) self.assertEqual(value1, target1) # Insert multiple rows for j in range(1, 10): pauli = PauliList("i" + j * "X") insert = PauliList([j * "I", j * "Y", j * "Z", "-i" + j * "X"]) target0 = insert + pauli target1 = pauli + insert with self.subTest(msg=f"multiple-rows from PauliList ({j})"): value0 = pauli.insert(0, insert) self.assertEqual(value0, target0) value1 = pauli.insert(1, insert) self.assertEqual(value1, target1) # Insert single column pauli = PauliList(["X", "Y", "Z", "-iI"]) for i in ["I", "X", "Y", "Z", "iY"]: phase = "" if len(i) == 1 else i[0] p = i if len(i) == 1 else i[1] target0 = PauliList( [ phase + "X" + p, phase + "Y" + p, phase + "Z" + p, ("" if phase else "-i") + "I" + p, ] ) target1 = PauliList( [ i + "X", i + "Y", i + "Z", ("" if phase else "-i") + p + "I", ] ) with self.subTest(msg="single-column single-val from str"): value = pauli.insert(0, i, qubit=True) self.assertEqual(value, target0) value = pauli.insert(1, i, qubit=True) self.assertEqual(value, target1) with self.subTest(msg="single-column single-val from PauliList"): value = pauli.insert(0, PauliList(i), qubit=True) self.assertEqual(value, target0) value = pauli.insert(1, PauliList(i), qubit=True) self.assertEqual(value, target1) # Insert single column with multiple values pauli = PauliList(["X", "Y", "iZ"]) for i in [["I", "X", "Y"], ["X", "iY", "Z"], ["Y", "Z", "I"]]: target0 = PauliList( ["X" + i[0], "Y" + i[1] if len(i[1]) == 1 else i[1][0] + "Y" + i[1][1], "iZ" + i[2]] ) target1 = PauliList([i[0] + "X", i[1] + "Y", "i" + i[2] + "Z"]) with self.subTest(msg="single-column multiple-vals from PauliList"): value = pauli.insert(0, PauliList(i), qubit=True) self.assertEqual(value, target0) value = pauli.insert(1, PauliList(i), qubit=True) self.assertEqual(value, target1) # Insert multiple columns from single pauli = PauliList(["X", "iY", "Z"]) for j in range(1, 5): for i in [j * "I", j * "X", j * "Y", "i" + j * "Z"]: phase = "" if len(i) == j else i[0] p = i if len(i) == j else i[1:] target0 = PauliList( [ phase + "X" + p, ("-" if phase else "i") + "Y" + p, phase + "Z" + p, ] ) target1 = PauliList([i + "X", ("-" if phase else "i") + p + "Y", i + "Z"]) with self.subTest(msg="multiple-columns single-val from str"): value = pauli.insert(0, i, qubit=True) self.assertEqual(value, target0) value = pauli.insert(1, i, qubit=True) self.assertEqual(value, target1) with self.subTest(msg="multiple-columns single-val from PauliList"): value = pauli.insert(0, PauliList(i), qubit=True) self.assertEqual(value, target0) value = pauli.insert(1, PauliList(i), qubit=True) self.assertEqual(value, target1) # Insert multiple columns multiple row values pauli = PauliList(["X", "Y", "-iZ"]) for j in range(1, 5): for i in [ [j * "I", j * "X", j * "Y"], [j * "X", j * "Z", "i" + j * "Y"], [j * "Y", j * "Z", j * "I"], ]: target0 = PauliList( [ "X" + i[0], "Y" + i[1], ("-i" if len(i[2]) == j else "") + "Z" + i[2][-j:], ] ) target1 = PauliList( [ i[0] + "X", i[1] + "Y", ("-i" if len(i[2]) == j else "") + i[2][-j:] + "Z", ] ) with self.subTest(msg="multiple-column multiple-vals from PauliList"): value = pauli.insert(0, PauliList(i), qubit=True) self.assertEqual(value, target0) value = pauli.insert(1, PauliList(i), qubit=True) self.assertEqual(value, target1) def test_commutes(self): """Test commutes method.""" # Single qubit Pauli pauli = PauliList(["I", "X", "Y", "Z", "-iY"]) with self.subTest(msg="commutes single-Pauli I"): value = list(pauli.commutes("I")) target = [True, True, True, True, True] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli X"): value = list(pauli.commutes("X")) target = [True, True, False, False, False] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli Y"): value = list(pauli.commutes("Y")) target = [True, False, True, False, True] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli Z"): value = list(pauli.commutes("Z")) target = [True, False, False, True, False] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli iZ"): value = list(pauli.commutes("iZ")) target = [True, False, False, True, False] self.assertEqual(value, target) # 2-qubit Pauli pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "-iYY"]) with self.subTest(msg="commutes single-Pauli II"): value = list(pauli.commutes("II")) target = [True, True, True, True, True, True] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli IX"): value = list(pauli.commutes("IX")) target = [True, True, True, False, False, False] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli XI"): value = list(pauli.commutes("XI")) target = [True, True, False, True, False, False] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli YI"): value = list(pauli.commutes("YI")) target = [True, True, True, False, False, True] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli IY"): value = list(pauli.commutes("IY")) target = [True, False, True, True, False, True] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli XY"): value = list(pauli.commutes("XY")) target = [True, False, False, True, True, False] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli YX"): value = list(pauli.commutes("YX")) target = [True, True, True, True, True, False] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli ZZ"): value = list(pauli.commutes("ZZ")) target = [True, False, False, True, True, True] self.assertEqual(value, target) with self.subTest(msg="commutes single-Pauli iYX"): value = list(pauli.commutes("iYX")) target = [True, True, True, True, True, False] self.assertEqual(value, target) def test_anticommutes(self): """Test anticommutes method.""" # Single qubit Pauli pauli = PauliList(["I", "X", "Y", "Z", "-iY"]) with self.subTest(msg="anticommutes single-Pauli I"): value = list(pauli.anticommutes("I")) target = [False, False, False, False, False] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli X"): value = list(pauli.anticommutes("X")) target = [False, False, True, True, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli Y"): value = list(pauli.anticommutes("Y")) target = [False, True, False, True, False] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli Z"): value = list(pauli.anticommutes("Z")) target = [False, True, True, False, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli iZ"): value = list(pauli.anticommutes("iZ")) target = [False, True, True, False, True] self.assertEqual(value, target) # 2-qubit Pauli pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iZX"]) with self.subTest(msg="anticommutes single-Pauli II"): value = list(pauli.anticommutes("II")) target = [False, False, False, False, False, False] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli IX"): value = list(pauli.anticommutes("IX")) target = [False, False, False, True, True, False] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli XI"): value = list(pauli.anticommutes("XI")) target = [False, False, True, False, True, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli YI"): value = list(pauli.anticommutes("YI")) target = [False, False, False, True, True, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli IY"): value = list(pauli.anticommutes("IY")) target = [False, True, False, False, True, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli XY"): value = list(pauli.anticommutes("XY")) target = [False, True, True, False, False, False] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli YX"): value = list(pauli.anticommutes("YX")) target = [False, False, False, False, False, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli ZZ"): value = list(pauli.anticommutes("ZZ")) target = [False, True, True, False, False, True] self.assertEqual(value, target) with self.subTest(msg="anticommutes single-Pauli iXY"): value = list(pauli.anticommutes("iXY")) target = [False, True, True, False, False, False] self.assertEqual(value, target) def test_commutes_with_all(self): """Test commutes_with_all method.""" # 1-qubit pauli = PauliList(["I", "X", "Y", "Z", "-iY"]) with self.subTest(msg="commutes_with_all [I]"): value = list(pauli.commutes_with_all("I")) target = [0, 1, 2, 3, 4] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [X]"): value = list(pauli.commutes_with_all("X")) target = [0, 1] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [Y]"): value = list(pauli.commutes_with_all("Y")) target = [0, 2, 4] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [Z]"): value = list(pauli.commutes_with_all("Z")) target = [0, 3] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [iY]"): value = list(pauli.commutes_with_all("iY")) target = [0, 2, 4] self.assertEqual(value, target) # 2-qubit Pauli pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iXY"]) with self.subTest(msg="commutes_with_all [IX, YI]"): other = PauliList(["IX", "YI"]) value = list(pauli.commutes_with_all(other)) target = [0, 1, 2] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [XY, ZZ]"): other = PauliList(["XY", "ZZ"]) value = list(pauli.commutes_with_all(other)) target = [0, 3, 4, 5] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [YX, ZZ]"): other = PauliList(["YX", "ZZ"]) value = list(pauli.commutes_with_all(other)) target = [0, 3, 4, 5] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [XY, YX]"): other = PauliList(["XY", "YX"]) value = list(pauli.commutes_with_all(other)) target = [0, 3, 4, 5] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [XY, IX]"): other = PauliList(["XY", "IX"]) value = list(pauli.commutes_with_all(other)) target = [0] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [YX, IX]"): other = PauliList(["YX", "IX"]) value = list(pauli.commutes_with_all(other)) target = [0, 1, 2] self.assertEqual(value, target) with self.subTest(msg="commutes_with_all [-iYX, iZZ]"): other = PauliList(["-iYX", "iZZ"]) value = list(pauli.commutes_with_all(other)) target = [0, 3, 4, 5] self.assertEqual(value, target) def test_anticommutes_with_all(self): """Test anticommutes_with_all method.""" # 1-qubit pauli = PauliList(["I", "X", "Y", "Z", "-iY"]) with self.subTest(msg="anticommutes_with_all [I]"): value = list(pauli.anticommutes_with_all("I")) target = [] self.assertEqual(value, target) with self.subTest(msg="antianticommutes_with_all [X]"): value = list(pauli.anticommutes_with_all("X")) target = [2, 3, 4] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [Y]"): value = list(pauli.anticommutes_with_all("Y")) target = [1, 3] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [Z]"): value = list(pauli.anticommutes_with_all("Z")) target = [1, 2, 4] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [iY]"): value = list(pauli.anticommutes_with_all("iY")) target = [1, 3] self.assertEqual(value, target) # 2-qubit Pauli pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iZX"]) with self.subTest(msg="anticommutes_with_all [IX, YI]"): other = PauliList(["IX", "YI"]) value = list(pauli.anticommutes_with_all(other)) target = [3, 4] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [XY, ZZ]"): other = PauliList(["XY", "ZZ"]) value = list(pauli.anticommutes_with_all(other)) target = [1, 2] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [YX, ZZ]"): other = PauliList(["YX", "ZZ"]) value = list(pauli.anticommutes_with_all(other)) target = [5] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [XY, YX]"): other = PauliList(["XY", "YX"]) value = list(pauli.anticommutes_with_all(other)) target = [] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [XY, IX]"): other = PauliList(["XY", "IX"]) value = list(pauli.anticommutes_with_all(other)) target = [] self.assertEqual(value, target) with self.subTest(msg="anticommutes_with_all [YX, IX]"): other = PauliList(["YX", "IX"]) value = list(pauli.anticommutes_with_all(other)) target = [] self.assertEqual(value, target) @combine( gate=( IGate(), XGate(), YGate(), ZGate(), HGate(), SGate(), SdgGate(), Clifford(IGate()), Clifford(XGate()), Clifford(YGate()), Clifford(ZGate()), Clifford(HGate()), Clifford(SGate()), Clifford(SdgGate()), ) ) def test_evolve_clifford1(self, gate): """Test evolve method for 1-qubit Clifford gates.""" op = Operator(gate) pauli_list = PauliList(pauli_group_labels(1, True)) value = [Operator(pauli) for pauli in pauli_list.evolve(gate)] value_h = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="h")] value_s = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="s")] if isinstance(gate, Clifford): value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.adjoint())] else: value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.inverse())] target = [op.adjoint().dot(pauli).dot(op) for pauli in pauli_list] self.assertListEqual(value, target) self.assertListEqual(value, value_h) self.assertListEqual(value_inv, value_s) @combine( gate=( CXGate(), CYGate(), CZGate(), SwapGate(), Clifford(CXGate()), Clifford(CYGate()), Clifford(CZGate()), Clifford(SwapGate()), ) ) def test_evolve_clifford2(self, gate): """Test evolve method for 2-qubit Clifford gates.""" op = Operator(gate) pauli_list = PauliList(pauli_group_labels(2, True)) value = [Operator(pauli) for pauli in pauli_list.evolve(gate)] value_h = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="h")] value_s = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="s")] if isinstance(gate, Clifford): value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.adjoint())] else: value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.inverse())] target = [op.adjoint().dot(pauli).dot(op) for pauli in pauli_list] self.assertListEqual(value, target) self.assertListEqual(value, value_h) self.assertListEqual(value_inv, value_s) def test_phase_dtype_evolve_clifford(self): """Test phase dtype during evolve method for Clifford gates.""" gates = ( IGate(), XGate(), YGate(), ZGate(), HGate(), SGate(), SdgGate(), CXGate(), CYGate(), CZGate(), SwapGate(), ) dtypes = [ int, np.int8, np.uint8, np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64, ] for gate, dtype in itertools.product(gates, dtypes): z = np.ones(gate.num_qubits, dtype=bool) x = np.ones(gate.num_qubits, dtype=bool) phase = (np.sum(z & x) % 4).astype(dtype) paulis = Pauli((z, x, phase)) evo = paulis.evolve(gate) self.assertEqual(evo.phase.dtype, dtype) @combine(phase=(True, False)) def test_evolve_clifford_qargs(self, phase): """Test evolve method for random Clifford""" cliff = random_clifford(3, seed=10) op = Operator(cliff) pauli_list = random_pauli_list(5, 3, seed=10, phase=phase) qargs = [3, 0, 1] value = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs)] value_inv = [Operator(pauli) for pauli in pauli_list.evolve(cliff.adjoint(), qargs=qargs)] value_h = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs, frame="h")] value_s = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs, frame="s")] target = [ Operator(pauli).compose(op.adjoint(), qargs=qargs).dot(op, qargs=qargs) for pauli in pauli_list ] self.assertListEqual(value, target) self.assertListEqual(value, value_h) self.assertListEqual(value_inv, value_s) def test_group_qubit_wise_commuting(self): """Test grouping qubit-wise commuting operators""" def qubitwise_commutes(left: Pauli, right: Pauli) -> bool: return len(left) == len(right) and all(a.commutes(b) for a, b in zip(left, right)) input_labels = ["IY", "ZX", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "iZZ", "II"] np.random.shuffle(input_labels) pauli_list = PauliList(input_labels) groups = pauli_list.group_qubit_wise_commuting() # checking that every input Pauli in pauli_list is in a group in the ouput output_labels = [pauli.to_label() for group in groups for pauli in group] self.assertListEqual(sorted(output_labels), sorted(input_labels)) # Within each group, every operator qubit-wise commutes with every other operator. for group in groups: self.assertTrue( all( qubitwise_commutes(pauli1, pauli2) for pauli1, pauli2 in itertools.combinations(group, 2) ) ) # For every pair of groups, at least one element from one does not qubit-wise commute with # at least one element of the other. for group1, group2 in itertools.combinations(groups, 2): self.assertFalse( all( qubitwise_commutes(group1_pauli, group2_pauli) for group1_pauli, group2_pauli in itertools.product(group1, group2) ) ) def test_group_commuting(self): """Test general grouping commuting operators""" def commutes(left: Pauli, right: Pauli) -> bool: return len(left) == len(right) and left.commutes(right) input_labels = ["IY", "ZX", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "iZZ", "II"] np.random.shuffle(input_labels) pauli_list = PauliList(input_labels) # if qubit_wise=True, equivalent to test_group_qubit_wise_commuting groups = pauli_list.group_commuting(qubit_wise=False) # checking that every input Pauli in pauli_list is in a group in the ouput output_labels = [pauli.to_label() for group in groups for pauli in group] self.assertListEqual(sorted(output_labels), sorted(input_labels)) # Within each group, every operator commutes with every other operator. for group in groups: self.assertTrue( all(commutes(pauli1, pauli2) for pauli1, pauli2 in itertools.combinations(group, 2)) ) # For every pair of groups, at least one element from one group does not commute with # at least one element of the other. for group1, group2 in itertools.combinations(groups, 2): self.assertFalse( all( commutes(group1_pauli, group2_pauli) for group1_pauli, group2_pauli in itertools.product(group1, group2) ) ) if __name__ == "__main__": unittest.main()
https://github.com/JackHidary/quantumcomputingbook
JackHidary
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/riddheshMarkandeya/shors-algorithm-quantum
riddheshMarkandeya
import math import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute from qiskit.quantum_info.operators import Operator from qiskit.circuit.library import CU1Gate from qiskit.visualization import plot_histogram from fractions import Fraction # Provided helper functions and oracles def make_permutation_matrix(n, permutation): r = np.zeros((n,n), dtype=int) for i in range(n): r[permutation(i), i] = 1 return r def mult_mat(x,k,N): n = math.ceil(math.log(N, 2)) return make_permutation_matrix( 2**n, permutation=lambda y: y*pow(x,k) % N if y<N else y) def c_mult_mat(x,k,N): n = math.ceil(math.log(N, 2)) permutation = lambda y: y if y%2==0 or (y-1)/2 >= N else 2*(int((y-1)/2)*pow(x,k) % N) + 1 return make_permutation_matrix(2*(2**n), permutation ) def mult_op(x,k,N): return Operator(mult_mat(x,k,N)) #controlled-U oracle def c_mult_op(x,k,N): return Operator(c_mult_mat(x,k,N)) # QFT and IQFT def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): circ.h(q[j]) for k in range(j+1,n): circ.cu1(math.pi/float(2**(k-j)), q[k], q[j]) for i in range(n//2): circ.swap(q[i], q[n-i-1]) def iqft(circ,q,n): for j in range(n): circ.h(q[j]) for k in range(j+1,n): #circ.cu1(-math.pi/float(2**(k-j)), q[k], q[j]) gate = CU1Gate(-np.pi/float(2**(k-j)) ) circ.append(gate, [q[k],q[j]]) for i in range(n//2): circ.swap(q[i], q[n-i-1]) # Constants N = 15 x = 7 # Quantum registers n_control = math.ceil(math.log(N, 2)) * 2 # Number of qubits in the control register control_qubits = QuantumRegister(n_control) target_qubits = QuantumRegister(math.ceil(math.log(N, 2)) + 1) # Extra qubit for modulo multiplication classical_bits = ClassicalRegister(n_control) # Quantum circuit circuit = QuantumCircuit(control_qubits, target_qubits, classical_bits) # Initialize control qubits in superposition circuit.h(control_qubits) # Apply controlled unitary operations for qubit in range(n_control): k = 2 ** qubit circuit.append(c_mult_op(x, k, N), [control_qubits[qubit]] + target_qubits[:]) # Apply inverse QFT iqft(circuit, control_qubits, n_control) # Measure control qubits circuit.measure(control_qubits, classical_bits) # Simulate the circuit simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, simulator, shots=1024).result() counts = result.get_counts(circuit) # Display the histogram plot_histogram(counts) # Determine the order r def determine_order(counts): # Find the output with the highest probability most_common_outcome = max(counts, key=counts.get) phase = int(most_common_outcome, 2) / (2**n_control) frac = Fraction(phase).limit_denominator(N) return frac.denominator r = determine_order(counts) print(f"Order r: {r}") # Post-processing: Find factors of N factor_found = False if r % 2 == 0: plus = math.gcd(int(pow(x, r//2) + 1), N) minus = math.gcd(int(pow(x, r//2) - 1), N) if plus != 1 and plus != N: print(f"One factor of {N} is {plus}") factor_found = True if minus != 1 and minus != N: print(f"One factor of {N} is {minus}") factor_found = True if not factor_found: print("No factors found. Try a different random x.")
https://github.com/lynnlangit/learning-quantum
lynnlangit
#!/usr/bin/env python # coding: utf-8 # # Solving linear systems of equations using HHL and its Qiskit implementation # In this tutorial, we introduce the HHL algorithm, derive the circuit, and implement it using Qiskit. We show how to run the HHL on a simulator and on a five qubit device. # ## Contents # 1. [Introduction](#introduction) # 2. [The HHL algorithm](#hhlalg) # 1. [Some mathematical background](#mathbackground) # 2. [Description of the HHL](#hhldescription) # 3. [Quantum Phase Estimation (QPE) within HHL](#qpe) # 4. [Non-exact QPE](#qpe2) # 3. [Example 1: 4-qubit HHL](#example1) # 4. [Qiskit Implementation](#implementation) # 1. [Running HHL on a simulator: general method](#implementationsim) # 2. [Running HHL on a real quantum device: optimised example](#implementationdev) # 5. [Problems](#problems) # 6. [References](#references) # ## 1. Introduction <a id='introduction'></a> # # Systems of linear equations arise naturally in many real-life applications in a wide range of areas, such as in the solution of Partial Differential Equations, the calibration of financial models, fluid simulation or numerical field calculation. The problem can be defined as, given a matrix $A\in\mathbb{C}^{N\times N}$ and a vector $\vec{b}\in\mathbb{C}^{N}$, find $\vec{x}\in\mathbb{C}^{N}$ satisfying $A\vec{x}=\vec{b}$ # # For example, take $N=2$, # # $$A = \begin{pmatrix}1 & -1/3\\-1/3 & 1 \end{pmatrix},\quad \vec{x}=\begin{pmatrix} x_{1}\\ x_{2}\end{pmatrix}\quad \text{and} \quad \vec{b}=\begin{pmatrix}1 \\ 0\end{pmatrix}$$ # # Then the problem can also be written as find $x_{1}, x_{2}\in\mathbb{C}$ such that # $$\begin{cases}x_{1} - \frac{x_{2}}{3} = 1 \\ -\frac{x_{1}}{3} + x_{2} = 0\end{cases} $$ # # A system of linear equations is called $s$-sparse if $A$ has at most $s$ non-zero entries per row or column. Solving an $s$-sparse system of size $N$ with a classical computer requires $\mathcal{ O }(Ns\kappa\log(1/\epsilon))$ running time using the conjugate gradient method <sup>[1](#conjgrad)</sup>. Here $\kappa$ denotes the condition number of the system and $\epsilon$ the accuracy of the approximation. # # The HHL is a quantum algorithm to estimate a function of the solution with running time complexity of $\mathcal{ O }(\log(N)s^{2}\kappa^{2}/\epsilon)$<sup>[2](#hhl)</sup> when $A$ is a Hermitian matrix under the assumptions of efficient oracles for loading the data, Hamiltonian simulation and computing a function of the solution. This is an exponential speed up in the size of the system, however one crucial remark to keep in mind is that the classical algorithm returns the full solution, while the HHL can only approximate functions of the solution vector. # ## 2. The HHL algorithm<a id='hhlalg'></a> # # ### A. Some mathematical background<a id='mathbackground'></a> # The first step towards solving a system of linear equations with a quantum computer is to encode the problem in the quantum language. By rescaling the system, we can assume $\vec{b}$ and $\vec{x}$ to be normalised and map them to the respective quantum states $|b\rangle$ and $|x\rangle$. Usually the mapping used is such that $i^{th}$ component of $\vec{b}$ (resp. $\vec{x}$) corresponds to the amplitude of the $i^{th}$ basis state of the quantum state $|b\rangle$ (resp. $|x\rangle$). From now on, we will focus on the rescaled problem # # $$ A|x\rangle=|b\rangle$$ # # Since $A$ is Hermitian, it has a spectral decomposition # $$ # A=\sum_{j=0}^{N-1}\lambda_{j}|u_{j}\rangle\langle u_{j}|,\quad \lambda_{j}\in\mathbb{ R } # $$ # where $|u_{j}\rangle$ is the $j^{th}$ eigenvector of $A$ with respective eigenvalue $\lambda_{j}$. Then, # $$ # A^{-1}=\sum_{j=0}^{N-1}\lambda_{j}^{-1}|u_{j}\rangle\langle u_{j}| # $$ # and the right hand side of the system can be written in the eigenbasis of $A$ as # $$ # |b\rangle=\sum_{j=0}^{N-1}b_{j}|u_{j}\rangle,\quad b_{j}\in\mathbb{ C } # $$ # It is useful to keep in mind that the goal of the HHL is to exit the algorithm with the readout register in the state # $$ # |x\rangle=A^{-1}|b\rangle=\sum_{j=0}^{N-1}\lambda_{j}^{-1}b_{j}|u_{j}\rangle # $$ # Note that here we already have an implicit normalisation constant since we are talking about a quantum state. # ### B. Description of the HHL algorithm <a id='hhldescription'></a> # # The algorithm uses three quantum registers, all of them set to $|0\rangle $ at the beginning of the algorithm. One register, which we will denote with the subindex $n_{l}$, is used to store a binary representation of the eigenvalues of $A$. A second register, denoted by $n_{b}$, contains the vector solution, and from now on $N=2^{n_{b}}$. There is an extra register, for the auxiliary qubits. These are qubits used as intermediate steps in the individual computations but will be ignored in the following description since they are set to $|0\rangle $ at the beginning of each computation and restored back to the $|0\rangle $ state at the end of the individual operation. # # The following is an outline of the HHL algorithm with a high-level drawing of the corresponding circuit. For simplicity all computations are assumed to be exact in the ensuing description, and a more detailed explanation of the non-exact case is given in Section [2.D.](#qpe2). # # <img src="images/hhlcircuit.png" width = "75%" height = "75%"> # # 1. Load the data $|b\rangle\in\mathbb{ C }^{N}$. That is, perform the transformation # $$ |0\rangle _{n_{b}} \mapsto |b\rangle _{n_{b}} $$ # 2. Apply Quantum Phase Estimation (QPE) with # $$ # U = e ^ { i A t } := \sum _{j=0}^{N-1}e ^ { i \lambda _ { j } t } |u_{j}\rangle\langle u_{j}| # $$ # The quantum state of the register expressed in the eigenbasis of $A$ is now # $$ # \sum_{j=0}^{N-1} b _ { j } |\lambda _ {j }\rangle_{n_{l}} |u_{j}\rangle_{n_{b}} # $$ # where $|\lambda _ {j }\rangle_{n_{l}}$ is the $n_{l}$-bit binary representation of $\lambda _ {j }$. # # 3. Add an auxiliary qubit and apply a rotation conditioned on $|\lambda_{ j }\rangle$, # $$ # \sum_{j=0}^{N-1} b _ { j } |\lambda _ { j }\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} \left( \sqrt { 1 - \frac { C^{2} } { \lambda _ { j } ^ { 2 } } } |0\rangle + \frac { C } { \lambda _ { j } } |1\rangle \right) # $$ # where $C$ is a normalisation constant, and, as expressed in the current form above, should be less than the smallest eigenvalue $\lambda_{min}$ in magnitude, i.e., $|C| < \lambda_{min}$. # # 4. Apply QPE$^{\dagger}$. Ignoring possible errors from QPE, this results in # $$ # \sum_{j=0}^{N-1} b _ { j } |0\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} \left( \sqrt { 1 - \frac {C^{2} } { \lambda _ { j } ^ { 2 } } } |0\rangle + \frac { C } { \lambda _ { j } } |1\rangle \right) # $$ # # 5. Measure the auxiliary qubit in the computational basis. If the outcome is $1$, the register is in the post-measurement state # $$ # \left( \sqrt { \frac { 1 } { \sum_{j=0}^{N-1} \left| b _ { j } \right| ^ { 2 } / \left| \lambda _ { j } \right| ^ { 2 } } } \right) \sum _{j=0}^{N-1} \frac{b _ { j }}{\lambda _ { j }} |0\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} # $$ # which up to a normalisation factor corresponds to the solution. # # 6. Apply an observable $M$ to calculate $F(x):=\langle x|M|x\rangle$. # ### C. Quantum Phase Estimation (QPE) within HHL <a id='qpe'></a> # # Quantum Phase Estimation is described in more detail in Chapter 3. However, since this quantum procedure is at the core of the HHL algorithm, we recall here the definition. Roughly speaking, it is a quantum algorithm which, given a unitary $U$ with eigenvector $|\psi\rangle_{m}$ and eigenvalue $e^{2\pi i\theta}$, finds $\theta$. We can formally define this as follows. # # **Definition:** Let $U\in\mathbb{ C }^{2^{m}\times 2^{m}}$ be unitary and let $|\psi\rangle_{m}\in\mathbb{ C }^{2^{m}}$ be one of its eigenvectors with respective eigenvalue $e^{2\pi i\theta}$. The **Quantum Phase Estimation** algorithm, abbreviated **QPE**, takes as inputs the unitary gate for $U$ and the state $|0\rangle_{n}|\psi\rangle_{m}$ and returns the state $|\tilde{\theta}\rangle_{n}|\psi\rangle_{m}$. Here $\tilde{\theta}$ denotes a binary approximation to $2^{n}\theta$ and the $n$ subscript denotes it has been truncated to $n$ digits. # $$ # \operatorname { QPE } ( U , |0\rangle_{n}|\psi\rangle_{m} ) = |\tilde{\theta}\rangle_{n}|\psi\rangle_{m} # $$ # # For the HHL we will use QPE with $U = e ^ { i A t }$, where $A$ is the matrix associated to the system we want to solve. In this case, # $$ # e ^ { i A t } = \sum_{j=0}^{N-1}e^{i\lambda_{j}t}|u_{j}\rangle\langle u_{j}| # $$ # Then, for the eigenvector $|u_{j}\rangle_{n_{b}}$, which has eigenvalue $e ^ { i \lambda _ { j } t }$, QPE will output $|\tilde{\lambda }_ { j }\rangle_{n_{l}}|u_{j}\rangle_{n_{b}}$. Where $\tilde{\lambda }_ { j }$ represents an $n_{l}$-bit binary approximation to $2^{n_l}\frac{\lambda_ { j }t}{2\pi}$. Therefore, if each $\lambda_{j}$ can be exactly represented with $n_{l}$ bits, # $$ # \operatorname { QPE } ( e ^ { i A t } , \sum_{j=0}^{N-1}b_{j}|0\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} ) = \sum_{j=0}^{N-1}b_{j}|\lambda_{j}\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} # $$ # ### D. Non-exact QPE <a id='qpe2'></a> # # In reality, the quantum state of the register after applying QPE to the initial state is # $$ # \sum _ { j=0 }^{N-1} b _ { j } \left( \sum _ { l = 0 } ^ { 2 ^ { n_{l} } - 1 } \alpha _ { l | j } |l\rangle_{n_{l}} \right)|u_{j}\rangle_{n_{b}} # $$ # where # $$ # \alpha _ { l | j } = \frac { 1 } { 2 ^ { n_{l} } } \sum _ { k = 0 } ^ { 2^{n_{l}}- 1 } \left( e ^ { 2 \pi i \left( \frac { \lambda _ { j } t } { 2 \pi } - \frac { l } { 2 ^ { n_{l} } } \right) } \right) ^ { k } # $$ # # Denote by $\tilde{\lambda_{j}}$ the best $n_{l}$-bit approximation to $\lambda_{j}$, $1\leq j\leq N$. Then we can relabel the $n_{l}$-register so that $\alpha _ { l | j }$ denotes the amplitude of $|l + \tilde { \lambda } _ { j } \rangle_{n_{l}}$. So now, # $$ # \alpha _ { l | j } : = \frac { 1 } { 2 ^ { n_{l}} } \sum _ { k = 0 } ^ { 2 ^ { n_{l} } - 1 } \left( e ^ { 2 \pi i \left( \frac { \lambda _ { j } t } { 2 \pi } - \frac { l + \tilde { \lambda } _ { j } } { 2 ^ { n_{l} } } \right) } \right) ^ { k } # $$ # If each $\frac { \lambda _ { j } t } { 2 \pi }$ can be represented exactly with $n_{l}$ binary bits, then $\frac { \lambda _ { j } t } { 2 \pi }=\frac { \tilde { \lambda } _ { j } } { 2 ^ { n_{l} } }$ $\forall j$. Therefore in this case $\forall j$, $1\leq j \leq N$, it holds that $\alpha _ { 0 | j } = 1$ and $\alpha _ { l | j } = 0 \quad \forall l \neq 0$. Only in this case we can write that the state of the register after QPE is # $$ # \sum_{j=0}^{N-1} b _ { j } |\lambda _ {j }\rangle_{n_{l}} |u_{j}\rangle_{n_{b}} # $$ # Otherwise, $|\alpha _ { l | j }|$ is large if and only if $\frac { \lambda _ { j } t } { 2 \pi } \approx \frac { l + \tilde { \lambda } _ { j } } { 2 ^ { n_{l} } }$ and the state of the register is # $$ # \sum _ { j=0 }^{N-1} \sum _ { l = 0 } ^ { 2 ^ { n_{l} } - 1 } \alpha _ { l | j } b _ { j }|l\rangle_{n_{l}} |u_{j}\rangle_{n_{b}} # $$ # ## 3. Example: 4-qubit HHL<a id='example1'></a> # # Let's take the small example from the introduction to illustrate the algorithm. That is, # $$A = \begin{pmatrix}1 & -1/3\\-1/3 & 1 \end{pmatrix}\quad \text{and} \quad |b\rangle=\begin{pmatrix}1 \\ 0\end{pmatrix}$$ # # We will use $n_{b}=1$ qubit to represent $|b\rangle$, and later the solution $|x\rangle$, $n_{l}=2$ qubits to store the binary representation of the eigenvalues and $1$ auxiliary qubit to store whether the conditioned rotation, hence the algorithm, was successful. # # For the purpose of illustrating the algorithm, we will cheat a bit and calculate the eigenvalues of $A$ to be able to choose $t$ to obtain an exact binary representation of the rescaled eigenvalues in the $n_{l}$-register. However, keep in mind that for the HHL algorithm implementation one does not need previous knowledge of the eigenvalues. Having said that, a short calculation will give # $$\lambda_{1} = 2/3\quad\text{and}\quad\lambda_{2}=4/3$$ # # Recall from the previous section that the QPE will output an $n_{l}$-bit ($2$-bit in this case) binary approximation to $\frac{\lambda_ { j }t}{2\pi}$. Therefore, if we set # $$t=2\pi\cdot \frac{3}{8}$$ # the QPE will give a $2$-bit binary approximation to # $$\frac{\lambda_ { 1 }t}{2\pi} = 1/4\quad\text{and}\quad\frac{\lambda_ { 2 }t}{2\pi}=1/2$$ # which is, respectively, # $$|01\rangle_{n_{l}}\quad\text{and}\quad|10\rangle_{n_{l}}$$ # # The eigenvectors are, respectively, # $$|u_{1}\rangle=\begin{pmatrix}1 \\ -1\end{pmatrix}\quad\text{and}\quad|u_{2}\rangle=\begin{pmatrix}1 \\ 1\end{pmatrix}$$ # Again, keep in mind that one does not need to compute the eigenvectors for the HHL implementation. In fact, a general Hermitian matrix $A$ of dimension $N$ can have up to $N$ different eigenvalues, therefore calculating them would take $\mathcal{O}(N)$ time and the quantum advantage would be lost. # # We can then write $|b\rangle$ in the eigenbasis of $A$ as # $$|b\rangle _{n_{b}}=\sum_{j=1}^{2}\frac{1}{\sqrt{2}}|u_{j}\rangle _{n_{b}}$$ # # Now we are ready to go through the different steps of the HHL algorithm. # # 1. State preparation in this example is trivial since $|b\rangle=|0\rangle$. # 2. Applying QPE will yield # $$ # \frac{1}{\sqrt{2}}|01\rangle|u_{1}\rangle + \frac{1}{\sqrt{2}}|10\rangle|u_{2}\rangle # $$ # 3. Conditioned rotation with $C=1/8$ that is less than the smallest (rescaled) eigenvalue of $\frac {1} {4}$. Note, the contant $C$ here needs to be chosen such that it is less than the smallest (rescaled) eigenvalue of $\frac {1} {4}$ but as large as possible so that when the auxiliary qubit is measured, the probabilit of it being in the state $|1>$ is large. # $$\frac{1}{\sqrt{2}}|01\rangle|u_{1}\rangle\left( \sqrt { 1 - \frac { (1/8)^{2} } {(1/4)^{2} } } |0\rangle + \frac { 1/8 } { 1/4 } |1\rangle \right) + \frac{1}{\sqrt{2}}|10\rangle|u_{2}\rangle\left( \sqrt { 1 - \frac { (1/8)^{2} } {(1/2)^{2} } } |0\rangle + \frac { 1/8 } { 1/2 } |1\rangle \right) # $$ # $$ # =\frac{1}{\sqrt{2}}|01\rangle|u_{1}\rangle\left( \sqrt { 1 - \frac { 1 } {4 } } |0\rangle + \frac { 1 } { 2 } |1\rangle \right) + \frac{1}{\sqrt{2}}|10\rangle|u_{2}\rangle\left( \sqrt { 1 - \frac { 1 } {16 } } |0\rangle + \frac { 1 } { 4 } |1\rangle \right) # $$ # 4. After applying QPE$^{\dagger}$ the quantum computer is in the state # $$ # \frac{1}{\sqrt{2}}|00\rangle|u_{1}\rangle\left( \sqrt { 1 - \frac { 1 } {4 } } |0\rangle + \frac { 1 } { 2 } |1\rangle \right) + \frac{1}{\sqrt{2}}|00\rangle|u_{2}\rangle\left( \sqrt { 1 - \frac { 1 } {16 } } |0\rangle + \frac { 1 } { 4 } |1\rangle \right) # $$ # 5. On outcome $1$ when measuring the auxiliary qubit, the state is # $$ # \frac{\frac{1}{\sqrt{2}}|00\rangle|u_{1}\rangle\frac { 1 } { 2 } |1\rangle + \frac{1}{\sqrt{2}}|00\rangle|u_{2}\rangle\frac { 1 } { 4 } |1\rangle}{\sqrt{5/32}} # $$ # A quick calculation shows that # $$ # \frac{\frac{1}{2\sqrt{2}}|u_{1}\rangle+ \frac{1}{4\sqrt{2}}|u_{2}\rangle}{\sqrt{5/32}} = \frac{|x\rangle}{||x||} # $$ # 6. Without using extra gates, we can compute the norm of $|x\rangle$: it is the probability of measuring $1$ in the auxiliary qubit from the previous step. # $$ # P(|1\rangle) = \left(\frac{1}{2\sqrt{2}}\right)^{2} + \left(\frac{1}{4\sqrt{2}}\right)^{2} = \frac{5}{32} = ||x||^{2} # $$ # # # ## 4. Qiskit Implementation<a id='implementation'></a> # Now that we have analytically solved the problem from the example we are going to use it to illustrate how to run the HHL on a quantum simulator and on the real hardware. For the quantum simulator, Qiskit already provides an implementation of the HHL algorithm requiring only the matrix $A$ and $|b\rangle$ as inputs in the simplest example. Although we can give the algorithm a general Hermitian matrix and an arbitrary initial state as NumPy arrays, in these cases the quantum algorithm will not achieve an exponential speedup. This is because the default implementation is exact and therefore exponential in the number of qubits (there is no algorithm that can prepare exactly an arbitrary quantum state using polynomial resources in the number of qubits or that can perform exactly the operation $e^{iAt}$ for some general Hermitian matrix $A$ using polynomial resources in the number of qubits). If we know an efficient implementation for a particular problem, the matrix and/or the vector can be given as `QuantumCircuit` objects. Alternatively, there's already an efficient implementation for tridiagonal Toeplitz matrices and in the future there might be more. # # However,at the time of writing the existing quantum computers are noisy and can only run small circuits. Therefore, in Section [4.B.](#implementationdev) we will see an optimised circuit that can be used for a class of problems to which our example belongs and mention the existing procedures to deal with noise in quantum computers. # ## A. Running HHL on a simulator: general method<a id='implementationsim'></a> # The interface for all algorithms to solve the linear system problem is `LinearSolver`. The problem to be solved is only specified when the `solve()` method is called: # ```python # LinearSolver(...).solve(matrix, vector) # ``` # # The simplest implementation takes the matrix and the vector as NumPy arrays. Below we also create a `NumPyLinearSolver` (the classical algorithm) to validate our solutions. # In[1]: ###### see this link to setup Qiskit --> https://qiskit.org/textbook/ch-prerequisites/setting-the-environment.html ##### import numpy as np from qiskit.algorithms.linear_solvers.numpy_linear_solver import NumPyLinearSolver from qiskit.algorithms.linear_solvers.hhl import HHL matrix = np.array([[1, -1/3], [-1/3, 1]]) vector = np.array([1, 0]) naive_hhl_solution = HHL().solve(matrix, vector) # For the classical solver we need to rescale the right hand side (i.e. `vector / np.linalg.norm(vector)`) to take into account the renormalisation that occurs once `vector` is encoded in a quantum state within HHL. # In[2]: classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) # The `linear_solvers` package contains a folder called `matrices` intended to be a placeholder for efficient implementations of particular types of matrices. At the time of writing the only truly efficient implementation it contains (i.e. complexity scaling polynomially in the number of qubits) is the `TridiagonalToeplitz` class. Tridiagonal Toeplitz symmetric real matrices are of the following form # $$A = \begin{pmatrix}a & b & 0 & 0\\b & a & b & 0 \\ 0 & b & a & b \\ 0 & 0 & b & a \end{pmatrix}, a,b\in\mathbb{R}$$ # (note that in this setting we do not consider non symmetric matrices since the HHL algorithm assumes that the input matrix is Hermitian). # # Since the matrix $A$ from our example is of this form we can create an instance of `TridiagonalToeplitz(num_qubits, a, b)` and compare the results to solving the system with an array as input. # In[3]: from qiskit.algorithms.linear_solvers.matrices.tridiagonal_toeplitz import TridiagonalToeplitz tridi_matrix = TridiagonalToeplitz(1, 1, -1 / 3) tridi_solution = HHL().solve(tridi_matrix, vector) # Recall that the HHL algorithm can find a solution exponentially faster in the size of the system than their classical counterparts (i.e. logarithmic complexity instead of polynomial). However the cost for this exponential speedup is that we do not obtain the full solution vector. # Instead, we obtain a quantum state representing the vector $x$ and learning all the components of this vector would take a linear time in its dimension, diminishing any speedup obtained by the quantum algorithm. # # Therefore, we can only compute functions from $x$ (the so called observables) to learn information about the solution. # This is reflected in the `LinearSolverResult` object returned by `solve()`, which contains the following properties # - `state`: either the circuit that prepares the solution or the solution as a vector # - `euclidean_norm`: the euclidean norm if the algorithm knows how to calculate it # - `observable`: the (list of) calculated observable(s) # - `circuit_results`: the observable results from the (list of) circuit(s) # # Let's ignore `observable` and `circuit_results` for the time being and check the solutions we obtained before. # # First, `classical_solution` was the result from a classical algorithm, so if we call `.state` it will return an array: # In[4]: print('classical state:', classical_solution.state) # Our other two examples were quantum algorithms, hence we can only access to the quantum state. This is achieved by returning the quantum circuit that prepares the solution state: # In[5]: print('naive state:') print(naive_hhl_solution.state) print('tridiagonal state:') print(tridi_solution.state) # Recall that the Euclidean norm for a vector $\mathbf{x}=(x_1,\dots,x_N)$ is defined as $||\mathbf{x}||=\sqrt{\sum_{i=1}^N x_i^2}$. Therefore, the probability of measuring $1$ in the auxiliary qubit from Step $5$ in Section B is the squared norm of $\mathbf{x}$. This means that the HHL algorithm can always calculate the euclidean norm of the solution and we can compare the accuracy of the results: # In[6]: print('classical Euclidean norm:', classical_solution.euclidean_norm) print('naive Euclidean norm:', naive_hhl_solution.euclidean_norm) print('tridiagonal Euclidean norm:', tridi_solution.euclidean_norm) # Comparing the solution vectors componentwise is more tricky, reflecting again the idea that we cannot obtain the full solution vector from the quantum algorithm. However, for educational purposes we can check that indeed the different solution vectors obtained are a good approximation at the vector component level as well. # # To do so first we need to use `Statevector` from the `quantum_info` package and extract the right vector components, i.e. those corresponding to the ancillary qubit (bottom in the circuits) being $1$ and the work qubits (the two middle in the circuits) being $0$. Thus, we are interested in the states `1000` and `1001`, corresponding to the first and second components of the solution vector respectively. # In[7]: from qiskit.quantum_info import Statevector naive_sv = Statevector(naive_hhl_solution.state).data tridi_sv = Statevector(tridi_solution.state).data # Extract the right vector components. 1000 corresponds to the index 8 and 1001 corresponds to the index 9 naive_full_vector = np.array([naive_sv[8], naive_sv[9]]) tridi_full_vector = np.array([tridi_sv[8], tridi_sv[9]]) print('naive raw solution vector:', naive_full_vector) print('tridi raw solution vector:', tridi_full_vector) # At a first glance it might seem that this is wrong because the components are complex numbers instead of reals. However note that the imaginary part is very small, most likely due to computer accuracy, and can be disregarded in this case. # In[8]: naive_full_vector = np.real(naive_full_vector) tridi_full_vector = np.real(tridi_full_vector) # Next, we will divide the vectors by their respective norms to suppress any constants coming from the different parts of the circuits. The full solution vector can then be recovered by multiplying these normalised vectors by the respective Euclidean norms calculated above: # In[9]: print('full naive solution vector:', naive_hhl_solution.euclidean_norm*naive_full_vector/np.linalg.norm(naive_full_vector)) print('full tridi solution vector:', tridi_solution.euclidean_norm*tridi_full_vector/np.linalg.norm(tridi_full_vector)) print('classical state:', classical_solution.state) # It should not come as a surprise that `naive_hhl_solution` is exact because all the default methods used are exact. However, `tridi_solution` is exact only in the $2\times 2$ system size case. For larger matrices it will be an approximation, as shown in the slightly larger example below. # In[10]: from scipy.sparse import diags num_qubits = 2 matrix_size = 2 ** num_qubits # entries of the tridiagonal Toeplitz symmetric matrix a = 1 b = -1/3 matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray() vector = np.array([1] + [0]*(matrix_size - 1)) # run the algorithms classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) naive_hhl_solution = HHL().solve(matrix, vector) tridi_matrix = TridiagonalToeplitz(num_qubits, a, b) tridi_solution = HHL().solve(tridi_matrix, vector) print('classical euclidean norm:', classical_solution.euclidean_norm) print('naive euclidean norm:', naive_hhl_solution.euclidean_norm) print('tridiagonal euclidean norm:', tridi_solution.euclidean_norm) # We can also compare the difference in resources from the exact method and the efficient implementation. The $2\times 2$ system size is again special in that the exact algorithm requires less resources, but as we increase the system size, we can see that indeed the exact method scales exponentially in the number of qubits while `TridiagonalToeplitz` is polynomial. # In[11]: from qiskit import transpile num_qubits = list(range(1,5)) a = 1 b = -1/3 i=1 # calculate the circuit depths for different number of qubits to compare the use of resources naive_depths = [] tridi_depths = [] for nb in num_qubits: matrix = diags([b, a, b], [-1, 0, 1], shape=(2**nb, 2**nb)).toarray() vector = np.array([1] + [0]*(2**nb -1)) naive_hhl_solution = HHL().solve(matrix, vector) tridi_matrix = TridiagonalToeplitz(nb, a, b) tridi_solution = HHL().solve(tridi_matrix, vector) naive_qc = transpile(naive_hhl_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx']) tridi_qc = transpile(tridi_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx']) naive_depths.append(naive_qc.depth()) tridi_depths.append(tridi_qc.depth()) i +=1 # In[ ]: sizes = [str(2**nb)+"x"+str(2**nb) for nb in num_qubits] columns = ['size of the system', 'quantum_solution depth', 'tridi_solution depth'] data = np.array([sizes, naive_depths, tridi_depths]) row_format ="{:>23}" * (len(columns) + 2) for team, row in zip(columns, data): print(row_format.format(team, *row)) # The reason the implementation still seems to need exponential resources is because the current conditioned rotation implementation (step 3 from Section 2.B) is exact (i.e. needs exponential resources in $n_l$). Instead we can calculate how many more resources the default implementation needs compared to Tridiagonal - since they only differ in how they implement $e^{iAt}$: # In[13]: print('excess:', [naive_depths[i] - tridi_depths[i] for i in range(0, len(naive_depths))]) # In the near future the plan is to integrate `qiskit.circuit.library.arithmetics.PiecewiseChebyshev` to obtain a polynomial implementation of the conditioned rotation as well. # # Now we can return to the topic of observables and find out what the `observable` and `circuit_results` properties contain. # # The way to compute functions of the solution vector $\mathbf{x}$ is through giving the `.solve()` method a `LinearSystemObservable` as input. There are are two types of available `LinearSystemObservable` which can be given as input: # In[12]: from qiskit.algorithms.linear_solvers.observables import AbsoluteAverage, MatrixFunctional # For a vector $\mathbf{x}=(x_1,...,x_N)$, the `AbsoluteAverage` observable computes $|\frac{1}{N}\sum_{i=1}^{N}x_i|$. # In[13]: num_qubits = 1 matrix_size = 2 ** num_qubits # entries of the tridiagonal Toeplitz symmetric matrix a = 1 b = -1/3 matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray() vector = np.array([1] + [0]*(matrix_size - 1)) tridi_matrix = TridiagonalToeplitz(1, a, b) average_solution = HHL().solve(tridi_matrix, vector, AbsoluteAverage()) classical_average = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), AbsoluteAverage()) print('quantum average:', average_solution.observable) print('classical average:', classical_average.observable) print('quantum circuit results:', average_solution.circuit_results) # The `MatrixFunctional` observable computes $\mathbf{x}^T B \mathbf{x}$ for a vector $\mathbf{x}$ and a tridiagonal symmetric Toeplitz matrix $B$. The class takes the main and off diagonal values of the matrix for its constuctor method. # In[14]: observable = MatrixFunctional(1, 1 / 2) functional_solution = HHL().solve(tridi_matrix, vector, observable) classical_functional = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), observable) print('quantum functional:', functional_solution.observable) print('classical functional:', classical_functional.observable) print('quantum circuit results:', functional_solution.circuit_results) # Therefore, `observable` contains the final value of the function on $\mathbf{x}$, while `circuit_results` contains the raw values obtained from the circuit and used to process the result of `observable`. # # This 'how to process the result' is better explained by looking at what arguments `.solve()` takes. The `solve()` method accepts up to five arguments: # ```python # def solve(self, matrix: Union[np.ndarray, QuantumCircuit], # vector: Union[np.ndarray, QuantumCircuit], # observable: Optional[Union[LinearSystemObservable, BaseOperator, # List[BaseOperator]]] = None, # post_rotation: Optional[Union[QuantumCircuit, List[QuantumCircuit]]] = None, # post_processing: Optional[Callable[[Union[float, List[float]]], # Union[float, List[float]]]] = None) \ # -> LinearSolverResult: # ``` # The first two are the matrix defining the linear system and the vector right hand side of the equation, which we have already covered. The remaining parameters concern the (list of) observable(s) to be computed out of the solution vector $x$, and can be specified in two different ways. One option is to give as the third and last parameter a (list of) `LinearSystemObservable`(s). Alternatively, we can give our own implementations of the `observable`, `post_rotation` and `post_processing`, where # - `observable` is the operator to compute the expected value of the observable and can be e.g. a `PauliSumOp` # - `post_rotation` is the circuit to be applied to the solution to extract information if additional gates are needed. # - `post_processing` is the function to compute the value of the observable from the calculated probabilities. # # In other words, there will be as many `circuit_results` as `post_rotation` circuits, and `post_processing` is telling the algorithm how to use the values we see when we print `circuit_results` to obtain the value we see when we print `observable`. # # Finally, the `HHL` class accepts the following parameters in its constructor method: # - error tolerance : the accuracy of the approximation of the solution, the default is `1e-2` # - expectation : how the expectation values are evaluated, the default is `PauliExpectation` # - quantum instance: the `QuantumInstance` or backend, the default is a `Statevector` simulation # In[15]: from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') hhl = HHL(1e-3, quantum_instance=backend) accurate_solution = hhl.solve(matrix, vector) classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) print(accurate_solution.euclidean_norm) print(classical_solution.euclidean_norm) # ## B. Running HHL on a real quantum device: optimised example<a id='implementationdev'></a> # In the previous section we ran the standard algorithm provided in Qiskit and saw that it uses $7$ qubits, has a depth of ~$100$ gates and requires a total of $54$ CNOT gates. These numbers are not feasible for the current available hardware, therefore we need to decrease these quantities. In particular, the goal will be to reduce the number of CNOTs by a factor of $5$ since they have worse fidelity than single-qubit gates. Furthermore, we can reduce the number of qubits to $4$ as was the original statement of the problem: the Qiskit method was written for a general problem and that is why it requires $3$ additional auxiliary qubits. # # However, solely decreasing the number of gates and qubits will not give a good approximation to the solution on real hardware. This is because there are two sources of errors: those that occur during the run of the circuit and readout errors. # # Qiskit provides a module to mitigate the readout errors by individually preparing and measuring all basis states, a detailed treatment on the topic can be found in the paper by Dewes et al.<sup>[3](#readouterr)</sup> To deal with the errors occurring during the run of the circuit, Richardson extrapolation can be used to calculate the error to the zero limit by running the circuit three times, each replacing each CNOT gate by $1$, $3$ and $5$ CNOTs respectively<sup>[4](#richardson)</sup>. The idea is that theoretically the three circuits should produce the same result, but in real hardware adding CNOTs means amplifying the error. Since we know that we have obtained results with an amplified error, and we can estimate by how much the error was amplified in each case, we can recombine the quantities to obtain a new result that is a closer approximation to the analytic solution than any of the previous obtained values. # # Below we give the optimised circuit that can be used for any problem of the form # $$A = \begin{pmatrix}a & b\\b & a \end{pmatrix}\quad \text{and} \quad |b\rangle=\begin{pmatrix}\cos(\theta) \\ \sin(\theta)\end{pmatrix},\quad a,b,\theta\in\mathbb{R}$$ # # The following optimisation was extracted from a work on the HHL for tridiagonal symmetric matrices<sup>[[5]](#tridi)</sup>, this particular circuit was derived with the aid of the UniversalQCompiler software<sup>[[6]](#qcompiler)</sup>. # # In[16]: from qiskit import QuantumRegister, QuantumCircuit import numpy as np t = 2 # This is not optimal; As an exercise, set this to the # value that will get the best results. See section 8 for solution. nqubits = 4 # Total number of qubits nb = 1 # Number of qubits representing the solution nl = 2 # Number of qubits representing the eigenvalues theta = 0 # Angle defining |b> a = 1 # Matrix diagonal b = -1/3 # Matrix off-diagonal # Initialize the quantum and classical registers qr = QuantumRegister(nqubits) # Create a Quantum Circuit qc = QuantumCircuit(qr) qrb = qr[0:nb] qrl = qr[nb:nb+nl] qra = qr[nb+nl:nb+nl+1] # State preparation. qc.ry(2*theta, qrb[0]) # QPE with e^{iAt} for qu in qrl: qc.h(qu) qc.p(a*t, qrl[0]) qc.p(a*t*2, qrl[1]) qc.u(b*t, -np.pi/2, np.pi/2, qrb[0]) # Controlled e^{iAt} on \lambda_{1}: params=b*t qc.p(np.pi/2,qrb[0]) qc.cx(qrl[0],qrb[0]) qc.ry(params,qrb[0]) qc.cx(qrl[0],qrb[0]) qc.ry(-params,qrb[0]) qc.p(3*np.pi/2,qrb[0]) # Controlled e^{2iAt} on \lambda_{2}: params = b*t*2 qc.p(np.pi/2,qrb[0]) qc.cx(qrl[1],qrb[0]) qc.ry(params,qrb[0]) qc.cx(qrl[1],qrb[0]) qc.ry(-params,qrb[0]) qc.p(3*np.pi/2,qrb[0]) # Inverse QFT qc.h(qrl[1]) qc.rz(-np.pi/4,qrl[1]) qc.cx(qrl[0],qrl[1]) qc.rz(np.pi/4,qrl[1]) qc.cx(qrl[0],qrl[1]) qc.rz(-np.pi/4,qrl[0]) qc.h(qrl[0]) # Eigenvalue rotation t1=(-np.pi +np.pi/3 - 2*np.arcsin(1/3))/4 t2=(-np.pi -np.pi/3 + 2*np.arcsin(1/3))/4 t3=(np.pi -np.pi/3 - 2*np.arcsin(1/3))/4 t4=(np.pi +np.pi/3 + 2*np.arcsin(1/3))/4 qc.cx(qrl[1],qra[0]) qc.ry(t1,qra[0]) qc.cx(qrl[0],qra[0]) qc.ry(t2,qra[0]) qc.cx(qrl[1],qra[0]) qc.ry(t3,qra[0]) qc.cx(qrl[0],qra[0]) qc.ry(t4,qra[0]) qc.measure_all() print("Depth: %i" % qc.depth()) print("CNOTS: %i" % qc.count_ops()['cx']) qc.draw(fold=-1) # The code below takes as inputs our circuit, the real hardware backend and the set of qubits we want to use, and returns and instance that can be run on the specified device. Creating the circuits with $3$ and $5$ CNOTs is the same but calling the transpile method with the right quantum circuit. # # Real hardware devices need to be recalibrated regularly, and the fidelity of a specific qubit or gate can change over time. Furthermore, different chips have different connectivities. If we try to run a circuit that performs a two-qubit gate between two qubits that are not connected on the specified device, the transpiler will add SWAP gates. Therefore it is good practice to check with the IBM Quantum Experience webpage<sup>[[7]](#qexperience)</sup> before running the following code and choose a set of qubits with the right connectivity and lowest error rates at the given time. # In[17]: from qiskit import BasicAer, ClassicalRegister, IBMQ from qiskit.compiler import transpile from qiskit.ignis.mitigation.measurement import (complete_meas_cal, # Measurement error mitigation functions CompleteMeasFitter, MeasurementFilter) provider = IBMQ.load_account() backend = provider.get_backend('ibmqx2') # calibrate using real hardware layout = [2,3,0,4] chip_qubits = 5 # Transpiled circuit for the real hardware qc_qa_cx = transpile(qc, backend=backend, initial_layout=layout) # The next step is to create the extra circuits used to mitigate the readout errors<sup>[[3]](#readouterr)</sup>. # In[18]: meas_cals, state_labels = complete_meas_cal(qubit_list=layout, qr=QuantumRegister(chip_qubits)) qcs = meas_cals + [qc_qa_cx] job = backend.run(qcs, shots=10) # The following plot<sup>[[5]](#tridi)</sup>, shows the results from running the circuit above on real hardware for $10$ different initial states. The $x$-axis represents the angle $\theta$ defining the initial state in each case. The results where obtained after mitigating the readout error and then extrapolating the errors arising during the run of the circuit from the results with the circuits with $1$, $3$ and $5$ CNOTs. # # <img src="images/norm_public.png"> # # Compare to the results without error mitigation nor extrapolation from the CNOTs<sup>[5](#tridi)</sup>. # # <img src="images/noerrmit_public.png"> # ## 8. Problems<a id='problems'></a> # ##### Real hardware: # # 1. Set the time parameter for the optimised example. # # <details> # <summary> Solution (Click to expand)</summary> # t = 2.344915690192344 # # The best result is to set it so that the smallest eigenvalue can be represented exactly, since it's inverse will have the largest contribution in the solution # </details> # # 2. Create transpiled circuits for $3$ and $5$ CNOTs from a given circuit 'qc'. When creating the circuits you will have to add barriers so that these consecutive CNOT gates do not get cancelled when using the transpile() method. # 3. Run your circuits on the real hardware and apply a quadratic fit to the results to obtain the extrapolated value. # ## 9. References<a id='references'></a> # 1. J. R. Shewchuk. An Introduction to the Conjugate Gradient Method Without the Agonizing Pain. Technical Report CMU-CS-94-125, School of Computer Science, Carnegie Mellon University, Pittsburgh, Pennsylvania, March 1994.<a id='conjgrad'></a> # 2. A. W. Harrow, A. Hassidim, and S. Lloyd, “Quantum algorithm for linear systems of equations,” Phys. Rev. Lett. 103.15 (2009), p. 150502.<a id='hhl'></a> # 3. A. Dewes, F. R. Ong, V. Schmitt, R. Lauro, N. Boulant, P. Bertet, D. Vion, and D. Esteve, “Characterization of a two-transmon processor with individual single-shot qubit readout,” Phys. Rev. Lett. 108, 057002 (2012). <a id='readouterr'></a> # 4. N. Stamatopoulos, D. J. Egger, Y. Sun, C. Zoufal, R. Iten, N. Shen, and S. Woerner, “Option Pricing using Quantum Computers,” arXiv:1905.02666 . <a id='richardson'></a> # 5. A. Carrera Vazquez, A. Frisch, D. Steenken, H. S. Barowski, R. Hiptmair, and S. Woerner, “Enhancing Quantum Linear System Algorithm by Richardson Extrapolation,” (to be included).<a id='tridi'></a> # 6. R. Iten, O. Reardon-Smith, L. Mondada, E. Redmond, R. Singh Kohli, R. Colbeck, “Introduction to UniversalQCompiler,” arXiv:1904.01072 .<a id='qcompiler'></a> # 7. https://quantum-computing.ibm.com/ .<a id='qexperience'></a> # 8. D. Bucher, J. Mueggenburg, G. Kus, I. Haide, S. Deutschle, H. Barowski, D. Steenken, A. Frisch, "Qiskit Aqua: Solving linear systems of equations with the HHL algorithm" https://github.com/Qiskit/qiskit-tutorials/blob/master/legacy_tutorials/aqua/linear_systems_of_equations.ipynb
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!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/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. """ Chi-matrix representation of a Quantum Channel. """ from __future__ import annotations import copy as _copy import math import numpy as np from qiskit import _numpy_compat from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel from qiskit.quantum_info.operators.channel.choi import Choi from qiskit.quantum_info.operators.channel.superop import SuperOp from qiskit.quantum_info.operators.channel.transformations import _to_chi from qiskit.quantum_info.operators.mixins import generate_apidocs from qiskit.quantum_info.operators.base_operator import BaseOperator class Chi(QuantumChannel): r"""Pauli basis Chi-matrix representation of a quantum channel. The Chi-matrix representation of an :math:`n`-qubit quantum channel :math:`\mathcal{E}` is a matrix :math:`\chi` such that the evolution of a :class:`~qiskit.quantum_info.DensityMatrix` :math:`\rho` is given by .. math:: \mathcal{E}(ρ) = \frac{1}{2^n} \sum_{i, j} \chi_{i,j} P_i ρ P_j where :math:`[P_0, P_1, ..., P_{4^{n}-1}]` is the :math:`n`-qubit Pauli basis in lexicographic order. It is related to the :class:`Choi` representation by a change of basis of the Choi-matrix into the Pauli basis. The :math:`\frac{1}{2^n}` in the definition above is a normalization factor that arises from scaling the Pauli basis to make it orthonormal. See reference [1] for further details. References: 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). `arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_ """ def __init__( self, data: QuantumCircuit | Instruction | BaseOperator | np.ndarray, input_dims: int | tuple | None = None, output_dims: int | tuple | None = None, ): """Initialize a quantum channel Chi-matrix operator. Args: data (QuantumCircuit or Instruction or BaseOperator or matrix): data to initialize superoperator. input_dims (tuple): the input subsystem dimensions. [Default: None] output_dims (tuple): the output subsystem dimensions. [Default: None] Raises: QiskitError: if input data is not an N-qubit channel or cannot be initialized as a Chi-matrix. Additional Information: If the input or output dimensions are None, they will be automatically determined from the input data. The Chi matrix representation is only valid for N-qubit channels. """ # If the input is a raw list or matrix we assume that it is # already a Chi matrix. if isinstance(data, (list, np.ndarray)): # Initialize from raw numpy or list matrix. chi_mat = np.asarray(data, dtype=complex) # Determine input and output dimensions dim_l, dim_r = chi_mat.shape if dim_l != dim_r: raise QiskitError("Invalid Chi-matrix input.") if input_dims: input_dim = np.prod(input_dims) if output_dims: output_dim = np.prod(input_dims) if output_dims is None and input_dims is None: output_dim = int(math.sqrt(dim_l)) input_dim = dim_l // output_dim elif input_dims is None: input_dim = dim_l // output_dim elif output_dims is None: output_dim = dim_l // input_dim # Check dimensions if input_dim * output_dim != dim_l: raise QiskitError("Invalid shape for Chi-matrix input.") else: # Otherwise we initialize by conversion from another Qiskit # object into the QuantumChannel. if isinstance(data, (QuantumCircuit, Instruction)): # If the input is a Terra QuantumCircuit or Instruction we # convert it to a SuperOp data = SuperOp._init_instruction(data) else: # We use the QuantumChannel init transform to initialize # other objects into a QuantumChannel or Operator object. data = self._init_transformer(data) input_dim, output_dim = data.dim # Now that the input is an operator we convert it to a Chi object rep = getattr(data, "_channel_rep", "Operator") chi_mat = _to_chi(rep, data._data, input_dim, output_dim) if input_dims is None: input_dims = data.input_dims() if output_dims is None: output_dims = data.output_dims() # Check input is N-qubit channel num_qubits = int(math.log2(input_dim)) if 2**num_qubits != input_dim or input_dim != output_dim: raise QiskitError("Input is not an n-qubit Chi matrix.") super().__init__(chi_mat, num_qubits=num_qubits) def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): dtype = self.data.dtype return np.array(self.data, dtype=dtype, copy=copy) @property def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._input_dim, self._output_dim, self._input_dim, self._output_dim) def _evolve(self, state, qargs=None): return SuperOp(self)._evolve(state, qargs) # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def conjugate(self): # Since conjugation is basis dependent we transform # to the Choi representation to compute the # conjugate channel return Chi(Choi(self).conjugate()) def transpose(self): return Chi(Choi(self).transpose()) def adjoint(self): return Chi(Choi(self).adjoint()) def compose(self, other: Chi, qargs: list | None = None, front: bool = False) -> Chi: if qargs is None: qargs = getattr(other, "qargs", None) if qargs is not None: return Chi(SuperOp(self).compose(other, qargs=qargs, front=front)) # If no qargs we compose via Choi representation to avoid an additional # representation conversion to SuperOp and then convert back to Chi return Chi(Choi(self).compose(other, front=front)) def tensor(self, other: Chi) -> Chi: if not isinstance(other, Chi): other = Chi(other) return self._tensor(self, other) def expand(self, other: Chi) -> Chi: if not isinstance(other, Chi): other = Chi(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): ret = _copy.copy(a) ret._op_shape = a._op_shape.tensor(b._op_shape) ret._data = np.kron(a._data, b.data) return ret # Update docstrings for API docs generate_apidocs(Chi)
https://github.com/Z-928/Bugs4Q
Z-928
# https://github.com/Qiskit/qiskit-terra/issues/2373 # Importing needed libraries from qiskit import * from qiskit.mapper import Layout import numpy as np import matplotlib as mp import matplotlib.pyplot as plt from scipy.optimize import curve_fit # Enable use of real device IBMQ.load_accounts() backend_exp = IBMQ.get_backend('ibmq_16_melbourne') for u in range(0,1): # It isn't important, it is because I measured all qubit's T1 u_st = str(u) file1 = 'T1__raw_qubit_' + u_st + '.txt' out1 = open( file1, 'w' ) out1.write('# This is the qubit\'s ' + u_st +' T1 raw data \n' ) circuit = [] q = QuantumRegister(2, 'q') #Only changing this and the layout makes it works c1 = ClassicalRegister(1, 'c') qc = QuantumCircuit(q) mz = QuantumCircuit(q,c1) lay = Layout({ (q,0) : 0, (q,1):1 }) # Exciting the qubit qc.x(q[0]) qc.barrier(q) # Measurment on Z-axis mz.measure(q[0],c1[0]) # Waiting time ( 30*0.12 us each iteration) for i in range(50): identity = QuantumCircuit(q,c1) identity.barrier(q) for k in range(i*30): identity.iden(q) identity.barrier(q) circuit.append(qc+identity+mz) # Running the experiment jobZ = execute(circuit, backend_exp, initial_layout=lay, shots=1024) out1.write('# N° id_gates Z-Measure Error \n') Result = jobZ.result() # Taking the results counts = [] for i in range(50): counts.append(Result.get_counts(circuit[i]) ) # Preparing the lists to make fits y = [] x = [] for i in range(50): py = counts[i]['1']/1024 x.append(i*30*0.12) y.append( py ) out1.write(str(i*30) + ' '+ str(py) + '\n') out1.write( '\n') def expo(x, amp, slope, high): y = amp*np.exp(-slope*x)+high return y x = np.array(x) y = np.array(y) err_y = np.array(err_y) params , paramscov = curve_fit(expo, x, y,p0=[1,0.02,0] ) a =np.sqrt(np.diag(paramscov)) out1.write('The raw T1 is ' + str(1/params[1])+ ' +- ' + str(a[1]/params[1]) + '\n') out1.close() plt.figure() plt.plot(x, expo(x, *params), label='Raw fitted function') plt.plot(x , y, 'ro', label= 'data') plt.xlabel( ' Time [us] ') plt.ylabel(' Probability of being in the excited state ') plt.legend() plt.savefig('plot_q_'+ u_st+ '_raw.png')
https://github.com/kerenavnery/qmail
kerenavnery
from qiskit import * from qiskit.quantum_info import Statevector #From Marc import parser #From Luca import socket from SocketChannel2 import SocketChannel class Channel: def __init__(self,slave_offset=0, myport=000, remote_port=000): self._state_vector = None self._arr_qubits = None self._basis_gates = ['u1', 'u2', 'u3', 'cx','x','y','H','z'] self._master = True self._offset = 0 self._slave_offset = slave_offset self.realchannel = SocketChannel(myport, False) TCP_IP = '127.0.0.1' self.realchannel.connect(TCP_IP, remote_port) self._circuit = None def close(self): try: self.realchannel.kill() except: print("Exception: Thread still busy") def send(self,circuit,arr_qubits): self._state_vector = Statevector.from_instruction(circuit) self._arr_qubits = arr_qubits self._circuit = circuit #From Marc ser = parser.QSerializer() ser.add_element('state_vector', self._state_vector)#self) ser.add_element('is_master', self._master)#self) ser.add_element('slave_offset', self._slave_offset)#self) ser.add_element('is_master', self._master)#self) ser.add_element('circuit', self._circuit)#self) str_to_send = ser.encode() #print(str_to_send.type()) #From Luca message = str_to_send channel = self.realchannel #SocketChannel() channel.send(message) channel.close() ## TODO: TCP THINGS return self def receive(self,circuit):#,recieve_channel): ## TODO: remove recieve as an input #TODO: TCP things #recieve_channel = TCP_STUFF #From Luca print('Wait to receive') channel = self.realchannel #SocketChannel(port=5005, listen=True) data = channel.receive() # print("received stuff \o/") #print("received data:", data) channel.close() #From Marc ser2 = parser.QSerializer() ser2.decode(data) #recieve_channel = ser2.get_element('channel_class') self._slave_offset = ser2.get_element('slave_offset') if(ser2.get_element('is_master')): self._master = False self._offset = self._slave_offset recieved_state_vector = ser2.get_element('state_vector') new_circuit = QuantumCircuit(len(recieved_state_vector.dims())) new_circuit.initialize(recieved_state_vector.data, range(len(recieved_state_vector.dims()))) new_circuit = transpile(new_circuit, basis_gates=self._basis_gates) new_circuit = new_circuit + circuit return ser2.get_element('circuit'), self._offset return new_circuit, self._offset
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
abhilash1910
!pip install pennylane # example of training a gan on mnist from numpy import expand_dims from numpy import zeros from numpy import ones from numpy import vstack from numpy.random import randn from numpy.random import randint import tensorflow as tf from keras.datasets.mnist import load_data from keras.optimizers import Adam from keras.models import Sequential from keras.layers import Dense from keras.layers import Reshape from keras.layers import Flatten from keras.layers import Conv2D from keras.layers import Conv2DTranspose from keras.layers import LeakyReLU from keras.layers import Dropout from matplotlib import pyplot import pennylane as qml import numpy as np num_wires=5 dev = qml.device('default.qubit', wires=5) # variables phi = [np.pi] * 12 for i in range(len(phi)): phi[i] = phi[i] / np.random.randint(2, 12) num_epochs = 30 eps = 1 initial_generator_weights = np.array([np.pi] + [0] * 44) + np.random.normal(scale=eps, size=(45,)) initial_discriminator_weights = np.random.normal(scale=eps, size=(35,)) generator_weights = tf.Variable(initial_generator_weights) discriminator_weights = tf.Variable(initial_discriminator_weights) opt = tf.keras.optimizers.Adam(0.4) def real_data(phi, **kwargs): # phi is a list with length 12 qml.Hadamard(wires=0) qml.CNOT(wires=[0,1]) qml.RX(phi[0], wires=0) qml.RY(phi[1], wires=0) qml.RZ(phi[2], wires=0) qml.RX(phi[3], wires=0) qml.RY(phi[4], wires=0) qml.RZ(phi[5], wires=0) qml.CNOT(wires=[0, 1]) qml.RX(phi[6], wires=1) qml.RY(phi[7], wires=1) qml.RZ(phi[8], wires=1) qml.RX(phi[9], wires=1) qml.RY(phi[10], wires=1) qml.RZ(phi[11], wires=1) # the discriminator acts on wires 0, 1, and 4 def discriminator_layer(w, **kwargs): qml.RX(w[0], wires=0) qml.RX(w[1], wires=1) qml.RX(w[2], wires=4) qml.RZ(w[3], wires=0) qml.RZ(w[4], wires=1) qml.RZ(w[5], wires=4) qml.MultiRZ(w[6], wires=[0, 1]) qml.MultiRZ(w[7], wires=[1, 4]) def discriminator(w, **kwargs): qml.Hadamard(wires=0) qml.CNOT(wires=[0,1]) discriminator_layer(w[:8]) discriminator_layer(w[8:16]) discriminator_layer(w[16:32]) qml.RX(w[32], wires=4) qml.RY(w[33], wires=4) qml.RZ(w[34], wires=4) def generator_layer(w): qml.RX(w[0], wires=0) qml.RX(w[1], wires=1) qml.RX(w[2], wires=2) qml.RX(w[3], wires=3) qml.RZ(w[4], wires=0) qml.RZ(w[5], wires=1) qml.RZ(w[6], wires=2) qml.RZ(w[7], wires=3) qml.MultiRZ(w[8], wires=[0, 1]) qml.MultiRZ(w[9], wires=[2, 3]) qml.MultiRZ(w[10], wires=[1, 2]) def generator(w, **kwargs): qml.Hadamard(wires=0) qml.CNOT(wires=[0,1]) generator_layer(w[:11]) generator_layer(w[11:22]) generator_layer(w[22:33]) # includes w[22], doesnt include w[33] qml.RX(w[33], wires=0) qml.RY(w[34], wires=0) qml.RZ(w[35], wires=0) qml.RX(w[36], wires=1) qml.RY(w[37], wires=1) qml.RZ(w[38], wires=1) qml.CNOT(wires=[0, 1]) qml.RX(w[39], wires=0) qml.RY(w[40], wires=0) qml.RZ(w[41], wires=0) qml.RX(w[42], wires=1) qml.RY(w[43], wires=1) qml.RZ(w[44], wires=1) @qml.qnode(dev, interface='tf') def real_discriminator(phi, discriminator_weights): real_data(phi) discriminator(discriminator_weights) return qml.expval(qml.PauliZ(4)) @qml.qnode(dev, interface='tf') def generator_discriminator(generator_weights, discriminator_weights): generator(generator_weights) discriminator(discriminator_weights) return qml.expval(qml.PauliZ(4)) def probability_real_real(discriminator_weights): # probability of guessing real data as real discriminator_output = real_discriminator(phi, discriminator_weights) # the output of the discriminator classifying the data as real probability_real_real = (discriminator_output + 1) / 2 return probability_real_real def probability_fake_real(generator_weights, discriminator_weights): # probability of guessing real fake as real # incorrect classification discriminator_output = generator_discriminator(generator_weights, discriminator_weights) probability_fake_real = (discriminator_output + 1) / 2 return probability_fake_real def discriminator_cost(discriminator_weights): accuracy = probability_real_real(discriminator_weights) - probability_fake_real(generator_weights, discriminator_weights) # accuracy = correct classification - incorrect classification cost = -accuracy return cost def generator_cost(generator_weights): accuracy = probability_fake_real(generator_weights, discriminator_weights) # accuracy = probability that the generator fools the discriminator cost = -accuracy return cost def train_discriminator(): for epoch in range(num_epochs): cost = lambda: discriminator_cost(discriminator_weights) # you need lambda because discriminator weights is a tensorflow object opt.minimize(cost, discriminator_weights) if epoch % 5 == 0: cost_val = discriminator_cost(discriminator_weights).numpy() print('Epoch {}/{}, Cost: {}, Probability class real as real: {}'.format(epoch, num_epochs, cost_val, probability_real_real(discriminator_weights).numpy())) if epoch == num_epochs - 1: print('\n') def train_generator(): for epoch in range(num_epochs): cost = lambda: generator_cost(generator_weights) opt.minimize(cost, generator_weights) if epoch % 5 == 0: cost_val = generator_cost(generator_weights).numpy() print('Epoch {}/{}, Cost: {}, Probability class fake as real: {}'.format(epoch, num_epochs, cost_val, probability_fake_real(generator_weights, discriminator_weights).numpy())) if epoch == num_epochs - 1: print('\n') train_discriminator() train_generator()
https://github.com/Pitt-JonesLab/slam_decomposition
Pitt-JonesLab
%matplotlib widget import logging logger = logging.getLogger() logger.setLevel(logging.INFO) from slam.basis import CircuitTemplate basis = CircuitTemplate() basis.build(3) basis.spanning_range = range(3, 4) basis.circuit.draw() from slam.cost_function import BasicCost, MakhlinFunctionalCost objective1 = BasicCost() objective2 = MakhlinFunctionalCost() from slam.sampler import GateSample from qiskit.circuit.library import SwapGate sampler = GateSample(gate=SwapGate()) from slam.optimizer import TemplateOptimizer # by default use BFGS optimizer1 = TemplateOptimizer( basis=basis, objective=objective1, override_fail=1, use_callback=True ) optimizer2 = TemplateOptimizer( basis=basis, objective=objective2, override_fail=1, use_callback=True ) ## optimizer3 = TemplateOptimizer( basis=basis, objective=objective1, override_fail=1, use_callback=True, override_method="Nelder-Mead", ) optimizer4 = TemplateOptimizer( basis=basis, objective=objective2, override_fail=1, use_callback=True, override_method="Nelder-Mead", ) from slam.utils.visualize import optimizer_training_plot _ret1 = optimizer1.approximate_from_distribution(sampler) optimizer_training_plot(_ret1[0], _ret1[1]); _ret2 = optimizer2.approximate_from_distribution(sampler) optimizer_training_plot(_ret2[0], _ret2[1]) _ret3 = optimizer3.approximate_from_distribution(sampler) optimizer_training_plot(_ret3[0], _ret3[1]); _ret4 = optimizer4.approximate_from_distribution(sampler) optimizer_training_plot(_ret4[0], _ret4[1]);
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import ElectronicStructureMoleculeDriver, ElectronicStructureDriverType molecule = Molecule( # coordinates are given in Angstrom geometry=[ ["O", [0.0, 0.0, 0.0]], ["H", [0.758602, 0.0, 0.504284]], ["H", [0.758602, 0.0, -0.504284]] ], multiplicity=1, # = 2*spin + 1 charge=0, ) driver = ElectronicStructureMoleculeDriver( molecule=molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF, ) properties = driver.run() # WRITE YOUR CODE BETWEEN THESE LINES - START num_alpha_electrons = num_beta_electrons = num_spin_orbitals = nuclear_rep_energy = # WRITE YOUR CODE BETWEEN THESE LINES - END from qc_grader.challenges.spring_2022 import grade_ex4a grade_ex4a( num_alpha_electrons=num_alpha_electrons, num_beta_electrons=num_beta_electrons, num_spin_orbitals=num_spin_orbitals, nuclear_rep_energy=nuclear_rep_energy ) from qiskit_nature.transformers.second_quantization.electronic import ActiveSpaceTransformer # Check the occupation of the spin orbitals PN_property = properties.get_property("ParticleNumber") print(PN_property) # Define the active space around the Fermi level # (selected automatically around the HOMO and LUMO, ordered by energy) transformer = ActiveSpaceTransformer( num_electrons=2, #how many electrons we have in our active space num_molecular_orbitals=2, #how many orbitals we have in our active space ) # We can hand-pick the MOs to be included in the AS # (in case they are not exactly around the Fermi level) # transformer = ActiveSpaceTransformer( # num_electrons=2, #how many electrons we have in our active space # num_molecular_orbitals=2, #how many orbitals we have in our active space # active_orbitals=[4,7], #We are specifically choosing MO number 4 (occupied with two electrons) and 7 (empty) # ) from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem problem = ElectronicStructureProblem(driver, [transformer]) second_q_ops = problem.second_q_ops() # this calls driver.run() internally hamiltonian = second_q_ops[0] print(hamiltonian) from qiskit_nature.operators.second_quantization import FermionicOp # WRITE YOUR CODE BETWEEN THESE LINES - START # list of valid tuples to initialize the FermionicOp list_operator = # positive integer that represents the length of registers num_register_length = # WRITE YOUR CODE BETWEEN THESE LINES - END from qc_grader.challenges.spring_2022 import grade_ex4b grade_ex4b(list_operator, num_register_length) from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter # Setup the mapper and qubit converter mapper_type = 'JordanWignerMapper' if mapper_type == 'ParityMapper': mapper = ParityMapper() elif mapper_type == 'JordanWignerMapper': mapper = JordanWignerMapper() elif mapper_type == 'BravyiKitaevMapper': mapper = BravyiKitaevMapper() converter = QubitConverter(mapper) qubit_op = converter.convert(hamiltonian) print(qubit_op) from qiskit_nature.circuit.library import HartreeFock particle_number = problem.grouped_property_transformed.get_property("ParticleNumber") num_spin_orbitals = particle_number.num_spin_orbitals num_particles = particle_number.num_particles init_state = HartreeFock(num_spin_orbitals, num_particles, converter) print(init_state) from qiskit.circuit.library import TwoLocal from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD # Choose the ansatz ansatz_type = "UCCSD" # Put arguments for twolocal if ansatz_type == "TwoLocal": # Single qubit rotations that are placed on all qubits with independent parameters rotation_blocks = ['ry', 'rz'] # Entangling gates entanglement_blocks = 'cz' # How the qubits are entangled entanglement = 'full' # Repetitions of rotation_blocks + entanglement_blocks with independent parameters repetitions = 1 # Skip the final rotation_blocks layer skip_final_rotation_layer = True ansatz = TwoLocal(qubit_op.num_qubits, rotation_blocks, entanglement_blocks, reps=repetitions, entanglement=entanglement, skip_final_rotation_layer=skip_final_rotation_layer) # Add the initial state ansatz.compose(init_state, front=True, inplace=True) elif ansatz_type == "UCCSD": ansatz = UCCSD(converter,num_particles,num_spin_orbitals,initial_state = init_state) elif ansatz_type == "PUCCD": ansatz = PUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state) elif ansatz_type == "SUCCD": ansatz = SUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state) elif ansatz_type == "Custom": # Example of how to write your own circuit from qiskit.circuit import Parameter, QuantumCircuit, QuantumRegister # Define the variational parameter theta = Parameter('a') n = qubit_op.num_qubits # Make an empty quantum circuit qc = QuantumCircuit(qubit_op.num_qubits) qubit_label = 0 # Place a Hadamard gate qc.h(qubit_label) # Place a CNOT ladder for i in range(n-1): qc.cx(i, i+1) # Visual separator qc.barrier() # rz rotations on all qubits qc.rz(theta, range(n)) ansatz = qc ansatz.compose(init_state, front=True, inplace=True) print(ansatz.decompose()) from qiskit import Aer backend = Aer.get_backend('statevector_simulator') from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP optimizer_type = 'L_BFGS_B' # You may want to tune the parameters # of each optimizer, here the defaults are used if optimizer_type == 'COBYLA': optimizer = COBYLA(maxiter=500) elif optimizer_type == 'L_BFGS_B': optimizer = L_BFGS_B(maxfun=500) elif optimizer_type == 'SPSA': optimizer = SPSA(maxiter=500) elif optimizer_type == 'SLSQP': optimizer = SLSQP(maxiter=500) from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver import numpy as np def exact_diagonalizer(problem, converter): solver = NumPyMinimumEigensolverFactory() calc = GroundStateEigensolver(converter, solver) result = calc.solve(problem) return result result_exact = exact_diagonalizer(problem, converter) exact_energy = np.real(result_exact.eigenenergies[0]) print("Exact electronic energy", exact_energy) print(result_exact) # The targeted electronic energy for H2 is -1.85336 Ha # Check with your VQE result. from qiskit.algorithms import VQE from IPython.display import display, clear_output # Print and save the data in lists def callback(eval_count, parameters, mean, std): # Overwrites the same line when printing display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std)) clear_output(wait=True) counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) counts = [] values = [] params = [] deviation = [] # Set initial parameters of the ansatz # We choose a fixed small displacement # So all participants start from similar starting point try: initial_point = [0.01] * len(ansatz.ordered_parameters) except: initial_point = [0.01] * ansatz.num_parameters algorithm = VQE(ansatz, optimizer=optimizer, quantum_instance=backend, callback=callback, initial_point=initial_point) result = algorithm.compute_minimum_eigenvalue(qubit_op) print(result) # Store results in a dictionary from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller # Unroller transpile your circuit into CNOTs and U gates pass_ = Unroller(['u', 'cx']) pm = PassManager(pass_) ansatz_tp = pm.run(ansatz) cnots = ansatz_tp.count_ops()['cx'] energy = result.optimal_value if ansatz_type == "TwoLocal": result_dict = { 'optimizer': optimizer.__class__.__name__, 'mapping': converter.mapper.__class__.__name__, 'ansatz': ansatz.__class__.__name__, 'rotation blocks': rotation_blocks, 'entanglement_blocks': entanglement_blocks, 'entanglement': entanglement, 'repetitions': repetitions, 'skip_final_rotation_layer': skip_final_rotation_layer, 'energy (Ha)': energy, 'error (mHa)': (energy-exact_energy)*1000, '# of parameters': len(result.optimal_point), 'final parameters': result.optimal_point, '# of evaluations': result.cost_function_evals, '# of qubits': int(qubit_op.num_qubits), '# of CNOTs': cnots} else: result_dict = { 'optimizer': optimizer.__class__.__name__, 'mapping': converter.mapper.__class__.__name__, 'ansatz': ansatz.__class__.__name__, 'rotation blocks': None, 'entanglement_blocks': None, 'entanglement': None, 'repetitions': None, 'skip_final_rotation_layer': None, 'energy (Ha)': energy, 'error (mHa)': (energy-exact_energy)*1000, '# of parameters': len(result.optimal_point), 'final parameters': result.optimal_point, '# of evaluations': result.cost_function_evals, '# of qubits': int(qubit_op.num_qubits), '# of CNOTs': cnots} # Plot the results import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ax.set_xlabel('Iterations') ax.set_ylabel('Energy') ax.grid() fig.text(0.7, 0.75, f'Energy: {result.optimal_value:.3f}') plt.title(f"{result_dict['optimizer']}-{result_dict['mapping']}\n{result_dict['ansatz']}") ax.plot(counts, values) ax.axhline(exact_energy, linestyle='--') fig_title = f"\ {result_dict['optimizer']}-\ {result_dict['mapping']}-\ {result_dict['ansatz']}-\ Energy({result_dict['energy (Ha)']:.3f}).png" fig.savefig(fig_title, dpi=300) # Display and save the data import pandas as pd import os.path filename = 'results_h2o.csv' if os.path.isfile(filename): result_df = pd.read_csv(filename) result_df = result_df.append([result_dict]) else: result_df = pd.DataFrame.from_dict([result_dict]) result_df.to_csv(filename) result_df[['optimizer','ansatz', 'rotation blocks', 'entanglement_blocks', 'entanglement', 'repetitions', '# of qubits', '# of parameters', '# of CNOTs', '# of evaluations', 'error (mHa)']] from qiskit import Aer from qiskit.utils import QuantumInstance from qiskit_nature.algorithms import GroundStateEigensolver, QEOM, VQEUCCFactory # This first part sets the ground state solver # see more about this part in the ground state calculation tutorial quantum_instance = QuantumInstance(Aer.get_backend("aer_simulator_statevector")) solver = VQEUCCFactory(quantum_instance) gsc = GroundStateEigensolver(converter, solver) # The qEOM algorithm is simply instantiated with the chosen ground state solver qeom_excited_states_calculation = QEOM(gsc, "sd") qeom_results = qeom_excited_states_calculation.solve(problem) print(qeom_results) # WRITE YOUR CODE BETWEEN THESE LINES - START # WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.circuit.library import UCCSD ansatz = UCCSD() ansatz.num_spin_orbitals = 10 from qiskit_nature.second_q.circuit.library import UCCSD ansatz = UCCSD() ansatz.num_spatial_orbitals = 5 from qiskit_nature.circuit.library import UCC, UVCC ucc = UCC(qubit_converter=None, num_particles=None, num_spin_orbitals=None, excitations=None) uvcc = UVCC(qubit_converter=None, num_modals=None, excitations=None) from qiskit_nature.second_q.circuit.library import UCC, UVCC ucc = UCC(num_spatial_orbitals=None, num_particles=None, excitations=None, qubit_converter=None) uvcc = UVCC(num_modals=None, excitations=None, qubit_converter=None) from qiskit_nature.circuit.library import HartreeFock, VSCF from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import DirectMapper, JordanWignerMapper hf = HartreeFock( num_spin_orbitals=4, num_particles=(1, 1), qubit_converter=QubitConverter(JordanWignerMapper()) ) vscf = VSCF(num_modals=[2, 2]) from qiskit_nature.second_q.circuit.library import HartreeFock, VSCF from qiskit_nature.second_q.mappers import DirectMapper, JordanWignerMapper, QubitConverter hf = HartreeFock() hf.num_spatial_orbitals = 2 hf.num_particles = (1, 1) hf.qubit_converter = QubitConverter(JordanWignerMapper()) vscf = VSCF() vscf.num_modals = [2, 2] from qiskit.providers.basicaer import BasicAer from qiskit.utils import QuantumInstance from qiskit_nature.algorithms.ground_state_solvers import VQEUCCFactory quantum_instance = QuantumInstance(BasicAer.get_backend("statevector_simulator")) vqe_factory = VQEUCCFactory(quantum_instance=quantum_instance) from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import UCCSD from qiskit_nature.second_q.algorithms.ground_state_solvers import VQEUCCFactory estimator = Estimator() ansatz = UCCSD() optimizer = SLSQP() vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer) from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver, VQEUCCFactory from qiskit_nature.algorithms.excited_states_solvers import QEOM from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper vqe_factory = VQEUCCFactory() converter = QubitConverter(JordanWignerMapper()) ground_state_solver = GroundStateEigensolver(converter, vqe_factory) qeom = QEOM(ground_state_solver) from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import UCCSD from qiskit_nature.second_q.algorithms.ground_state_solvers import ( GroundStateEigensolver, VQEUCCFactory, ) from qiskit_nature.second_q.algorithms.excited_states_solvers import QEOM from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter estimator = Estimator() ansatz = UCCSD() optimizer = SLSQP() vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer) converter = QubitConverter(JordanWignerMapper()) ground_state_solver = GroundStateEigensolver(converter, vqe_factory) qeom = QEOM(ground_state_solver, estimator) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for Statevector quantum state class.""" import unittest import logging from itertools import permutations from ddt import ddt, data import numpy as np from numpy.testing import assert_allclose from qiskit.test import QiskitTestCase from qiskit import QiskitError from qiskit import QuantumRegister, QuantumCircuit from qiskit import transpile from qiskit.circuit.library import HGate, QFT, GlobalPhaseGate from qiskit.providers.basicaer import QasmSimulatorPy from qiskit.utils import optionals from qiskit.quantum_info.random import random_unitary, random_statevector, random_pauli from qiskit.quantum_info.states import Statevector from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.visualization.state_visualization import numbers_to_latex_terms, state_to_latex logger = logging.getLogger(__name__) @ddt class TestStatevector(QiskitTestCase): """Tests for Statevector class.""" @classmethod def rand_vec(cls, n, normalize=False): """Return complex vector or statevector""" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("rand_vec default_rng seeded with seed=%s", seed) rng = np.random.default_rng(seed) vec = rng.random(n) + 1j * rng.random(n) if normalize: vec /= np.sqrt(np.dot(vec, np.conj(vec))) return vec def test_init_array_qubit(self): """Test subsystem initialization from N-qubit array.""" # Test automatic inference of qubit subsystems vec = self.rand_vec(8) for dims in [None, 8]: state = Statevector(vec, dims=dims) assert_allclose(state.data, vec) self.assertEqual(state.dim, 8) self.assertEqual(state.dims(), (2, 2, 2)) self.assertEqual(state.num_qubits, 3) def test_init_array(self): """Test initialization from array.""" vec = self.rand_vec(3) state = Statevector(vec) assert_allclose(state.data, vec) self.assertEqual(state.dim, 3) self.assertEqual(state.dims(), (3,)) self.assertIsNone(state.num_qubits) vec = self.rand_vec(2 * 3 * 4) state = Statevector(vec, dims=[2, 3, 4]) assert_allclose(state.data, vec) self.assertEqual(state.dim, 2 * 3 * 4) self.assertEqual(state.dims(), (2, 3, 4)) self.assertIsNone(state.num_qubits) def test_init_circuit(self): """Test initialization from circuit.""" circuit = QuantumCircuit(3) circuit.x(0) state = Statevector(circuit) self.assertEqual(state.dim, 8) self.assertEqual(state.dims(), (2, 2, 2)) self.assertTrue(all(state.data == np.array([0, 1, 0, 0, 0, 0, 0, 0], dtype=complex))) self.assertEqual(state.num_qubits, 3) def test_init_array_except(self): """Test initialization exception from array.""" vec = self.rand_vec(4) self.assertRaises(QiskitError, Statevector, vec, dims=[4, 2]) self.assertRaises(QiskitError, Statevector, vec, dims=[2, 4]) self.assertRaises(QiskitError, Statevector, vec, dims=5) def test_init_statevector(self): """Test initialization from Statevector.""" vec1 = Statevector(self.rand_vec(4)) vec2 = Statevector(vec1) self.assertEqual(vec1, vec2) def test_from_circuit(self): """Test initialization from a circuit.""" # random unitaries u0 = random_unitary(2).data u1 = random_unitary(2).data # add to circuit qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.unitary(u0, [qr[0]]) circ.unitary(u1, [qr[1]]) target = Statevector(np.kron(u1, u0).dot([1, 0, 0, 0])) vec = Statevector.from_instruction(circ) self.assertEqual(vec, target) # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) target = Statevector.from_label("000").evolve(Operator(circuit)) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.h(0) circuit.h(1) circuit.cp(lam, 0, 1) target = Statevector.from_label("00").evolve(Operator(circuit)) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circ.x(0) circuit.ch(0, 1) target = Statevector.from_label("00").evolve(Operator(circuit)) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test custom controlled gate qc = QuantumCircuit(2) qc.x(0) qc.h(1) gate = qc.to_gate() gate_ctrl = gate.control() circuit = QuantumCircuit(3) circuit.x(0) circuit.append(gate_ctrl, range(3)) target = Statevector.from_label("000").evolve(Operator(circuit)) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test initialize instruction target = Statevector([1, 0, 0, 1j]) / np.sqrt(2) circuit = QuantumCircuit(2) circuit.initialize(target.data, [0, 1]) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) target = Statevector([1, 0, 1, 0]) / np.sqrt(2) circuit = QuantumCircuit(2) circuit.initialize("+", [1]) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) target = Statevector([1, 0, 0, 0]) circuit = QuantumCircuit(2) circuit.initialize(0, [0, 1]) # initialize from int psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test reset instruction target = Statevector([1, 0]) circuit = QuantumCircuit(1) circuit.h(0) circuit.reset(0) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test 0q instruction target = Statevector([1j, 0]) circuit = QuantumCircuit(1) circuit.append(GlobalPhaseGate(np.pi / 2), [], []) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) def test_from_instruction(self): """Test initialization from an instruction.""" target = np.dot(HGate().to_matrix(), [1, 0]) vec = Statevector.from_instruction(HGate()).data global_phase_equivalent = matrix_equal(vec, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_label(self): """Test initialization from a label""" x_p = Statevector(np.array([1, 1]) / np.sqrt(2)) x_m = Statevector(np.array([1, -1]) / np.sqrt(2)) y_p = Statevector(np.array([1, 1j]) / np.sqrt(2)) y_m = Statevector(np.array([1, -1j]) / np.sqrt(2)) z_p = Statevector(np.array([1, 0])) z_m = Statevector(np.array([0, 1])) label = "01" target = z_p.tensor(z_m) self.assertEqual(target, Statevector.from_label(label)) label = "+-" target = x_p.tensor(x_m) self.assertEqual(target, Statevector.from_label(label)) label = "rl" target = y_p.tensor(y_m) self.assertEqual(target, Statevector.from_label(label)) def test_equal(self): """Test __eq__ method""" for _ in range(10): vec = self.rand_vec(4) self.assertEqual(Statevector(vec), Statevector(vec.tolist())) def test_getitem(self): """Test __getitem__ method""" for _ in range(10): vec = self.rand_vec(4) state = Statevector(vec) for i in range(4): self.assertEqual(state[i], vec[i]) self.assertEqual(state[format(i, "b")], vec[i]) def test_getitem_except(self): """Test __getitem__ method raises exceptions.""" for i in range(1, 4): state = Statevector(self.rand_vec(2**i)) self.assertRaises(QiskitError, state.__getitem__, 2**i) self.assertRaises(QiskitError, state.__getitem__, -1) def test_copy(self): """Test Statevector copy method""" for _ in range(5): vec = self.rand_vec(4) orig = Statevector(vec) cpy = orig.copy() cpy._data[0] += 1.0 self.assertFalse(cpy == orig) def test_is_valid(self): """Test is_valid method.""" state = Statevector([1, 1]) self.assertFalse(state.is_valid()) for _ in range(10): state = Statevector(self.rand_vec(4, normalize=True)) self.assertTrue(state.is_valid()) def test_to_operator(self): """Test to_operator method for returning projector.""" for _ in range(10): vec = self.rand_vec(4) target = Operator(np.outer(vec, np.conj(vec))) op = Statevector(vec).to_operator() self.assertEqual(op, target) def test_evolve(self): """Test _evolve method.""" for _ in range(10): op = random_unitary(4) vec = self.rand_vec(4) target = Statevector(np.dot(op.data, vec)) evolved = Statevector(vec).evolve(op) self.assertEqual(target, evolved) def test_evolve_subsystem(self): """Test subsystem _evolve method.""" # Test evolving single-qubit of 3-qubit system for _ in range(5): vec = self.rand_vec(8) state = Statevector(vec) op0 = random_unitary(2) op1 = random_unitary(2) op2 = random_unitary(2) # Test evolve on 1-qubit op = op0 op_full = Operator(np.eye(4)).tensor(op) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[0]), target) # Evolve on qubit 1 op_full = Operator(np.eye(2)).tensor(op).tensor(np.eye(2)) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[1]), target) # Evolve on qubit 2 op_full = op.tensor(np.eye(4)) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[2]), target) # Test evolve on 2-qubits op = op1.tensor(op0) # Evolve on qubits [0, 2] op_full = op1.tensor(np.eye(2)).tensor(op0) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[0, 2]), target) # Evolve on qubits [2, 0] op_full = op0.tensor(np.eye(2)).tensor(op1) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[2, 0]), target) # Test evolve on 3-qubits op = op2.tensor(op1).tensor(op0) # Evolve on qubits [0, 1, 2] op_full = op target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[0, 1, 2]), target) # Evolve on qubits [2, 1, 0] op_full = op0.tensor(op1).tensor(op2) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[2, 1, 0]), target) def test_evolve_qudit_subsystems(self): """Test nested evolve calls on qudit subsystems.""" dims = (3, 4, 5) init = self.rand_vec(np.prod(dims)) ops = [random_unitary((dim,)) for dim in dims] state = Statevector(init, dims) for i, op in enumerate(ops): state = state.evolve(op, [i]) target_op = np.eye(1) for op in ops: target_op = np.kron(op.data, target_op) target = Statevector(np.dot(target_op, init), dims) self.assertEqual(state, target) def test_evolve_global_phase(self): """Test evolve circuit with global phase.""" state_i = Statevector([1, 0]) qr = QuantumRegister(2) phase = np.pi / 4 circ = QuantumCircuit(qr, global_phase=phase) circ.x(0) state_f = state_i.evolve(circ, qargs=[0]) target = Statevector([0, 1]) * np.exp(1j * phase) self.assertEqual(state_f, target) def test_conjugate(self): """Test conjugate method.""" for _ in range(10): vec = self.rand_vec(4) target = Statevector(np.conj(vec)) state = Statevector(vec).conjugate() self.assertEqual(state, target) def test_expand(self): """Test expand method.""" for _ in range(10): vec0 = self.rand_vec(2) vec1 = self.rand_vec(3) target = np.kron(vec1, vec0) state = Statevector(vec0).expand(Statevector(vec1)) self.assertEqual(state.dim, 6) self.assertEqual(state.dims(), (2, 3)) assert_allclose(state.data, target) def test_tensor(self): """Test tensor method.""" for _ in range(10): vec0 = self.rand_vec(2) vec1 = self.rand_vec(3) target = np.kron(vec0, vec1) state = Statevector(vec0).tensor(Statevector(vec1)) self.assertEqual(state.dim, 6) self.assertEqual(state.dims(), (3, 2)) assert_allclose(state.data, target) def test_inner(self): """Test inner method.""" for _ in range(10): vec0 = Statevector(self.rand_vec(4)) vec1 = Statevector(self.rand_vec(4)) target = np.vdot(vec0.data, vec1.data) result = vec0.inner(vec1) self.assertAlmostEqual(result, target) vec0 = Statevector(self.rand_vec(6), dims=(2, 3)) vec1 = Statevector(self.rand_vec(6), dims=(2, 3)) target = np.vdot(vec0.data, vec1.data) result = vec0.inner(vec1) self.assertAlmostEqual(result, target) def test_inner_except(self): """Test inner method raises exceptions.""" vec0 = Statevector(self.rand_vec(4)) vec1 = Statevector(self.rand_vec(3)) self.assertRaises(QiskitError, vec0.inner, vec1) vec0 = Statevector(self.rand_vec(6), dims=(2, 3)) vec1 = Statevector(self.rand_vec(6), dims=(3, 2)) self.assertRaises(QiskitError, vec0.inner, vec1) def test_add(self): """Test add method.""" for _ in range(10): vec0 = self.rand_vec(4) vec1 = self.rand_vec(4) state0 = Statevector(vec0) state1 = Statevector(vec1) self.assertEqual(state0 + state1, Statevector(vec0 + vec1)) def test_add_except(self): """Test add method raises exceptions.""" state1 = Statevector(self.rand_vec(2)) state2 = Statevector(self.rand_vec(3)) self.assertRaises(QiskitError, state1.__add__, state2) def test_subtract(self): """Test subtract method.""" for _ in range(10): vec0 = self.rand_vec(4) vec1 = self.rand_vec(4) state0 = Statevector(vec0) state1 = Statevector(vec1) self.assertEqual(state0 - state1, Statevector(vec0 - vec1)) def test_multiply(self): """Test multiply method.""" for _ in range(10): vec = self.rand_vec(4) state = Statevector(vec) val = np.random.rand() + 1j * np.random.rand() self.assertEqual(val * state, Statevector(val * state)) def test_negate(self): """Test negate method""" for _ in range(10): vec = self.rand_vec(4) state = Statevector(vec) self.assertEqual(-state, Statevector(-1 * vec)) def test_equiv(self): """Test equiv method""" vec = np.array([1, 0, 0, -1j]) / np.sqrt(2) phase = np.exp(-1j * np.pi / 4) statevec = Statevector(vec) self.assertTrue(statevec.equiv(phase * vec)) self.assertTrue(statevec.equiv(Statevector(phase * vec))) self.assertFalse(statevec.equiv(2 * vec)) def test_equiv_on_circuit(self): """Test the equiv method on different types of input.""" statevec = Statevector([1, 0]) qc = QuantumCircuit(1) self.assertTrue(statevec.equiv(qc)) qc.x(0) self.assertFalse(statevec.equiv(qc)) def test_to_dict(self): """Test to_dict method""" with self.subTest(msg="dims = (2, 3)"): vec = Statevector(np.arange(1, 7), dims=(2, 3)) target = {"00": 1, "01": 2, "10": 3, "11": 4, "20": 5, "21": 6} self.assertDictAlmostEqual(target, vec.to_dict()) with self.subTest(msg="dims = (11, )"): vec = Statevector(np.arange(1, 12), dims=(11,)) target = {str(i): i + 1 for i in range(11)} self.assertDictAlmostEqual(target, vec.to_dict()) with self.subTest(msg="dims = (2, 11)"): vec = Statevector(np.arange(1, 23), dims=(2, 11)) target = {} for i in range(11): for j in range(2): key = f"{i},{j}" target[key] = 2 * i + j + 1 self.assertDictAlmostEqual(target, vec.to_dict()) def test_probabilities_product(self): """Test probabilities method for product state""" state = Statevector.from_label("+0") # 2-qubit qargs with self.subTest(msg="P(None)"): probs = state.probabilities() target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([0, 1])"): probs = state.probabilities([0, 1]) target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([1, 0]"): probs = state.probabilities([1, 0]) target = np.array([0.5, 0.5, 0, 0]) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs with self.subTest(msg="P([0])"): probs = state.probabilities([0]) target = np.array([1, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([1])"): probs = state.probabilities([1]) target = np.array([0.5, 0.5]) self.assertTrue(np.allclose(probs, target)) def test_probabilities_ghz(self): """Test probabilities method for GHZ state""" state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) # 3-qubit qargs target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5]) for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs target = np.array([0.5, 0, 0, 0.5]) for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs target = np.array([0.5, 0.5]) for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) def test_probabilities_w(self): """Test probabilities method with W state""" state = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) # 3-qubit qargs target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0]) for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs target = np.array([1 / 3, 1 / 3, 1 / 3, 0]) for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs target = np.array([2 / 3, 1 / 3]) for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) def test_probabilities_dict_product(self): """Test probabilities_dict method for product state""" state = Statevector.from_label("+0") # 2-qubit qargs with self.subTest(msg="P(None)"): probs = state.probabilities_dict() target = {"00": 0.5, "10": 0.5} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([0, 1])"): probs = state.probabilities_dict([0, 1]) target = {"00": 0.5, "10": 0.5} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([1, 0]"): probs = state.probabilities_dict([1, 0]) target = {"00": 0.5, "01": 0.5} self.assertDictAlmostEqual(probs, target) # 1-qubit qargs with self.subTest(msg="P([0])"): probs = state.probabilities_dict([0]) target = {"0": 1} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([1])"): probs = state.probabilities_dict([1]) target = {"0": 0.5, "1": 0.5} self.assertDictAlmostEqual(probs, target) def test_probabilities_dict_ghz(self): """Test probabilities_dict method for GHZ state""" state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) # 3-qubit qargs target = {"000": 0.5, "111": 0.5} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 2-qubit qargs target = {"00": 0.5, "11": 0.5} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 1-qubit qargs target = {"0": 0.5, "1": 0.5} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) def test_probabilities_dict_w(self): """Test probabilities_dict method with W state""" state = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) # 3-qubit qargs target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0]) target = {"001": 1 / 3, "010": 1 / 3, "100": 1 / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 2-qubit qargs target = {"00": 1 / 3, "01": 1 / 3, "10": 1 / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 1-qubit qargs target = {"0": 2 / 3, "1": 1 / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) def test_sample_counts_ghz(self): """Test sample_counts method for GHZ state""" shots = 2000 threshold = 0.02 * shots state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) state.seed(100) # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) def test_sample_counts_w(self): """Test sample_counts method for W state""" shots = 3000 threshold = 0.02 * shots state = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) state.seed(100) target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) def test_probabilities_dict_unequal_dims(self): """Test probabilities_dict for a state with unequal subsystem dimensions.""" vec = np.zeros(60, dtype=float) vec[15:20] = np.ones(5) vec[40:46] = np.ones(6) state = Statevector(vec / np.sqrt(11.0), dims=[3, 4, 5]) p = 1.0 / 11.0 self.assertDictEqual( state.probabilities_dict(), { s: p for s in [ "110", "111", "112", "120", "121", "311", "312", "320", "321", "322", "330", ] }, ) # differences due to rounding self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0]), {"0": 4 * p, "1": 4 * p, "2": 3 * p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[1]), {"1": 5 * p, "2": 5 * p, "3": p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[2]), {"1": 5 * p, "3": 6 * p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0, 1]), {"10": p, "11": 2 * p, "12": 2 * p, "20": 2 * p, "21": 2 * p, "22": p, "30": p}, delta=1e-10, ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[1, 0]), {"01": p, "11": 2 * p, "21": 2 * p, "02": 2 * p, "12": 2 * p, "22": p, "03": p}, delta=1e-10, ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0, 2]), {"10": 2 * p, "11": 2 * p, "12": p, "31": 2 * p, "32": 2 * p, "30": 2 * p}, delta=1e-10, ) def test_sample_counts_qutrit(self): """Test sample_counts method for qutrit state""" p = 0.3 shots = 1000 threshold = 0.03 * shots state = Statevector([np.sqrt(p), 0, np.sqrt(1 - p)]) state.seed(100) with self.subTest(msg="counts"): target = {"0": shots * p, "2": shots * (1 - p)} counts = state.sample_counts(shots=shots) self.assertDictAlmostEqual(counts, target, threshold) def test_sample_memory_ghz(self): """Test sample_memory method for GHZ state""" shots = 2000 state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) state.seed(100) # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) def test_sample_memory_w(self): """Test sample_memory method for W state""" shots = 3000 state = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) state.seed(100) target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) def test_sample_memory_qutrit(self): """Test sample_memory method for qutrit state""" p = 0.3 shots = 1000 state = Statevector([np.sqrt(p), 0, np.sqrt(1 - p)]) state.seed(100) with self.subTest(msg="memory"): memory = state.sample_memory(shots) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), {"0", "2"}) def test_reset_2qubit(self): """Test reset method for 2-qubit state""" state = Statevector(np.array([1, 0, 0, 1]) / np.sqrt(2)) state.seed(100) with self.subTest(msg="reset"): psi = state.copy() value = psi.reset() target = Statevector(np.array([1, 0, 0, 0])) self.assertEqual(value, target) with self.subTest(msg="reset"): psi = state.copy() value = psi.reset([0, 1]) target = Statevector(np.array([1, 0, 0, 0])) self.assertEqual(value, target) with self.subTest(msg="reset [0]"): psi = state.copy() value = psi.reset([0]) targets = [Statevector(np.array([1, 0, 0, 0])), Statevector(np.array([0, 0, 1, 0]))] self.assertIn(value, targets) with self.subTest(msg="reset [0]"): psi = state.copy() value = psi.reset([1]) targets = [Statevector(np.array([1, 0, 0, 0])), Statevector(np.array([0, 1, 0, 0]))] self.assertIn(value, targets) def test_reset_qutrit(self): """Test reset method for qutrit""" state = Statevector(np.array([1, 1, 1]) / np.sqrt(3)) state.seed(200) value = state.reset() target = Statevector(np.array([1, 0, 0])) self.assertEqual(value, target) def test_measure_2qubit(self): """Test measure method for 2-qubit state""" state = Statevector.from_label("+0") seed = 200 shots = 100 with self.subTest(msg="measure"): for i in range(shots): psi = state.copy() psi.seed(seed + i) outcome, value = psi.measure() self.assertIn(outcome, ["00", "10"]) if outcome == "00": target = Statevector.from_label("00") self.assertEqual(value, target) else: target = Statevector.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [0, 1]"): for i in range(shots): psi = state.copy() outcome, value = psi.measure([0, 1]) self.assertIn(outcome, ["00", "10"]) if outcome == "00": target = Statevector.from_label("00") self.assertEqual(value, target) else: target = Statevector.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [1, 0]"): for i in range(shots): psi = state.copy() outcome, value = psi.measure([1, 0]) self.assertIn(outcome, ["00", "01"]) if outcome == "00": target = Statevector.from_label("00") self.assertEqual(value, target) else: target = Statevector.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [0]"): for i in range(shots): psi = state.copy() outcome, value = psi.measure([0]) self.assertEqual(outcome, "0") target = Statevector(np.array([1, 0, 1, 0]) / np.sqrt(2)) self.assertEqual(value, target) with self.subTest(msg="measure [1]"): for i in range(shots): psi = state.copy() outcome, value = psi.measure([1]) self.assertIn(outcome, ["0", "1"]) if outcome == "0": target = Statevector.from_label("00") self.assertEqual(value, target) else: target = Statevector.from_label("10") self.assertEqual(value, target) def test_measure_qutrit(self): """Test measure method for qutrit""" state = Statevector(np.array([1, 1, 1]) / np.sqrt(3)) seed = 200 shots = 100 for i in range(shots): psi = state.copy() psi.seed(seed + i) outcome, value = psi.measure() self.assertIn(outcome, ["0", "1", "2"]) if outcome == "0": target = Statevector([1, 0, 0]) self.assertEqual(value, target) elif outcome == "1": target = Statevector([0, 1, 0]) self.assertEqual(value, target) else: target = Statevector([0, 0, 1]) self.assertEqual(value, target) def test_from_int(self): """Test from_int method""" with self.subTest(msg="from_int(0, 4)"): target = Statevector([1, 0, 0, 0]) value = Statevector.from_int(0, 4) self.assertEqual(target, value) with self.subTest(msg="from_int(3, 4)"): target = Statevector([0, 0, 0, 1]) value = Statevector.from_int(3, 4) self.assertEqual(target, value) with self.subTest(msg="from_int(8, (3, 3))"): target = Statevector([0, 0, 0, 0, 0, 0, 0, 0, 1], dims=(3, 3)) value = Statevector.from_int(8, (3, 3)) self.assertEqual(target, value) def test_expval(self): """Test expectation_value method""" psi = Statevector([1, 0, 0, 1]) / np.sqrt(2) for label, target in [ ("II", 1), ("XX", 1), ("YY", -1), ("ZZ", 1), ("IX", 0), ("YZ", 0), ("ZX", 0), ("YI", 0), ]: with self.subTest(msg=f"<{label}>"): op = Pauli(label) expval = psi.expectation_value(op) self.assertAlmostEqual(expval, target) psi = Statevector([np.sqrt(2), 0, 0, 0, 0, 0, 0, 1 + 1j]) / 2 for label, target in [ ("XXX", np.sqrt(2) / 2), ("YYY", -np.sqrt(2) / 2), ("ZZZ", 0), ("XYZ", 0), ("YIY", 0), ]: with self.subTest(msg=f"<{label}>"): op = Pauli(label) expval = psi.expectation_value(op) self.assertAlmostEqual(expval, target) labels = ["XXX", "IXI", "YYY", "III"] coeffs = [3.0, 5.5, -1j, 23] spp_op = SparsePauliOp.from_list(list(zip(labels, coeffs))) expval = psi.expectation_value(spp_op) target = 25.121320343559642 + 0.7071067811865476j self.assertAlmostEqual(expval, target) @data( "II", "IX", "IY", "IZ", "XI", "XX", "XY", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "ZZ", "-II", "-IX", "-IY", "-IZ", "-XI", "-XX", "-XY", "-XZ", "-YI", "-YX", "-YY", "-YZ", "-ZI", "-ZX", "-ZY", "-ZZ", "iII", "iIX", "iIY", "iIZ", "iXI", "iXX", "iXY", "iXZ", "iYI", "iYX", "iYY", "iYZ", "iZI", "iZX", "iZY", "iZZ", "-iII", "-iIX", "-iIY", "-iIZ", "-iXI", "-iXX", "-iXY", "-iXZ", "-iYI", "-iYX", "-iYY", "-iYZ", "-iZI", "-iZX", "-iZY", "-iZZ", ) def test_expval_pauli(self, pauli): """Test expectation_value method for Pauli op""" seed = 1020 op = Pauli(pauli) state = random_statevector(2**op.num_qubits, seed=seed) target = state.expectation_value(op.to_matrix()) expval = state.expectation_value(op) self.assertAlmostEqual(expval, target) @data([0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]) def test_expval_pauli_qargs(self, qubits): """Test expectation_value method for Pauli op""" seed = 1020 op = random_pauli(2, seed=seed) state = random_statevector(2**3, seed=seed) target = state.expectation_value(op.to_matrix(), qubits) expval = state.expectation_value(op, qubits) self.assertAlmostEqual(expval, target) @data(*(qargs for i in range(4) for qargs in permutations(range(4), r=i + 1))) def test_probabilities_qargs(self, qargs): """Test probabilities method with qargs""" # Get initial state nq = 4 nc = len(qargs) state_circ = QuantumCircuit(nq, nc) for i in range(nq): state_circ.ry((i + 1) * np.pi / (nq + 1), i) # Get probabilities state = Statevector(state_circ) probs = state.probabilities(qargs) # Estimate target probs from simulator measurement sim = QasmSimulatorPy() shots = 5000 seed = 100 circ = transpile(state_circ, sim) circ.measure(qargs, range(nc)) result = sim.run(circ, shots=shots, seed_simulator=seed).result() target = np.zeros(2**nc, dtype=float) for i, p in result.get_counts(0).int_outcomes().items(): target[i] = p / shots # Compare delta = np.linalg.norm(probs - target) self.assertLess(delta, 0.05) def test_global_phase(self): """Test global phase is handled correctly when evolving statevector.""" qc = QuantumCircuit(1) qc.rz(0.5, 0) qc2 = transpile(qc, basis_gates=["p"]) sv = Statevector.from_instruction(qc2) expected = np.array([0.96891242 - 0.24740396j, 0]) self.assertEqual(float(qc2.global_phase), 2 * np.pi - 0.25) self.assertEqual(sv, Statevector(expected)) def test_reverse_qargs(self): """Test reverse_qargs method""" circ1 = QFT(5) circ2 = circ1.reverse_bits() state1 = Statevector.from_instruction(circ1) state2 = Statevector.from_instruction(circ2) self.assertEqual(state1.reverse_qargs(), state2) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "requires matplotlib") @unittest.skipUnless(optionals.HAS_PYLATEX, "requires pylatexenc") def test_drawings(self): """Test draw method""" qc1 = QFT(5) sv = Statevector.from_instruction(qc1) with self.subTest(msg="str(statevector)"): str(sv) for drawtype in ["repr", "text", "latex", "latex_source", "qsphere", "hinton", "bloch"]: with self.subTest(msg=f"draw('{drawtype}')"): sv.draw(drawtype) with self.subTest(msg=" draw('latex', convention='vector')"): sv.draw("latex", convention="vector") def test_state_to_latex_for_none(self): """ Test for `\rangleNone` output in latex representation See https://github.com/Qiskit/qiskit-terra/issues/8169 """ sv = Statevector( [ 7.07106781e-01 - 8.65956056e-17j, -5.55111512e-17 - 8.65956056e-17j, 7.85046229e-17 + 8.65956056e-17j, -7.07106781e-01 + 8.65956056e-17j, 0.00000000e00 + 0.00000000e00j, -0.00000000e00 + 0.00000000e00j, -0.00000000e00 + 0.00000000e00j, 0.00000000e00 - 0.00000000e00j, ], dims=(2, 2, 2), ) latex_representation = state_to_latex(sv) self.assertEqual( latex_representation, "\\frac{\\sqrt{2}}{2} |000\\rangle- \\frac{\\sqrt{2}}{2} |011\\rangle", ) def test_state_to_latex_for_large_statevector(self): """Test conversion of large dense state vector""" sv = Statevector(np.ones((2**15, 1))) latex_representation = state_to_latex(sv) self.assertEqual( latex_representation, " |000000000000000\\rangle+ |000000000000001\\rangle+ |000000000000010\\rangle+" " |000000000000011\\rangle+ |000000000000100\\rangle+ |000000000000101\\rangle +" " \\ldots + |111111111111011\\rangle+ |111111111111100\\rangle+" " |111111111111101\\rangle+ |111111111111110\\rangle+ |111111111111111\\rangle", ) def test_state_to_latex_with_prefix(self): """Test adding prefix to state vector latex output""" psi = Statevector(np.array([np.sqrt(1 / 2), 0, 0, np.sqrt(1 / 2)])) prefix = "|\\psi_{AB}\\rangle = " latex_sv = state_to_latex(psi) latex_expected = prefix + latex_sv latex_representation = state_to_latex(psi, prefix=prefix) self.assertEqual(latex_representation, latex_expected) def test_state_to_latex_for_large_sparse_statevector(self): """Test conversion of large sparse state vector""" sv = Statevector(np.eye(2**15, 1)) latex_representation = state_to_latex(sv) self.assertEqual(latex_representation, " |000000000000000\\rangle") def test_state_to_latex_with_max_size_limit(self): """Test limit the maximum number of non-zero terms in the expression""" sv = Statevector( [ 0.35355339 + 0.0j, 0.35355339 + 0.0j, 0.35355339 + 0.0j, 0.35355339 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 - 0.35355339j, 0.0 + 0.35355339j, 0.0 + 0.35355339j, 0.0 - 0.35355339j, ], dims=(2, 2, 2, 2), ) latex_representation = state_to_latex(sv, max_size=5) self.assertEqual( latex_representation, "\\frac{\\sqrt{2}}{4} |0000\\rangle+" "\\frac{\\sqrt{2}}{4} |0001\\rangle + " "\\ldots +" "\\frac{\\sqrt{2} i}{4} |1110\\rangle- " "\\frac{\\sqrt{2} i}{4} |1111\\rangle", ) def test_state_to_latex_with_decimals_round(self): """Test rounding of decimal places in the expression""" sv = Statevector( [ 0.35355339 + 0.0j, 0.35355339 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 - 0.35355339j, 0.0 + 0.35355339j, ], dims=(2, 2, 2), ) latex_representation = state_to_latex(sv, decimals=3) self.assertEqual( latex_representation, "0.354 |000\\rangle+0.354 |001\\rangle- 0.354 i |110\\rangle+0.354 i |111\\rangle", ) def test_number_to_latex_terms(self): """Test conversions of complex numbers to latex terms""" cases = [ ([1 - 8e-17, 0], ["", None]), ([0, -1], [None, "-"]), ([0, 1], [None, ""]), ([0, 1j], [None, "i"]), ([-1, 1], ["-", "+"]), ([0, 1j], [None, "i"]), ([-1, 1j], ["-", "+i"]), ([1e-16 + 1j], ["i"]), ([-1 + 1e-16 * 1j], ["-"]), ([-1, -1 - 1j], ["-", "+(-1 - i)"]), ([np.sqrt(2) / 2, np.sqrt(2) / 2], ["\\frac{\\sqrt{2}}{2}", "+\\frac{\\sqrt{2}}{2}"]), ([1 + np.sqrt(2)], ["(1 + \\sqrt{2})"]), ] with self.assertWarns(DeprecationWarning): for numbers, latex_terms in cases: terms = numbers_to_latex_terms(numbers, 15) self.assertListEqual(terms, latex_terms) def test_statevector_draw_latex_regression(self): """Test numerical rounding errors are not printed""" sv = Statevector(np.array([1 - 8e-17, 8.32667268e-17j])) latex_string = sv.draw(output="latex_source") self.assertTrue(latex_string.startswith(" |0\\rangle")) self.assertNotIn("|1\\rangle", latex_string) def test_statevctor_iter(self): """Test iteration over a state vector""" empty_vector = [] dummy_vector = [1, 2, 3] empty_sv = Statevector([]) sv = Statevector(dummy_vector) # Assert that successive iterations behave as expected, i.e., the # iterator is reset upon each exhaustion of the corresponding # collection of elements. for _ in range(2): self.assertEqual(empty_vector, list(empty_sv)) self.assertEqual(dummy_vector, list(sv)) def test_statevector_len(self): """Test state vector length""" empty_vector = [] dummy_vector = [1, 2, 3] empty_sv = Statevector([]) sv = Statevector(dummy_vector) self.assertEqual(len(empty_vector), len(empty_sv)) self.assertEqual(len(dummy_vector), len(sv)) def test_clip_probabilities(self): """Test probabilities are clipped to [0, 1].""" sv = Statevector([1.1, 0]) self.assertEqual(list(sv.probabilities()), [1.0, 0.0]) # The "1" key should be zero and therefore omitted. self.assertEqual(sv.probabilities_dict(), {"0": 1.0}) def test_round_probabilities(self): """Test probabilities are correctly rounded. This is good to test to ensure clipping, renormalizing and rounding work together. """ p = np.sqrt(1 / 3) sv = Statevector([p, p, p, 0]) expected = [0.33, 0.33, 0.33, 0] self.assertEqual(list(sv.probabilities(decimals=2)), expected) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 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. """Class for holding time evolution result.""" from __future__ import annotations import numpy as np from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit_algorithms.list_or_dict import ListOrDict from ..algorithm_result import AlgorithmResult class TimeEvolutionResult(AlgorithmResult): """ Class for holding time evolution result. Attributes: evolved_state (QuantumCircuit|Statevector): An evolved quantum state. aux_ops_evaluated (ListOrDict[tuple[complex, complex]] | None): Optional list of observables for which expected values on an evolved state are calculated. These values are in fact tuples formatted as (mean, standard deviation). observables (ListOrDict[tuple[np.ndarray, np.ndarray]] | None): Optional list of observables for which expected on an evolved state are calculated at each timestep. These values are in fact lists of tuples formatted as (mean, standard deviation). times (np.array | None): Optional list of times at which each observable has been evaluated. """ def __init__( self, evolved_state: QuantumCircuit | Statevector, aux_ops_evaluated: ListOrDict[tuple[complex, complex]] | None = None, observables: ListOrDict[tuple[np.ndarray, np.ndarray]] | None = None, times: np.ndarray | None = None, ): """ Args: evolved_state: An evolved quantum state. aux_ops_evaluated: Optional list of observables for which expected values on an evolved state are calculated. These values are in fact tuples formatted as (mean, standard deviation). observables: Optional list of observables for which expected values are calculated for each timestep. These values are in fact tuples formatted as (mean array, standard deviation array). times: Optional list of times at which each observable has been evaluated. """ self.evolved_state = evolved_state self.aux_ops_evaluated = aux_ops_evaluated self.observables = observables self.times = times
https://github.com/ttlion/ShorAlgQiskit
ttlion
""" This is the final implementation of Shor's Algorithm using the circuit presented in section 2.3 of the report about the first simplification introduced by the base paper used. As the circuit is completely general, it is a rather long circuit, with a lot of QASM instructions in the generated Assembly code, which makes that for high values of N the code is not able to run in IBM Q Experience because IBM has a very low restriction on the number os QASM instructions it can run. For N=15, it can run on IBM. But, for example, for N=21 it already may not, because it exceeds the restriction of QASM instructions. The user can try to use n qubits on top register instead of 2n to get more cases working on IBM. This will, however and naturally, diminish the probabilty of success. For a small number of qubits (about until 20), the code can be run on a local simulator. This makes it to be a little slow even for the factorization of small numbers N. Because of this, although all is general and we ask the user to introduce the number N and if he agrees with the 'a' value selected or not, we after doing that force N=15 and a=4, because that is a case where the simulation, although slow, can be run in local simulator and does not last 'forever' to end. If the user wants he can just remove the 2 lines of code where that is done, and put bigger N (that will be slow) or can try to run on the ibm simulator (for that, the user should introduce its IBM Q Experience Token and be aware that for high values of N it will just receive a message saying the size of the circuit is too big) """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ from qiskit import BasicAer import sys """ Imports to Python functions """ import math import array import fractions import numpy as np import time """ Local Imports """ from cfunctions import check_if_power, get_value_a from cfunctions import get_factors from qfunctions import create_QFT, create_inverse_QFT from qfunctions import cMULTmodN """ Main program """ if __name__ == '__main__': """ Ask for analysis number N """ N = int(input('Please insert integer number N: ')) print('input number was: {0}\n'.format(N)) """ Check if N==1 or N==0""" if N==1 or N==0: print('Please put an N different from 0 and from 1') exit() """ Check if N is even """ if (N%2)==0: print('N is even, so does not make sense!') exit() """ Check if N can be put in N=p^q, p>1, q>=2 """ """ Try all numbers for p: from 2 to sqrt(N) """ if check_if_power(N)==True: exit() print('Not an easy case, using the quantum circuit is necessary\n') """ To login to IBM Q experience the following functions should be called """ """ IBMQ.delete_accounts() IBMQ.save_account('insert token here') IBMQ.load_accounts() """ """ Get an integer a that is coprime with N """ a = get_value_a(N) """ If user wants to force some values, he can do that here, please make sure to update the print and that N and a are coprime""" print('Forcing N=15 and a=4 because its the fastest case, please read top of source file for more info') N=15 a=4 """ Get n value used in Shor's algorithm, to know how many qubits are used """ n = math.ceil(math.log(N,2)) print('Total number of qubits used: {0}\n'.format(4*n+2)) ts = time.time() """ Create quantum and classical registers """ """auxilliary quantum register used in addition and multiplication""" aux = QuantumRegister(n+2) """quantum register where the sequential QFT is performed""" up_reg = QuantumRegister(2*n) """quantum register where the multiplications are made""" down_reg = QuantumRegister(n) """classical register where the measured values of the QFT are stored""" up_classic = ClassicalRegister(2*n) """ Create Quantum Circuit """ circuit = QuantumCircuit(down_reg , up_reg , aux, up_classic) """ Initialize down register to 1 and create maximal superposition in top register """ circuit.h(up_reg) circuit.x(down_reg[0]) """ Apply the multiplication gates as showed in the report in order to create the exponentiation """ for i in range(0, 2*n): cMULTmodN(circuit, up_reg[i], down_reg, aux, int(pow(a, pow(2, i))), N, n) """ Apply inverse QFT """ create_inverse_QFT(circuit, up_reg, 2*n ,1) """ Measure the top qubits, to get x value""" circuit.measure(up_reg,up_classic) """ show results of circuit creation """ create_time = round(time.time()-ts, 3) #if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Select how many times the circuit runs""" number_shots=int(input('Number of times to run the circuit: ')) if number_shots < 1: print('Please run the circuit at least one time...') exit() if number_shots > 1: print('\nIf the circuit takes too long to run, consider running it less times\n') """ Print info to user """ print('Executing the circuit {0} times for N={1} and a={2}\n'.format(number_shots,N,a)) """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('qasm_simulator'),shots=number_shots) """ to run on IBM, use backend=IBMQ.get_backend('ibmq_qasm_simulator') in execute() function """ """ to run locally, use backend=BasicAer.get_backend('qasm_simulator') in execute() function """ """ Get the results of the simulation in proper structure """ sim_result=simulation.result() counts_result = sim_result.get_counts(circuit) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print info to user from the simulation results """ print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format(number_shots)) i=0 while i < len(counts_result): print('Result \"{0}\" happened {1} times out of {2}'.format(list(sim_result.get_counts().keys())[i],list(sim_result.get_counts().values())[i],number_shots)) i=i+1 """ An empty print just to have a good display in terminal """ print(' ') """ Initialize this variable """ prob_success=0 """ For each simulation result, print proper info to user and try to calculate the factors of N""" i=0 while i < len(counts_result): """ Get the x_value from the final state qubits """ output_desired = list(sim_result.get_counts().keys())[i] x_value = int(output_desired, 2) prob_this_result = 100 * ( int( list(sim_result.get_counts().values())[i] ) ) / (number_shots) print("------> Analysing result {0}. This result happened in {1:.4f} % of all cases\n".format(output_desired,prob_this_result)) """ Print the final x_value to user """ print('In decimal, x_final value for this result is: {0}\n'.format(x_value)) """ Get the factors using the x value obtained """ success=get_factors(int(x_value),int(2*n),int(N),int(a)) if success==True: prob_success = prob_success + prob_this_result i=i+1 print("\nUsing a={0}, found the factors of N={1} in {2:.4f} % of the cases\n".format(a,N,prob_success))
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/qiskit-community/qiskit-translations-staging
qiskit-community
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") circ.draw(output='mpl')
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ ====================================================== Executing Experiments (:mod:`qiskit.execute_function`) ====================================================== .. currentmodule:: qiskit.execute_function .. autofunction:: execute """ import logging from time import time from qiskit.compiler import transpile, schedule from qiskit.providers.backend import Backend from qiskit.pulse import Schedule, ScheduleBlock from qiskit.exceptions import QiskitError from qiskit.utils.deprecation import deprecate_arg logger = logging.getLogger(__name__) def _log_submission_time(start_time, end_time): log_msg = "Total Job Submission Time - %.5f (ms)" % ((end_time - start_time) * 1000) logger.info(log_msg) @deprecate_arg("qobj_id", since="0.21.0", additional_msg="This argument has no effect anymore.") @deprecate_arg("qobj_header", since="0.21.0", additional_msg="This argument has no effect anymore.") def execute( experiments, backend, basis_gates=None, coupling_map=None, # circuit transpile options backend_properties=None, initial_layout=None, seed_transpiler=None, optimization_level=None, pass_manager=None, qobj_id=None, qobj_header=None, shots=None, # common run options memory=None, seed_simulator=None, default_qubit_los=None, default_meas_los=None, # schedule run options qubit_lo_range=None, meas_lo_range=None, schedule_los=None, meas_level=None, meas_return=None, memory_slots=None, memory_slot_size=None, rep_time=None, rep_delay=None, parameter_binds=None, schedule_circuit=False, inst_map=None, meas_map=None, scheduling_method=None, init_qubits=None, **run_config, ): """Execute a list of :class:`qiskit.circuit.QuantumCircuit` or :class:`qiskit.pulse.Schedule` on a backend. The execution is asynchronous, and a handle to a job instance is returned. Args: experiments (QuantumCircuit or list[QuantumCircuit] or Schedule or list[Schedule]): Circuit(s) or pulse schedule(s) to execute backend (Backend): Backend to execute circuits on. Transpiler options are automatically grabbed from backend.configuration() and backend.properties(). If any other option is explicitly set (e.g. coupling_map), it will override the backend's. basis_gates (list[str]): List of basis gate names to unroll to. e.g: ``['u1', 'u2', 'u3', 'cx']`` If ``None``, do not unroll. coupling_map (CouplingMap or list): Coupling map (perhaps custom) to target in mapping. Multiple formats are supported: #. CouplingMap instance #. list Must be given as an adjacency matrix, where each entry specifies all two-qubit interactions supported by backend e.g: ``[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]`` backend_properties (BackendProperties): Properties returned by a backend, including information on gate errors, readout errors, qubit coherence times, etc. Find a backend that provides this information with: ``backend.properties()`` initial_layout (Layout or dict or list): Initial position of virtual qubits on physical qubits. If this layout makes the circuit compatible with the coupling_map constraints, it will be used. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. Multiple formats are supported: #. :class:`qiskit.transpiler.Layout` instance #. ``dict``: * virtual to physical:: {qr[0]: 0, qr[1]: 3, qr[2]: 5} * physical to virtual:: {0: qr[0], 3: qr[1], 5: qr[2]} #. ``list``: * virtual to physical:: [0, 3, 5] # virtual qubits are ordered (in addition to named) * physical to virtual:: [qr[0], None, None, qr[1], None, qr[2]] seed_transpiler (int): Sets random seed for the stochastic parts of the transpiler optimization_level (int): How much optimization to perform on the circuits. Higher levels generate more optimized circuits, at the expense of longer transpilation time. * 0: no optimization * 1: light optimization * 2: heavy optimization * 3: even heavier optimization If None, level 1 will be chosen as default. pass_manager (PassManager): The pass manager to use during transpilation. If this arg is present, auto-selection of pass manager based on the transpile options will be turned off and this pass manager will be used directly. qobj_id (str): DEPRECATED: String identifier to annotate the Qobj. This has no effect and the :attr:`~.QuantumCircuit.name` attribute of the input circuit(s) should be used instead. qobj_header (QobjHeader or dict): DEPRECATED: User input that will be inserted in Qobj header, and will also be copied to the corresponding :class:`qiskit.result.Result` header. Headers do not affect the run. Headers do not affect the run. This kwarg has no effect anymore and the :attr:`~.QuantumCircuit.metadata` attribute of the input circuit(s) should be used instead. shots (int): Number of repetitions of each circuit, for sampling. Default: 1024 memory (bool): If True, per-shot measurement bitstrings are returned as well (provided the backend supports it). For OpenPulse jobs, only measurement level 2 supports this option. Default: False seed_simulator (int): Random seed to control sampling, for when backend is a simulator default_qubit_los (Optional[List[float]]): List of job level qubit drive LO frequencies in Hz. Overridden by ``schedule_los`` if specified. Must have length ``n_qubits``. default_meas_los (Optional[List[float]]): List of job level measurement LO frequencies in Hz. Overridden by ``schedule_los`` if specified. Must have length ``n_qubits``. qubit_lo_range (Optional[List[List[float]]]): List of job level drive LO ranges each of form ``[range_min, range_max]`` in Hz. Used to validate ``qubit_lo_freq``. Must have length ``n_qubits``. meas_lo_range (Optional[List[List[float]]]): List of job level measurement LO ranges each of form ``[range_min, range_max]`` in Hz. Used to validate ``meas_lo_freq``. Must have length ``n_qubits``. schedule_los (list): Experiment level (ie circuit or schedule) LO frequency configurations for qubit drive and measurement channels. These values override the job level values from ``default_qubit_los`` and ``default_meas_los``. Frequencies are in Hz. Settable for qasm and pulse jobs. If a single LO config or dict is used, the values are set at job level. If a list is used, the list must be the size of the number of experiments in the job, except in the case of a single experiment. In this case, a frequency sweep will be assumed and one experiment will be created for every list entry. Not every channel is required to be specified. If not specified, the backend default value will be used. meas_level (int or MeasLevel): Set the appropriate level of the measurement output for pulse experiments. meas_return (str or MeasReturn): Level of measurement data for the backend to return For ``meas_level`` 0 and 1: ``"single"`` returns information from every shot. ``"avg"`` returns average measurement output (averaged over number of shots). memory_slots (int): Number of classical memory slots used in this job. memory_slot_size (int): Size of each memory slot if the output is Level 0. rep_time (int): Time per program execution in seconds. Must be from the list provided by the backend (``backend.configuration().rep_times``). Defaults to the first entry. rep_delay (float): Delay between programs in seconds. Only supported on certain backends (``backend.configuration().dynamic_reprate_enabled`` ). If supported, ``rep_delay`` will be used instead of ``rep_time`` and must be from the range supplied by the backend (``backend.configuration().rep_delay_range``). Default is given by ``backend.configuration().default_rep_delay``. parameter_binds (list[dict]): List of Parameter bindings over which the set of experiments will be executed. Each list element (bind) should be of the form ``{Parameter1: value1, Parameter2: value2, ...}``. All binds will be executed across all experiments, e.g. if parameter_binds is a length-:math:`n` list, and there are :math:`m` experiments, a total of :math:`m \\times n` experiments will be run (one for each experiment/bind pair). schedule_circuit (bool): If ``True``, ``experiments`` will be converted to :class:`qiskit.pulse.Schedule` objects prior to execution. inst_map (InstructionScheduleMap): Mapping of circuit operations to pulse schedules. If None, defaults to the ``instruction_schedule_map`` of ``backend``. meas_map (list(list(int))): List of sets of qubits that must be measured together. If None, defaults to the ``meas_map`` of ``backend``. scheduling_method (str or list(str)): Optionally specify a particular scheduling method. init_qubits (bool): Whether to reset the qubits to the ground state for each shot. Default: ``True``. run_config (dict): Extra arguments used to configure the run (e.g. for Aer configurable backends). Refer to the backend documentation for details on these arguments. Note: for now, these keyword arguments will both be copied to the Qobj config, and passed to backend.run() Returns: Job: returns job instance derived from Job Raises: QiskitError: if the execution cannot be interpreted as either circuits or schedules Example: Construct a 5-qubit GHZ circuit and execute 4321 shots on a backend. .. code-block:: from qiskit import QuantumCircuit, execute, BasicAer backend = BasicAer.get_backend('qasm_simulator') qc = QuantumCircuit(5, 5) qc.h(0) qc.cx(0, range(1, 5)) qc.measure_all() job = execute(qc, backend, shots=4321) """ del qobj_id del qobj_header if isinstance(experiments, (Schedule, ScheduleBlock)) or ( isinstance(experiments, list) and isinstance(experiments[0], (Schedule, ScheduleBlock)) ): # do not transpile a schedule circuit if schedule_circuit: raise QiskitError("Must supply QuantumCircuit to schedule circuit.") elif pass_manager is not None: # transpiling using pass_manager _check_conflicting_argument( optimization_level=optimization_level, basis_gates=basis_gates, coupling_map=coupling_map, seed_transpiler=seed_transpiler, backend_properties=backend_properties, initial_layout=initial_layout, ) experiments = pass_manager.run(experiments) else: # transpiling the circuits using given transpile options experiments = transpile( experiments, basis_gates=basis_gates, coupling_map=coupling_map, backend_properties=backend_properties, initial_layout=initial_layout, seed_transpiler=seed_transpiler, optimization_level=optimization_level, backend=backend, ) if schedule_circuit: experiments = schedule( circuits=experiments, backend=backend, inst_map=inst_map, meas_map=meas_map, method=scheduling_method, ) if isinstance(backend, Backend): start_time = time() run_kwargs = { "shots": shots, "memory": memory, "seed_simulator": seed_simulator, "qubit_lo_freq": default_qubit_los, "meas_lo_freq": default_meas_los, "qubit_lo_range": qubit_lo_range, "meas_lo_range": meas_lo_range, "schedule_los": schedule_los, "meas_level": meas_level, "meas_return": meas_return, "memory_slots": memory_slots, "memory_slot_size": memory_slot_size, "rep_time": rep_time, "rep_delay": rep_delay, "init_qubits": init_qubits, } for key in list(run_kwargs.keys()): if not hasattr(backend.options, key): if run_kwargs[key] is not None: logger.info( "%s backend doesn't support option %s so not passing that kwarg to run()", backend.name, key, ) del run_kwargs[key] elif run_kwargs[key] is None: del run_kwargs[key] if parameter_binds: run_kwargs["parameter_binds"] = parameter_binds run_kwargs.update(run_config) job = backend.run(experiments, **run_kwargs) end_time = time() _log_submission_time(start_time, end_time) else: raise QiskitError("Invalid backend type %s" % type(backend)) return job def _check_conflicting_argument(**kargs): conflicting_args = [arg for arg, value in kargs.items() if value] if conflicting_args: raise QiskitError( "The parameters pass_manager conflicts with the following " "parameter(s): {}.".format(", ".join(conflicting_args)) )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (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. """Test the RZXCalibrationBuilderNoEcho.""" from math import pi, erf import numpy as np from ddt import data, ddt from qiskit.converters import circuit_to_dag from qiskit import circuit, schedule, QiskitError from qiskit.circuit.library.standard_gates import SXGate, RZGate from qiskit.providers.fake_provider import FakeHanoi # TODO - include FakeHanoiV2, FakeSherbrooke from qiskit.providers.fake_provider import FakeArmonk from qiskit.pulse import ( ControlChannel, DriveChannel, GaussianSquare, Waveform, Play, InstructionScheduleMap, Schedule, ) from qiskit.pulse import builder from qiskit.pulse.transforms import target_qobj_transform from qiskit.test import QiskitTestCase from qiskit.transpiler import PassManager from qiskit.transpiler.passes.calibration.builders import ( RZXCalibrationBuilder, RZXCalibrationBuilderNoEcho, ) class TestCalibrationBuilder(QiskitTestCase): """Test the Calibration Builder.""" # CR parameters __risefall = 4 __angle = np.pi / 2 __granularity = 16 @staticmethod def get_cr_play(cr_schedule, name): """A helper function to filter CR pulses.""" def _filter_func(time_inst): return isinstance(time_inst[1], Play) and time_inst[1].pulse.name.startswith(name) return cr_schedule.filter(_filter_func).instructions[0][1] def compute_stretch_duration(self, play_gaussian_square_pulse, theta): """Compute duration of stretched Gaussian Square pulse.""" pulse = play_gaussian_square_pulse.pulse sigma = pulse.sigma width = self.compute_stretch_width(play_gaussian_square_pulse, theta) duration = width + sigma * self.__risefall return round(duration / self.__granularity) * self.__granularity def compute_stretch_width(self, play_gaussian_square_pulse, theta): """Compute width of stretched Gaussian Square pulse.""" pulse = play_gaussian_square_pulse.pulse sigma = pulse.sigma width = pulse.width risefall_area = sigma * np.sqrt(2 * np.pi) * erf(self.__risefall) full_area = risefall_area + width target_area = abs(theta) / self.__angle * full_area return max(0, target_area - risefall_area) def u0p_play(self, cr_schedule): """Returns the positive CR pulse from cr_schedule.""" return self.get_cr_play(cr_schedule, "CR90p_u") def u0m_play(self, cr_schedule): """Returns the negative CR pulse from cr_schedule.""" return self.get_cr_play(cr_schedule, "CR90m_u") def d1p_play(self, cr_schedule): """Returns the positive rotary echo pulse from cr_schedule.""" return self.get_cr_play(cr_schedule, "CR90p_d") def d1m_play(self, cr_schedule): """Returns the negative rotary echo pulse from cr_schedule.""" return self.get_cr_play(cr_schedule, "CR90m_d") @ddt class TestRZXCalibrationBuilder(TestCalibrationBuilder): """Test RZXCalibrationBuilder.""" def build_forward( self, backend, theta, u0p_play, d1p_play, u0m_play, d1m_play, ): """A helper function to generate reference pulse schedule for forward direction.""" duration = self.compute_stretch_duration(u0p_play, theta) width = self.compute_stretch_width(u0p_play, theta) with builder.build( backend, default_alignment="sequential", default_transpiler_settings={"optimization_level": 0}, ) as ref_sched: with builder.align_left(): # Positive CRs u0p_params = u0p_play.pulse.parameters u0p_params["duration"] = duration u0p_params["width"] = width builder.play( GaussianSquare(**u0p_params), ControlChannel(0), ) d1p_params = d1p_play.pulse.parameters d1p_params["duration"] = duration d1p_params["width"] = width builder.play( GaussianSquare(**d1p_params), DriveChannel(1), ) builder.x(0) with builder.align_left(): # Negative CRs u0m_params = u0m_play.pulse.parameters u0m_params["duration"] = duration u0m_params["width"] = width builder.play( GaussianSquare(**u0m_params), ControlChannel(0), ) d1m_params = d1m_play.pulse.parameters d1m_params["duration"] = duration d1m_params["width"] = width builder.play( GaussianSquare(**d1m_params), DriveChannel(1), ) builder.x(0) return ref_sched def build_reverse( self, backend, theta, u0p_play, d1p_play, u0m_play, d1m_play, ): """A helper function to generate reference pulse schedule for backward direction.""" duration = self.compute_stretch_duration(u0p_play, theta) width = self.compute_stretch_width(u0p_play, theta) with builder.build( backend, default_alignment="sequential", default_transpiler_settings={"optimization_level": 0}, ) as ref_sched: # Hadamard gates builder.call_gate(RZGate(np.pi / 2), qubits=(0,)) builder.call_gate(SXGate(), qubits=(0,)) builder.call_gate(RZGate(np.pi / 2), qubits=(0,)) builder.call_gate(RZGate(np.pi / 2), qubits=(1,)) builder.call_gate(SXGate(), qubits=(1,)) builder.call_gate(RZGate(np.pi / 2), qubits=(1,)) with builder.align_left(): # Positive CRs u0p_params = u0p_play.pulse.parameters u0p_params["duration"] = duration u0p_params["width"] = width builder.play( GaussianSquare(**u0p_params), ControlChannel(0), ) d1p_params = d1p_play.pulse.parameters d1p_params["duration"] = duration d1p_params["width"] = width builder.play( GaussianSquare(**d1p_params), DriveChannel(1), ) builder.x(0) with builder.align_left(): # Negative CRs u0m_params = u0m_play.pulse.parameters u0m_params["duration"] = duration u0m_params["width"] = width builder.play( GaussianSquare(**u0m_params), ControlChannel(0), ) d1m_params = d1m_play.pulse.parameters d1m_params["duration"] = duration d1m_params["width"] = width builder.play( GaussianSquare(**d1m_params), DriveChannel(1), ) builder.x(0) # Hadamard gates builder.call_gate(RZGate(np.pi / 2), qubits=(0,)) builder.call_gate(SXGate(), qubits=(0,)) builder.call_gate(RZGate(np.pi / 2), qubits=(0,)) builder.call_gate(RZGate(np.pi / 2), qubits=(1,)) builder.call_gate(SXGate(), qubits=(1,)) builder.call_gate(RZGate(np.pi / 2), qubits=(1,)) return ref_sched @data(-np.pi / 4, 0.1, np.pi / 4, np.pi / 2, np.pi) def test_rzx_calibration_cr_pulse_stretch(self, theta: float): """Test that cross resonance pulse durations are computed correctly.""" backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map cr_schedule = inst_map.get("cx", (0, 1)) with builder.build() as test_sched: RZXCalibrationBuilder.rescale_cr_inst(self.u0p_play(cr_schedule), theta) self.assertEqual( test_sched.duration, self.compute_stretch_duration(self.u0p_play(cr_schedule), theta) ) @data(-np.pi / 4, 0.1, np.pi / 4, np.pi / 2, np.pi) def test_rzx_calibration_rotary_pulse_stretch(self, theta: float): """Test that rotary pulse durations are computed correctly.""" backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map cr_schedule = inst_map.get("cx", (0, 1)) with builder.build() as test_sched: RZXCalibrationBuilder.rescale_cr_inst(self.d1p_play(cr_schedule), theta) self.assertEqual( test_sched.duration, self.compute_stretch_duration(self.d1p_play(cr_schedule), theta) ) def test_raise(self): """Test that the correct error is raised.""" theta = np.pi / 4 qc = circuit.QuantumCircuit(2) qc.rzx(theta, 0, 1) dag = circuit_to_dag(qc) backend = FakeArmonk() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilder(inst_map) qubit_map = {qubit: i for i, qubit in enumerate(dag.qubits)} with self.assertRaises(QiskitError): for node in dag.gate_nodes(): qubits = [qubit_map[q] for q in node.qargs] _pass.get_calibration(node.op, qubits) def test_ecr_cx_forward(self): """Test that correct pulse sequence is generated for native CR pair.""" # Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling theta = np.pi / 4 qc = circuit.QuantumCircuit(2) qc.rzx(theta, 0, 1) backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilder(inst_map) test_qc = PassManager(_pass).run(qc) cr_schedule = inst_map.get("cx", (0, 1)) ref_sched = self.build_forward( backend, theta, self.u0p_play(cr_schedule), self.d1p_play(cr_schedule), self.u0m_play(cr_schedule), self.d1m_play(cr_schedule), ) self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched)) def test_ecr_cx_reverse(self): """Test that correct pulse sequence is generated for non-native CR pair.""" # Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling theta = np.pi / 4 qc = circuit.QuantumCircuit(2) qc.rzx(theta, 1, 0) backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilder(inst_map) test_qc = PassManager(_pass).run(qc) cr_schedule = inst_map.get("cx", (0, 1)) ref_sched = self.build_reverse( backend, theta, self.u0p_play(cr_schedule), self.d1p_play(cr_schedule), self.u0m_play(cr_schedule), self.d1m_play(cr_schedule), ) self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched)) def test_pass_alive_with_dcx_ish(self): """Test if the pass is not terminated by error with direct CX input.""" cx_sched = Schedule() # Fake direct cr cx_sched.insert(0, Play(GaussianSquare(800, 0.2, 64, 544), ControlChannel(1)), inplace=True) # Fake direct compensation tone # Compensation tone doesn't have dedicated pulse class. # So it's reported as a waveform now. compensation_tone = Waveform(0.1 * np.ones(800, dtype=complex)) cx_sched.insert(0, Play(compensation_tone, DriveChannel(0)), inplace=True) inst_map = InstructionScheduleMap() inst_map.add("cx", (1, 0), schedule=cx_sched) theta = pi / 3 rzx_qc = circuit.QuantumCircuit(2) rzx_qc.rzx(theta, 1, 0) pass_ = RZXCalibrationBuilder(instruction_schedule_map=inst_map) with self.assertWarns(UserWarning): # User warning that says q0 q1 is invalid cal_qc = PassManager(pass_).run(rzx_qc) self.assertEqual(cal_qc, rzx_qc) class TestRZXCalibrationBuilderNoEcho(TestCalibrationBuilder): """Test RZXCalibrationBuilderNoEcho.""" def build_forward( self, theta, u0p_play, d1p_play, ): """A helper function to generate reference pulse schedule for forward direction.""" duration = self.compute_stretch_duration(u0p_play, 2.0 * theta) width = self.compute_stretch_width(u0p_play, 2.0 * theta) with builder.build() as ref_sched: # Positive CRs u0p_params = u0p_play.pulse.parameters u0p_params["duration"] = duration u0p_params["width"] = width builder.play( GaussianSquare(**u0p_params), ControlChannel(0), ) d1p_params = d1p_play.pulse.parameters d1p_params["duration"] = duration d1p_params["width"] = width builder.play( GaussianSquare(**d1p_params), DriveChannel(1), ) builder.delay(duration, DriveChannel(0)) return ref_sched def test_ecr_cx_forward(self): """Test that correct pulse sequence is generated for native CR pair. .. notes:: No echo builder only supports native direction. """ # Sufficiently large angle to avoid minimum duration, i.e. amplitude rescaling theta = np.pi / 4 qc = circuit.QuantumCircuit(2) qc.rzx(theta, 0, 1) backend = FakeHanoi() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilderNoEcho(inst_map) test_qc = PassManager(_pass).run(qc) cr_schedule = inst_map.get("cx", (0, 1)) ref_sched = self.build_forward( theta, self.u0p_play(cr_schedule), self.d1p_play(cr_schedule), ) self.assertEqual(schedule(test_qc, backend), target_qobj_transform(ref_sched)) # # TODO - write test for forward ECR native pulse # def test_ecr_forward(self): def test_pass_alive_with_dcx_ish(self): """Test if the pass is not terminated by error with direct CX input.""" cx_sched = Schedule() # Fake direct cr cx_sched.insert(0, Play(GaussianSquare(800, 0.2, 64, 544), ControlChannel(1)), inplace=True) # Fake direct compensation tone # Compensation tone doesn't have dedicated pulse class. # So it's reported as a waveform now. compensation_tone = Waveform(0.1 * np.ones(800, dtype=complex)) cx_sched.insert(0, Play(compensation_tone, DriveChannel(0)), inplace=True) inst_map = InstructionScheduleMap() inst_map.add("cx", (1, 0), schedule=cx_sched) theta = pi / 3 rzx_qc = circuit.QuantumCircuit(2) rzx_qc.rzx(theta, 1, 0) pass_ = RZXCalibrationBuilderNoEcho(instruction_schedule_map=inst_map) with self.assertWarns(UserWarning): # User warning that says q0 q1 is invalid cal_qc = PassManager(pass_).run(rzx_qc) self.assertEqual(cal_qc, rzx_qc)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt 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 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 # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") 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_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # 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()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') zne_fid_list = [] zne_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # 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(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 = t3_st_qcs zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) 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), ")") 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) retrieved_jobs = jobs zne_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) zne_rho = expvals_to_valid_rho(num_qubits, zne_expvals) zne_fid = state_fidelity(zne_rho, target_state) zne_fids.append(zne_fid) zne_fid_list.append(np.mean(zne_fids)) zne_stddev_list.append(np.std(zne_fids)) t2 = time.perf_counter() print('zne pt state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(zne_fids), np.std(zne_fids))) print("time:", t2 - t1) print() with open("e2d1_zne_pt.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": zne_fid_list, "stddev": zne_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, zne_fid_list)
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
Andres8bit
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization import QuadraticProgram problem = QuadraticProgram("sample") problem.binary_var("x") problem.binary_var("y") problem.maximize(linear={"x": 1, "y": -2}) print(problem.prettyprint()) from qiskit.algorithms import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = NumPyMinimumEigensolver() meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = NumPyMinimumEigensolver() meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) mes = QAOA(optimizer=COBYLA(), quantum_instance=qins) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer shots = 1000 mes = QAOA(sampler=Sampler(), optimizer=COBYLA()) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) mes = VQE(ansatz=RealAmplitudes(), optimizer=COBYLA(), quantum_instance=qins) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = SamplingVQE(sampler=Sampler(), ansatz=RealAmplitudes(), optimizer=COBYLA()) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Estimator from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = VQE(estimator=Estimator(), ansatz=RealAmplitudes(), optimizer=COBYLA()) try: meo = MinimumEigenOptimizer(min_eigen_solver=mes) except TypeError as ex: print(ex) from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) qaoa = QAOA(optimizer=COBYLA(), quantum_instance=qins) optimizer = WarmStartQAOAOptimizer( pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25 ) result = optimizer.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer qaoa = QAOA(sampler=Sampler(), optimizer=COBYLA()) optimizer = WarmStartQAOAOptimizer( pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25 ) result = optimizer.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import GroverOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, quantum_instance=qins) result = optimizer.solve(problem) print(result) from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, sampler=Sampler()) result = optimizer.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) try: optimizer = GroverOptimizer( num_value_qubits=3, num_iterations=3, quantum_instance=qins, sampler=Sampler() ) # raises an error because both quantum_instance and sampler are set. except ValueError as ex: print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/msramalho/Teach-Me-Quantum
msramalho
import math # importing Qiskit from qiskit import Aer, IBMQ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.backends.ibmq import least_busy # useful additional packages from qiskit.wrapper.jupyter import * from qiskit.tools.visualization import plot_histogram IBMQ.load_accounts() def input_state(circ, q, n): """n-qubit input state for QFT that produces output 1.""" for j in range(n): circ.h(q[j]) circ.u1(math.pi/float(2**(j)), q[j]).inverse() def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(math.pi/float(2**(j-k)), q[j], q[k]) circ.h(q[j]) q = QuantumRegister(3) c = ClassicalRegister(3) qft3 = QuantumCircuit(q, c) input_state(qft3, q, 3) qft(qft3, q, 3) for i in range(3): qft3.measure(q[i], c[i]) print(qft3.qasm()) # run on local simulator backend = Aer.get_backend("qasm_simulator") simulate = execute(qft3, backend=backend, shots=1024).result() simulate.get_counts() %%qiskit_job_status # Use the IBM Quantum Experience backend = least_busy(IBMQ.backends(simulator=False)) shots = 1024 job_exp = execute(qft3, backend=backend, shots=shots) results = job_exp.result() plot_histogram(results.get_counts())
https://github.com/xtophe388/QISKIT
xtophe388
# useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import pi import sys # importing the QISKit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, get_backend # importing API token to access remote backends try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} except: qx_config = { "APItoken":"YOUR_TOKEN_HERE", "url":"https://quantumexperience.ng.bluemix.net/api"} # import basic plot tools from qiskit.tools.visualization import plot_histogram backend = 'local_qasm_simulator' # the device to run on shots = 1024 # the number of shots in the experiment #to record the rotation number for encoding 00, 10, 11, 01 rotationNumbers = {"00":1, "10":3, "11":5, "01":7} # Creating registers # qubit for encoding 2 bits of information qr = QuantumRegister(1) # bit for recording the measurement of the qubit cr = ClassicalRegister(1) # dictionary for encoding circuits encodingCircuits = {} # Quantum circuits for encoding 00, 10, 11, 01 for bits in ("00", "01", "10", "11"): circuitName = "Encode"+bits encodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName) encodingCircuits[circuitName].u3(rotationNumbers[bits]*pi/4.0, 0, 0, qr[0]) encodingCircuits[circuitName].barrier() # dictionary for decoding circuits decodingCircuits = {} # Quantum circuits for decoding the first and second bit for pos in ("First", "Second"): circuitName = "Decode"+pos decodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName) if pos == "Second": #if pos == "First" we can directly measure decodingCircuits[circuitName].h(qr[0]) decodingCircuits[circuitName].measure(qr[0], cr[0]) #combine encoding and decoding of QRACs to get a list of complete circuits circuitNames = [] circuits = [] for k1 in encodingCircuits.keys(): for k2 in decodingCircuits.keys(): circuitNames.append(k1+k2) circuits.append(encodingCircuits[k1]+decodingCircuits[k2]) print("List of circuit names:", circuitNames) #list of circuit names job = execute(circuits, backend=backend, shots=shots) results = job.result() print("Experimental Result of Encode01DecodeFirst") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode01DecodeFirst")])) #We should measure "0" with probability 0.85 print("Experimental Result of Encode01DecodeSecond") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode01DecodeSecond")])) #We should measure "1" with probability 0.85 print("Experimental Result of Encode11DecodeFirst") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode11DecodeFirst")])) #We should measure "1" with probability 0.85 print("Experimental Result of Encode11DecodeSecond") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode11DecodeSecond")])) #We should measure "1" with probability 0.85 #to enable sleep import time backend = "ibmqx4" #connect to remote API to be able to use remote simulators and real devices register(qx_config['APItoken'], qx_config['url']) print("Available backends:", available_backends()) if get_backend(backend).status["available"] is True: job_exp = execute(circuits, backend=backend, shots=shots) lapse = 0 interval = 50 while not job_exp.done: print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status) time.sleep(interval) lapse += 1 print(job_exp.status) results = job_exp.result() print("Experimental Result of Encode01DecodeFirst") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode01DecodeFirst")])) #We should measure "0" with probability 0.85 print("Experimental Result of Encode01DecodeSecond") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode01DecodeSecond")])) #We should measure "1" with probability 0.85 backend = 'local_qasm_simulator' # the device to run on shots = 1024 # the number of shots in the experiment from math import sqrt, cos, acos #compute the value of theta theta = acos(sqrt(0.5 + sqrt(3.0)/6.0)) #to record the u3 parameters for encoding 000, 010, 100, 110, 001, 011, 101, 111 rotationParams = {"000":(2*theta, pi/4, -pi/4), "010":(2*theta, 3*pi/4, -3*pi/4), "100":(pi-2*theta, pi/4, -pi/4), "110":(pi-2*theta, 3*pi/4, -3*pi/4), "001":(2*theta, -pi/4, pi/4), "011":(2*theta, -3*pi/4, 3*pi/4), "101":(pi-2*theta, -pi/4, pi/4), "111":(pi-2*theta, -3*pi/4, 3*pi/4)} # Creating registers # qubit for encoding 3 bits of information qr = QuantumRegister(1) # bit for recording the measurement of the qubit cr = ClassicalRegister(1) # dictionary for encoding circuits encodingCircuits = {} # Quantum circuits for encoding 000, ..., 111 for bits in rotationParams.keys(): circuitName = "Encode"+bits encodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName) encodingCircuits[circuitName].u3(*rotationParams[bits], qr[0]) encodingCircuits[circuitName].barrier() # dictionary for decoding circuits decodingCircuits = {} # Quantum circuits for decoding the first, second and third bit for pos in ("First", "Second", "Third"): circuitName = "Decode"+pos decodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName) if pos == "Second": #if pos == "First" we can directly measure decodingCircuits[circuitName].h(qr[0]) elif pos == "Third": decodingCircuits[circuitName].u3(pi/2, -pi/2, pi/2, qr[0]) decodingCircuits[circuitName].measure(qr[0], cr[0]) #combine encoding and decoding of QRACs to get a list of complete circuits circuitNames = [] circuits = [] for k1 in encodingCircuits.keys(): for k2 in decodingCircuits.keys(): circuitNames.append(k1+k2) circuits.append(encodingCircuits[k1]+decodingCircuits[k2]) print("List of circuit names:", circuitNames) #list of circuit names job = execute(circuits, backend=backend, shots=shots) results = job.result() print("Experimental Result of Encode010DecodeFirst") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeFirst")])) #We should measure "0" with probability 0.78 print("Experimental Result of Encode010DecodeSecond") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeSecond")])) #We should measure "1" with probability 0.78 print("Experimental Result of Encode010DecodeThird") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeThird")])) #We should measure "0" with probability 0.78 backend = "ibmqx4" #backend = "local_qasm_simulator" print("Available backends:", available_backends()) if get_backend(backend).status["available"] is True: job_exp = execute(circuits, backend=backend, shots=shots) lapse = 0 interval = 50 while not job_exp.done: print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status) time.sleep(interval) lapse += 1 print(job_exp.status) results = job_exp.result() print("Experimental Result of Encode010DecodeFirst") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeFirst")])) #We should measure "0" with probability 0.78 print("Experimental Result of Encode010DecodeSecond") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeSecond")])) #We should measure "1" with probability 0.78 print("Experimental Result of Encode010DecodeThird") plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeThird")])) #We should measure "0" with probability 0.78
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. """Disassemble function for a qobj into a list of circuits and its config""" from typing import Any, Dict, List, NewType, Tuple, Union import collections import math from qiskit import pulse from qiskit.circuit.classicalregister import ClassicalRegister from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister from qiskit.qobj import PulseQobjInstruction from qiskit.qobj.converters import QobjToInstructionConverter # A ``CircuitModule`` is a representation of a circuit execution on the backend. # It is currently a list of quantum circuits to execute, a run Qobj dictionary # and a header dictionary. CircuitModule = NewType( "CircuitModule", Tuple[List[QuantumCircuit], Dict[str, Any], Dict[str, Any]] ) # A ``PulseModule`` is a representation of a pulse execution on the backend. # It is currently a list of pulse schedules to execute, a run Qobj dictionary # and a header dictionary. PulseModule = NewType("PulseModule", Tuple[List[pulse.Schedule], Dict[str, Any], Dict[str, Any]]) def disassemble(qobj) -> Union[CircuitModule, PulseModule]: """Disassemble a qobj and return the circuits or pulse schedules, run_config, and user header. .. note:: ``disassemble(assemble(qc))`` is not guaranteed to produce an exactly equal circuit to the input, due to limitations in the :obj:`.QasmQobj` format that need to be maintained for backend system compatibility. This is most likely to be the case when using newer features of :obj:`.QuantumCircuit`. In most cases, the output should be equivalent, if not quite equal. Args: qobj (Qobj): The input qobj object to disassemble Returns: Union[CircuitModule, PulseModule]: The disassembled program which consists of: * programs: A list of quantum circuits or pulse schedules * run_config: The dict of the run config * user_qobj_header: The dict of any user headers in the qobj Examples: .. code-block:: python from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.compiler.assembler import assemble from qiskit.assembler.disassemble import disassemble # Create a circuit to assemble into a qobj q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) # Assemble the circuit into a Qobj qobj = assemble(qc, shots=2000, memory=True) # Disassemble the qobj back into a circuit circuits, run_config_out, headers = disassemble(qobj) """ if qobj.type == "PULSE": return _disassemble_pulse_schedule(qobj) else: return _disassemble_circuit(qobj) def _disassemble_circuit(qobj) -> CircuitModule: run_config = qobj.config.to_dict() # convert lo freq back to Hz qubit_lo_freq = run_config.get("qubit_lo_freq", []) if qubit_lo_freq: run_config["qubit_lo_freq"] = [freq * 1e9 for freq in qubit_lo_freq] meas_lo_freq = run_config.get("meas_lo_freq", []) if meas_lo_freq: run_config["meas_lo_freq"] = [freq * 1e9 for freq in meas_lo_freq] user_qobj_header = qobj.header.to_dict() return CircuitModule((_experiments_to_circuits(qobj), run_config, user_qobj_header)) def _qobj_to_circuit_cals(qobj, pulse_lib): """Return circuit calibrations dictionary from qobj/exp config calibrations.""" qobj_cals = qobj.config.calibrations.to_dict()["gates"] converter = QobjToInstructionConverter(pulse_lib) qc_cals = {} for gate in qobj_cals: config = (tuple(gate["qubits"]), tuple(gate["params"])) cal = { config: pulse.Schedule( name="{} {} {}".format(gate["name"], str(gate["params"]), str(gate["qubits"])) ) } for instruction in gate["instructions"]: qobj_instruction = PulseQobjInstruction.from_dict(instruction) schedule = converter(qobj_instruction) cal[config] = cal[config].insert(schedule.ch_start_time(), schedule) if gate["name"] in qc_cals: qc_cals[gate["name"]].update(cal) else: qc_cals[gate["name"]] = cal return qc_cals def _experiments_to_circuits(qobj): """Return a list of QuantumCircuit object(s) from a qobj. Args: qobj (Qobj): The Qobj object to convert to QuantumCircuits Returns: list: A list of QuantumCircuit objects from the qobj """ if not qobj.experiments: return None circuits = [] for exp in qobj.experiments: quantum_registers = [QuantumRegister(i[1], name=i[0]) for i in exp.header.qreg_sizes] classical_registers = [ClassicalRegister(i[1], name=i[0]) for i in exp.header.creg_sizes] circuit = QuantumCircuit(*quantum_registers, *classical_registers, name=exp.header.name) qreg_dict = collections.OrderedDict() creg_dict = collections.OrderedDict() for reg in quantum_registers: qreg_dict[reg.name] = reg for reg in classical_registers: creg_dict[reg.name] = reg conditional = {} for i in exp.instructions: name = i.name qubits = [] params = getattr(i, "params", []) try: for qubit in i.qubits: qubit_label = exp.header.qubit_labels[qubit] qubits.append(qreg_dict[qubit_label[0]][qubit_label[1]]) except Exception: # pylint: disable=broad-except pass clbits = [] try: for clbit in i.memory: clbit_label = exp.header.clbit_labels[clbit] clbits.append(creg_dict[clbit_label[0]][clbit_label[1]]) except Exception: # pylint: disable=broad-except pass if hasattr(circuit, name): instr_method = getattr(circuit, name) if i.name in ["snapshot"]: _inst = instr_method( i.label, snapshot_type=i.snapshot_type, qubits=qubits, params=params ) elif i.name == "initialize": _inst = instr_method(params, qubits) elif i.name == "isometry": _inst = instr_method(*params, qubits, clbits) elif i.name in ["mcx", "mcu1", "mcp"]: _inst = instr_method(*params, qubits[:-1], qubits[-1], *clbits) else: _inst = instr_method(*params, *qubits, *clbits) elif name == "bfunc": conditional["value"] = int(i.val, 16) full_bit_size = sum(creg_dict[x].size for x in creg_dict) mask_map = {} raw_map = {} raw = [] for creg in creg_dict: size = creg_dict[creg].size reg_raw = [1] * size if not raw: raw = reg_raw else: for pos, val in enumerate(raw): if val == 1: raw[pos] = 0 raw = reg_raw + raw mask = [0] * (full_bit_size - len(raw)) + raw raw_map[creg] = mask mask_map[int("".join(str(x) for x in mask), 2)] = creg if bin(int(i.mask, 16)).count("1") == 1: # The condition is on a single bit. This might be a single-bit condition, or it # might be a register of length one. The case that it's a single-bit condition # in a register of length one is ambiguous, and we choose to return a condition # on the register. This may not match the input circuit exactly, but is at # least equivalent. cbit = int(math.log2(int(i.mask, 16))) for reg in creg_dict.values(): size = reg.size if cbit >= size: cbit -= size else: conditional["register"] = reg if reg.size == 1 else reg[cbit] break mask_str = bin(int(i.mask, 16))[2:].zfill(full_bit_size) mask = [int(item) for item in list(mask_str)] else: creg = mask_map[int(i.mask, 16)] conditional["register"] = creg_dict[creg] mask = raw_map[creg] val = int(i.val, 16) for j in reversed(mask): if j == 0: val = val >> 1 else: conditional["value"] = val break else: _inst = temp_opaque_instruction = Instruction( name=name, num_qubits=len(qubits), num_clbits=len(clbits), params=params ) circuit.append(temp_opaque_instruction, qubits, clbits) if conditional and name != "bfunc": _inst.c_if(conditional["register"], conditional["value"]) conditional = {} pulse_lib = qobj.config.pulse_library if hasattr(qobj.config, "pulse_library") else [] # The dict update method did not work here; could investigate in the future if hasattr(qobj.config, "calibrations"): circuit.calibrations = dict( **circuit.calibrations, **_qobj_to_circuit_cals(qobj, pulse_lib) ) if hasattr(exp.config, "calibrations"): circuit.calibrations = dict( **circuit.calibrations, **_qobj_to_circuit_cals(exp, pulse_lib) ) circuits.append(circuit) return circuits def _disassemble_pulse_schedule(qobj) -> PulseModule: run_config = qobj.config.to_dict() run_config.pop("pulse_library") qubit_lo_freq = run_config.get("qubit_lo_freq") if qubit_lo_freq: run_config["qubit_lo_freq"] = [freq * 1e9 for freq in qubit_lo_freq] meas_lo_freq = run_config.get("meas_lo_freq") if meas_lo_freq: run_config["meas_lo_freq"] = [freq * 1e9 for freq in meas_lo_freq] user_qobj_header = qobj.header.to_dict() # extract schedule lo settings schedule_los = [] for program in qobj.experiments: program_los = {} if hasattr(program, "config"): if hasattr(program.config, "qubit_lo_freq"): for i, lo in enumerate(program.config.qubit_lo_freq): program_los[pulse.DriveChannel(i)] = lo * 1e9 if hasattr(program.config, "meas_lo_freq"): for i, lo in enumerate(program.config.meas_lo_freq): program_los[pulse.MeasureChannel(i)] = lo * 1e9 schedule_los.append(program_los) if any(schedule_los): run_config["schedule_los"] = schedule_los return PulseModule((_experiments_to_schedules(qobj), run_config, user_qobj_header)) def _experiments_to_schedules(qobj) -> List[pulse.Schedule]: """Return a list of :class:`qiskit.pulse.Schedule` object(s) from a qobj. Args: qobj (Qobj): The Qobj object to convert to pulse schedules. Returns: A list of :class:`qiskit.pulse.Schedule` objects from the qobj Raises: pulse.PulseError: If a parameterized instruction is supplied. """ converter = QobjToInstructionConverter(qobj.config.pulse_library) schedules = [] for program in qobj.experiments: insts = [] for inst in program.instructions: insts.append(converter(inst)) schedule = pulse.Schedule(*insts) schedules.append(schedule) return schedules
https://github.com/BryceFuller/qiskit_camp
BryceFuller
#!/usr/bin/env python # coding: utf-8 # Python import math # Local # External import numpy as np from qiskit import QuantumCircuit, QuantumRegister import qiskit.aqua def PrepareMultiDeterminantState(weights, determinants, normalize=True, mode='basic'): ''' Constructs multideterminant state : a linear superposition of many fermionic determinants. Appropriate for us as an input state for VQE. Input: np.array of REAL weights, and list of determinants. Each determinant is a bitstring of length n. Output: a QuantumCircuit object. If mode == basic, acting on 2n qubits (n logical, n ancillas). Otherwise, acting on n+1 qubits. The depth of the circuit goes like O(n L) where L = len(weights), in basic mode, and exponentially in n when only 1 ancilla. This is an implementation of the circuit in https://arxiv.org/abs/1809.05523 ''' # number of determinants in the state L = len(weights) if L != len(determinants): raise Exception('# weights != # determinants') # Check normalization norm = np.linalg.norm(weights) # print('Norm is: {}'.format(norm)) if normalize: weights /= norm elif abs(norm-1) > 10**-5: raise Exception('Weights do not produce a normalized vector.') # TODO: check that weights are normalized # number of orbitals that determinants can be made of n = len(determinants[0]) # the first n qubits will be used for orbitals, the next as the controlled rotation ancilla, # the last n as ancillas will be used for the n-Toffoli qubits = QuantumRegister(n, 'q') cqub = QuantumRegister(1, 'c') if mode == 'noancilla': # no ancillas registers = [qubits, cqub] else: ancillas = QuantumRegister(n-1, 'a') registers = [qubits, cqub, ancillas] # initialize circ = QuantumCircuit(*registers) for i in range(n): if determinants[0][i] == 1: circ.x(qubits[i]) circ.x(cqub) b = 1 # the beta a = 0 # iterate over all determinants that must be in the final state for step in range(L-1): # choose first qubit on which D_l and D_{l+1} differ old_det = determinants[step] new_det = determinants[step+1] a = weights[step] # Find first bit of difference different_qubit = 0 while different_qubit <= n: if old_det[different_qubit] != new_det[different_qubit]: break else: different_qubit += 1 if different_qubit == n: raise Exception('Determinants {} and {} are the same.'.format(old_det, new_det)) # Compute the rotation angle # Equation is cos(g) beta_l = alpha_l angle = math.acos(a/b) # print('Step {} angle is {}'.format(step, angle)) # beta_{l+1} is b = b * math.sin(angle) if old_det[different_qubit] == 1: b = -b # print('Flipped beta sign.') # want a controlled-Y rotation, but can do controlled-Z, so map Y basis to Z basis. # 1) first map Y to X (with U1(-pi/2) gate) # 2) X to Z, with Hadamard # 3) apply z-rotation # 4) undo this # --- # circ.u1(-math.pi/2, qubits[different_qubit]) # circ.h(qubits[different_qubit]) # circ.crz(angle, cqub, qubits[different_qubit]) # circ.h(qubits[different_qubit]) # circ.u1(-math.pi/2, qubits[different_qubit]) circ.cu3(2 * angle, 0, 0, cqub, qubits[different_qubit]) # Now must do an n-qubit Toffoli to change the |1> to |0> # but controlled on the |D_l> bitstring flip_all(circ, qubits, old_det) if mode == 'noancilla': # no ancillas circ.mct(qubits, cqub[0], None, mode='noancilla') else: circ.mct(qubits, cqub[0], ancillas, mode='basic') # nToffoliAncillas(circ, qubits, ancillas, cqub) flip_all(circ, qubits, old_det) # undo # if step > 0: # break # If b not same sign as weight, flip sign # if b * weights[step+1]: # circ.z(cqub) # b = -b # Now continue flipping the rest of the bits for i in range(different_qubit+1, n): if old_det[i] != new_det[i]: circ.cx(cqub, qubits[i]) circ.barrier() # Finally check that the sign of the last weight is correct # and set the ancilla to zero. if b * weights[-1] < 0: # must flip sign circ.z(cqub) # Remove the |1> flip_all(circ, qubits, new_det) if mode == 'noancilla': # no ancillas circ.mct(qubits, cqub[0], None, mode='noancilla') else: circ.mct(qubits, cqub[0], ancillas, mode='basic') # nToffoliAncillas(circ, qubits, ancillas, cqub) flip_all(circ, qubits, new_det) # undo return circ def flip_all(circ, tgt, bits): ''' Flips the qubits of tgt where the bit in the bitstring is 0. ''' for i in range(len(bits)): if bits[i] == 0: # flip circ.x(tgt[i]) def nToffoliAncillas(circ, ctrl, anc, tgt): ''' Returns a circuit that implements an n-qubit Toffoli using n ancillas. ''' n = len(ctrl) # compute circ.ccx(ctrl[0], ctrl[1], anc[0]) for i in range(2, n): circ.ccx(ctrl[i], anc[i-2], anc[i-1]) # copy circ.cx(anc[n-2], tgt[0]) # uncompute for i in range(n-1, 1, -1): circ.ccx(ctrl[i], anc[i-2], anc[i-1]) circ.ccx(ctrl[0], ctrl[1], anc[0]) return circ