repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/chriszapri/qiskitDemo
chriszapri
from qiskit import QuantumCircuit, assemble, Aer # Qiskit features imported from qiskit.visualization import plot_bloch_multivector, plot_histogram # For visualization from qiskit.quantum_info import Statevector # Intermediary statevector saving import numpy as np # Numpy math library sim = Aer.get_backend('aer_simulator') # Simulation that this notebook relies on ### For real quantum computer backend, replace Aer.get_backend with backend object of choice # Widgets for value sliders import ipywidgets as widgets from IPython.display import display # Value sliders theta = widgets.FloatSlider( value=0, min=0, max=180, step=0.5, description='θ', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', ) phi = widgets.FloatSlider( value=0, min=0, max=360, step=0.5, description='φ', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', ) display(theta) # Zenith angle in degrees display(phi) # Azimuthal angle in degrees ## Careful! These act as zenith and azimuthal only when applied to |0> statevector in rx(theta), rz(phi) order qc = QuantumCircuit(1) # 1 qubit quantum circuit, every qubits starts at |0> qc.rx(theta.value/180.0*np.pi,0) # Rotation about Bloch vector x-axis qc.rz(phi.value/180.0*np.pi,0) # Rotation about Bloch vector y-axis qc.save_statevector() # Get final statevector after measurement qc.measure_all() # Measurement: collapses the statevector to either |0> or |1> qobj = assemble(qc) # Quantum circuit saved to an object interStateV = sim.run(qobj).result().get_statevector() finalStates = sim.run(qobj).result().get_counts() qc.draw() plot_bloch_multivector(interStateV) # Plot intermediary statevector after two gates on Bloch sphere plot_histogram(finalStates) # Probability of |0> or |1> from measuring above statevector
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb from qiskit import * nshots = 8192 qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main') simulator = Aer.get_backend('qasm_simulator') device = provider.get_backend('ibmq_lima') from qiskit.tools.visualization import plot_histogram from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor def qc_ent_dist(): qc = QuantumCircuit(2, name = 'E dist') qc.h([0]); qc.cx(0, 1) return qc qc_ent_dist_ = qc_ent_dist(); qc_ent_dist_.draw(output = 'mpl') def qc_bb_cb(): qc = QuantumCircuit(2, name = 'BB->CB') qc.cx(0,1); qc.h(0) return qc qc_bb_cb_ = qc_bb_cb(); qc_bb_cb_.draw(output = 'mpl') def qc_teleport(th, ph, lb): qc = QuantumCircuit(3) qc_ent_dist_ = qc_ent_dist(); qc.append(qc_ent_dist_, [1, 2]) # distribuição de emaranhamento qc.barrier() qc.u(th, ph, lb, [0]) # Preparação do estado a ser teletransportado qc.barrier() qc_bb_cb_ = qc_bb_cb(); qc.append(qc_bb_cb_, [0, 1]) # Base de Bell para base computacional qc.barrier() qc.cx(1, 2); qc.cz(0, 2) # infor clássica + unitária de Bob return qc qc_teleport_ = qc_teleport(0.1, 0.5, 0); qc_teleport_.decompose().draw(output = 'mpl') import numpy as np import math th, ph, lb = 0, 0, 0; rho_teo = np.array([[math.cos(th/2)**2, (math.cos(ph)+1j*math.sin(ph))*math.sin(th/2)*math.cos(th/2)], [(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2)*math.cos(th/2), math.sin(th/2)**2]]) qc_teleport_ = qc_teleport(0.1, 0.5, 0) qstc = state_tomography_circuits(qc_teleport_, [2]) # simulação job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots = nshots) qstf = StateTomographyFitter(job.result(), qstc) rho_sim = qstf.fit(method='lstsq') print('rho_teo = ', rho_teo) print('rho_sim = ', rho_sim) # experimento job = qiskit.execute(qstc, backend = device, shots = nshots) job_monitor(job) qstf = StateTomographyFitter(job.result(), qstc) rho_exp = qstf.fit(method = 'lstsq') print('rho_exp = ', rho_exp) F = qiskit.quantum_info.state_fidelity(rho_teo, rho_exp); print('F = ', F) # variar th em cos(th/2)|0>+exp(i*ph)sin(th/2)|1>
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/sebasmos/QuantumVE
sebasmos
API_KEY = "5bd4ecfdc74e6680da7c79998259781431661e5326ae2f88eea95dee8f74b87530ba63fbca8105404de4ffd36e4b484631907acff73c805580928218a5ccf0b3" import qiskit as q from qiskit import IBMQ,schedule import numpy as np import qiskit.pulse as pulse from qiskit.circuit import Parameter %matplotlib inline import sys sys.path.insert(0, '..') # Add qiskit_runtime directory to the path IBMQ.save_account(API_KEY) # Details in: https://qiskit.org/documentation/install.html IBMQ.save_account(API_KEY, overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider("ibm-q") for backend in provider.backends(): try: qubit_count = len(backend.properties().quibits) except: qubit_count = "simulated" print(f"{backend.name()} has {backend.status().pending_jobs} queued and { qubit_count} qubits") from qiskit.tools.monitor import job_monitor backend = provider.get_backend("ibmq_lima") provider = IBMQ.get_provider( hub='ibm-q', group='open', project='main' ) options = { 'backend_name': 'ibmq_qasm_simulator' } runtime_inputs = { # An instance of FeatureMap in # dictionary format used to map # classical data into a quantum # state space. 'feature_map': None, # dict (required) # NxD array of training data, # where N is the number # of samples and D is # the feature dimension. 'data': None, # numpy.ndarray (required) # Nx1 array of +/-1 labels # of the N training samples. 'labels': None, # numpy.ndarray (required) # Initial parameters of the quantum # kernel. If not specified, an # array of randomly generated numbers # is used. 'initial_kernel_parameters': None, # numpy.ndarray # Number of SPSA optimization steps. # Default is 1. 'maxiters': None, # int # Penalty parameter for the soft-margin # support vector machine. Default is # 1. 'C': None, # float # Initial position of virtual qubits # on the physical qubits of # the quantum device. Default is # None. 'initial_layout': None # list or dict } job = provider.runtime.run( program_id='quantum-kernel-alignment', options=options, inputs=runtime_inputs ) # Job id print(job.job_id()) # See job status print(job.status()) # Get results result = job.result()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) es_problem = driver.run() from qiskit_nature.second_q.mappers import JordanWignerMapper mapper = JordanWignerMapper() from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver numpy_solver = NumPyMinimumEigensolver() from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD ansatz = UCCSD( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, initial_state=HartreeFock( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, ), ) vqe_solver = VQE(Estimator(), ansatz, SLSQP()) vqe_solver.initial_point = [0.0] * ansatz.num_parameters from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.circuit.library import TwoLocal tl_circuit = TwoLocal( rotation_blocks=["h", "rx"], entanglement_blocks="cz", entanglement="full", reps=2, parameter_prefix="y", ) another_solver = VQE(Estimator(), tl_circuit, SLSQP()) from qiskit_nature.second_q.algorithms import GroundStateEigensolver calc = GroundStateEigensolver(mapper, vqe_solver) res = calc.solve(es_problem) print(res) calc = GroundStateEigensolver(mapper, numpy_solver) res = calc.solve(es_problem) print(res) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.mappers import DirectMapper from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis([2, 2, 2, 2]) vib_problem = driver.run(basis=basis) vib_problem.hamiltonian.truncation_order = 2 mapper = DirectMapper() solver_without_filter = NumPyMinimumEigensolver() solver_with_filter = NumPyMinimumEigensolver( filter_criterion=vib_problem.get_default_filter_criterion() ) gsc_wo = GroundStateEigensolver(mapper, solver_without_filter) result_wo = gsc_wo.solve(vib_problem) gsc_w = GroundStateEigensolver(mapper, solver_with_filter) result_w = gsc_w.solve(vib_problem) print(result_wo) print("\n\n") print(result_w) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import networkx as nx import dimod import matplotlib.pyplot as plt import dwave_networkx as dnx from dwave.embedding import pegasus import neal, dwave.system # Define target Pegasus Graph M = 16 # Defines number of qubits in Pegasus graph : 24M(M-1) P_M = dnx.pegasus_graph(M, data = True) # allow the use of pegasus indizes # Define source complete graph a = 12*(M-1) # See section 3.1 in Next Generation Topologies White Paper K_a = nx.complete_graph(a) a # Embedding K_a into P_M embedding = pegasus.find_clique_embedding(K_a, target_graph=P_M) """ Alternative: from minorminer import find_embedding # Embedding K_a into P_M timeout = 60 tries = 50 embedding = find_embedding(K_a, P_M, timeout = timeout, tries = tries) """ if embedding: print("Found Embedding") print(f"P_a has : Nodes {P_M.number_of_nodes()} Connections {P_M.number_of_edges()}") from collections import Counter degree_ct = Counter() for node, degree in dict(P_M.degree()).items(): degree_ct[degree] += 1 degree_ct chain_ct = Counter() for node, chainlist in embedding.items(): chain_ct[len(chainlist)] += 1 print(f"The embedding has {len(embedding.keys())} nodes") chain_ct structured_sampler = dimod.StructureComposite(neal.SimulatedAnnealingSampler(), P_M.nodes, P_M.edges) sampler = dwave.system.FixedEmbeddingComposite(structured_sampler, embedding = embedding) num_reads = 500 max_clique_size_avg = 0 for i in range(num_reads): max_clique_size_avg += dnx.clique_number(K_a, sampler=sampler) max_clique_size_avg = max_clique_size_avg / num_reads # to run this line 95 in clique.py (dwave-networkx - algorithms) must be commented out # the decorator checks if sampler is properly implemented can be skipped... print(f'Found {max_clique_size_avg = }. We wanted {a}. So {a - max_clique_size_avg :.4} are missing')
https://github.com/QPower-Research/QPowerAlgo
QPower-Research
# initialization import numpy as np # importing Qiskit from qiskit import QuantumCircuit, transpile from qiskit.primitives import Sampler, Estimator # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw('mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw('mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw('mpl') balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw('mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw('mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) dj_circuit.draw('mpl') dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw('mpl') # use local simulator sampler = Sampler() result = sampler.run(dj_circuit).result() answer = result.quasi_dists[0] plot_histogram(answer) def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw('mpl') result = sampler.run(dj_circuit).result() answer = result.quasi_dists[0] plot_histogram(answer) # from qiskit_ibm_runtime import QiskitRuntimeService # # Save an IBM Quantum account and set it as your default account. # QiskitRuntimeService.save_account(channel="ibm_quantum", token="<Enter Your Token Here>", overwrite=True) # # Load saved credentials # service = QiskitRuntimeService() from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() service.backends() service = QiskitRuntimeService() backend = service.least_busy(operational=True,min_num_qubits=5) print(backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager pm = generate_preset_pass_manager(optimization_level=3, backend=backend,seed_transpiler=11) qc = pm.run(dj_circuit) qc.draw('mpl',idle_wires=False) # Get the results of the computation from qiskit.primitives import BackendSampler sampler = BackendSampler(backend) result = sampler.run(qc).result() answer = result.quasi_dists[0] plot_histogram(answer)
https://github.com/sanori/qiskit-tips
sanori
from qiskit import QuantumCircuit qc = QuantumCircuit(1) qc.x(0) qc.draw('mpl') from qiskit.visualization import visualize_transition visualize_transition(qc) qc = QuantumCircuit(1) qc.x(0) qc.y(0) qc.h(0) qc.draw('mpl') visualize_transition(qc)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) circuit = dag_to_circuit(dag) circuit.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective 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 = 2.126 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_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 european_put = european_put_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, strike_price - x) 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[x <= strike_price]) 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=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_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] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_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)[::-1] print("Exact delta: \t%.4f" % exact_delta) print("Esimated 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/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] for _ in range(100): depths.append( transpile( ghz, backend, layout_method='trivial' # Fixed layout mapped in circuit order ).depth() ) plt.figure(figsize=(8, 6)) plt.hist(depths, align='left', color='#AC557C') plt.xlabel('Depth', fontsize=14) plt.ylabel('Counts', fontsize=14);
https://github.com/noamsgl/IBMAscolaChallenge
noamsgl
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import numpy as np from ipywidgets import interact, interactive, fixed, interact_manual, FloatSlider, Layout import ipywidgets as widgets sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]}) plt.rcParams['figure.figsize'] = [12, 8] # load dataframe filepath = "../datasets/universal_error/DepolOnly/U3_19.csv" df = pd.read_csv(filepath) # reorder columns df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'population', 'p0_0', 'p0_1', 'p1_0', 'p1_1']] # filters labels = ['theta', 'phi', 'lam', 'E'] depol_columns = ['depol_prob'] thermal_columns = ['t1', 't2', 'population'] readout_columns = ['p0_0', 'p0_1', 'p1_0', 'p1_1'] # filtered dataframes ideal_only = df.query('depol_prob == 0 & t1 == inf & t2 == inf & p0_0 == 1 & p1_1 == 1') @interact def show_gates_more_than(theta_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%')), lam_range=widgets.FloatRangeSlider(value=[0, 6.3], min = 0.0, max=2*np.pi, layout=Layout(width='80%')), phi_values=widgets.SelectMultiple(options=ideal_only['phi'].unique(), value=tuple(ideal_only['phi'].unique()))): filtered = ideal_only.loc[(ideal_only['theta'].between(theta_range[0],theta_range[1])) & (ideal_only['lam'].between(lam_range[0],lam_range[1])) & (ideal_only['phi'].isin(phi_values))] # filtered = filtered.loc[filtered[]] sns.scatterplot(x='theta', y='E', hue="lam", data=filtered); depol_only = df.query('p0_0 == 1 & p1_1 == 1 & t1 == inf & t2 == inf')[labels + depol_columns] sns.scatterplot(x=depol_only['theta'], y=depol_only['E']); sns.regplot(x=depol_only['lam'], y=depol_only['E'])
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's inverse gate operation.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, pulse from qiskit.circuit import Clbit from qiskit.circuit.library import RXGate, RYGate from qiskit.test import QiskitTestCase from qiskit.circuit.exceptions import CircuitError from qiskit.extensions.simulator import Snapshot class TestCircuitProperties(QiskitTestCase): """QuantumCircuit properties tests.""" def test_qarg_numpy_int(self): """Test castable to integer args for QuantumCircuit.""" n = np.int64(12) qc1 = QuantumCircuit(n) self.assertEqual(qc1.num_qubits, 12) self.assertEqual(type(qc1), QuantumCircuit) def test_carg_numpy_int(self): """Test castable to integer cargs for QuantumCircuit.""" n = np.int64(12) c1 = ClassicalRegister(n) qc1 = QuantumCircuit(c1) c_regs = qc1.cregs self.assertEqual(c_regs[0], c1) self.assertEqual(type(qc1), QuantumCircuit) def test_carg_numpy_int_2(self): """Test castable to integer cargs for QuantumCircuit.""" qc1 = QuantumCircuit(12, np.int64(12)) self.assertEqual(len(qc1.clbits), 12) self.assertTrue(all(isinstance(bit, Clbit) for bit in qc1.clbits)) self.assertEqual(type(qc1), QuantumCircuit) def test_qarg_numpy_int_exception(self): """Test attempt to pass non-castable arg to QuantumCircuit.""" self.assertRaises(CircuitError, QuantumCircuit, "string") def test_warning_on_noninteger_float(self): """Test warning when passing non-integer float to QuantumCircuit""" self.assertRaises(CircuitError, QuantumCircuit, 2.2) # but an integer float should pass qc = QuantumCircuit(2.0) self.assertEqual(qc.num_qubits, 2) def test_circuit_depth_empty(self): """Test depth of empty circuity""" q = QuantumRegister(5, "q") qc = QuantumCircuit(q) self.assertEqual(qc.depth(), 0) def test_circuit_depth_no_reg(self): """Test depth of no register circuits""" qc = QuantumCircuit() self.assertEqual(qc.depth(), 0) def test_circuit_depth_meas_only(self): """Test depth of measurement only""" q = QuantumRegister(1, "q") c = ClassicalRegister(1, "c") qc = QuantumCircuit(q, c) qc.measure(q, c) self.assertEqual(qc.depth(), 1) def test_circuit_depth_barrier(self): """Make sure barriers do not add to depth""" # ┌───┐ ░ ┌─┐ # q_0: ┤ H ├──■──────────────────░─┤M├──────────── # ├───┤┌─┴─┐ ░ └╥┘┌─┐ # q_1: ┤ H ├┤ X ├──■─────────────░──╫─┤M├───────── # ├───┤└───┘ │ ┌───┐ ░ ║ └╥┘┌─┐ # q_2: ┤ H ├───────┼──┤ X ├──■───░──╫──╫─┤M├────── # ├───┤ │ └─┬─┘┌─┴─┐ ░ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├───────┼────┼──┤ X ├─░──╫──╫──╫─┤M├─── # ├───┤ ┌─┴─┐ │ └───┘ ░ ║ ║ ║ └╥┘┌─┐ # q_4: ┤ H ├─────┤ X ├──■────────░──╫──╫──╫──╫─┤M├ # └───┘ └───┘ ░ ║ ║ ║ ║ └╥┘ # c: 5/═════════════════════════════╩══╩══╩══╩══╩═ # 0 1 2 3 4 q = QuantumRegister(5, "q") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[4]) qc.cx(q[0], q[1]) qc.cx(q[1], q[4]) qc.cx(q[4], q[2]) qc.cx(q[2], q[3]) qc.barrier(q) qc.measure(q, c) self.assertEqual(qc.depth(), 6) def test_circuit_depth_simple(self): """Test depth for simple circuit""" # ┌───┐ # q_0: ┤ H ├──■──────────────────── # └───┘ │ ┌───┐┌─┐ # q_1: ───────┼────────────┤ X ├┤M├ # ┌───┐ │ ┌───┐┌───┐└─┬─┘└╥┘ # q_2: ┤ X ├──┼──┤ X ├┤ X ├──┼───╫─ # └───┘ │ └───┘└───┘ │ ║ # q_3: ───────┼──────────────┼───╫─ # ┌─┴─┐┌───┐ │ ║ # q_4: ─────┤ X ├┤ X ├───────■───╫─ # └───┘└───┘ ║ # c: 1/══════════════════════════╩═ # 0 q = QuantumRegister(5, "q") c = ClassicalRegister(1, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[4]) qc.x(q[2]) qc.x(q[2]) qc.x(q[2]) qc.x(q[4]) qc.cx(q[4], q[1]) qc.measure(q[1], c[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_multi_reg(self): """Test depth for multiple registers""" # ┌───┐ # q1_0: ┤ H ├──■───────────────── # ├───┤┌─┴─┐ # q1_1: ┤ H ├┤ X ├──■──────────── # ├───┤└───┘ │ ┌───┐ # q1_2: ┤ H ├───────┼──┤ X ├──■── # ├───┤ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├───────┼────┼──┤ X ├ # ├───┤ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├─────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q1, q2, c) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_3q_gate(self): """Test depth for 3q gate""" # ┌───┐ # q1_0: ┤ H ├──■────■───────────────── # ├───┤ │ ┌─┴─┐ # q1_1: ┤ H ├──┼──┤ X ├──■──────────── # ├───┤ │ └───┘ │ ┌───┐ # q1_2: ┤ H ├──┼─────────┼──┤ X ├──■── # ├───┤┌─┴─┐ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├┤ X ├───────┼────┼──┤ X ├ # ├───┤└─┬─┘ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├──■───────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q1, q2, c) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.ccx(q2[1], q1[0], q2[0]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.depth(), 6) def test_circuit_depth_conditionals1(self): """Test circuit depth for conditional gates #1.""" # ┌───┐ ┌─┐ # q_0: ┤ H ├──■──┤M├───────────────── # ├───┤┌─┴─┐└╥┘┌─┐ # q_1: ┤ H ├┤ X ├─╫─┤M├────────────── # ├───┤└───┘ ║ └╥┘ ┌───┐ # q_2: ┤ H ├──■───╫──╫──┤ H ├──────── # ├───┤┌─┴─┐ ║ ║ └─╥─┘ ┌───┐ # q_3: ┤ H ├┤ X ├─╫──╫────╫────┤ H ├─ # └───┘└───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌──╨──┐┌──╨──┐ # c: 4/═══════════╩══╩═╡ 0x2 ╞╡ 0x4 ╞ # 0 1 └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[0], q[1]) qc.cx(q[2], q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.h(q[2]).c_if(c, 2) qc.h(q[3]).c_if(c, 4) self.assertEqual(qc.depth(), 5) def test_circuit_depth_conditionals2(self): """Test circuit depth for conditional gates #2.""" # ┌───┐ ┌─┐┌─┐ # q_0: ┤ H ├──■──┤M├┤M├────────────── # ├───┤┌─┴─┐└╥┘└╥┘ # q_1: ┤ H ├┤ X ├─╫──╫─────────────── # ├───┤└───┘ ║ ║ ┌───┐ # q_2: ┤ H ├──■───╫──╫──┤ H ├──────── # ├───┤┌─┴─┐ ║ ║ └─╥─┘ ┌───┐ # q_3: ┤ H ├┤ X ├─╫──╫────╫────┤ H ├─ # └───┘└───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌──╨──┐┌──╨──┐ # c: 4/═══════════╩══╩═╡ 0x2 ╞╡ 0x4 ╞ # 0 0 └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[0], q[1]) qc.cx(q[2], q[3]) qc.measure(q[0], c[0]) qc.measure(q[0], c[0]) qc.h(q[2]).c_if(c, 2) qc.h(q[3]).c_if(c, 4) self.assertEqual(qc.depth(), 6) def test_circuit_depth_conditionals3(self): """Test circuit depth for conditional gates #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───■──────────── # ├───┤└╥┘ │ ┌─┐ # q_1: ┤ H ├─╫────┼───┤M├────── # ├───┤ ║ │ └╥┘┌─┐ # q_2: ┤ H ├─╫────┼────╫─┤M├─── # ├───┤ ║ ┌─┴─┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──┤ X ├──╫──╫─┤M├ # └───┘ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌──╨──┐ ║ ║ ║ # c: 4/══════╩═╡ 0x2 ╞═╩══╩══╩═ # 0 └─────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c, 2) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 4) def test_circuit_depth_bit_conditionals1(self): """Test circuit depth for single bit conditional gates #1.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────────────────────── # ├───┤└╥┘ ┌───┐ # q_1: ┤ H ├─╫───────┤ H ├────────────── # ├───┤ ║ ┌─┐ └─╥─┘ # q_2: ┤ H ├─╫─┤M├─────╫──────────────── # ├───┤ ║ └╥┘ ║ ┌───┐ # q_3: ┤ H ├─╫──╫──────╫────────┤ H ├─── # └───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌────╨────┐┌────╨────┐ # c: 4/══════╩══╩═╡ c_0=0x1 ╞╡ c_2=0x0 ╞ # 0 2 └─────────┘└─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[2], c[2]) qc.h(q[1]).c_if(c[0], True) qc.h(q[3]).c_if(c[2], False) self.assertEqual(qc.depth(), 3) def test_circuit_depth_bit_conditionals2(self): """Test circuit depth for single bit conditional gates #2.""" # ┌───┐┌─┐ » # q_0: ┤ H ├┤M├──────────────────────────────■─────────────────────■─────» # ├───┤└╥┘ ┌───┐ ┌─┴─┐ │ » # q_1: ┤ H ├─╫───────┤ H ├─────────────────┤ X ├───────────────────┼─────» # ├───┤ ║ ┌─┐ └─╥─┘ └─╥─┘ ┌─┴─┐ » # q_2: ┤ H ├─╫─┤M├─────╫─────────────────────╫──────────■────────┤ H ├───» # ├───┤ ║ └╥┘ ║ ┌───┐ ║ ┌─┴─┐ └─╥─┘ » # q_3: ┤ H ├─╫──╫──────╫────────┤ H ├────────╫────────┤ X ├────────╫─────» # └───┘ ║ ║ ║ └─╥─┘ ║ └─╥─┘ ║ » # ║ ║ ┌────╨────┐┌────╨────┐┌────╨────┐┌────╨────┐┌────╨────┐» # c: 4/══════╩══╩═╡ c_1=0x1 ╞╡ c_3=0x1 ╞╡ c_0=0x0 ╞╡ c_2=0x0 ╞╡ c_1=0x1 ╞» # 0 2 └─────────┘└─────────┘└─────────┘└─────────┘└─────────┘» # « # «q_0: ─────────── # « # «q_1: ─────■───── # « │ # «q_2: ─────┼───── # « ┌─┴─┐ # «q_3: ───┤ H ├─── # « └─╥─┘ # « ┌────╨────┐ # «c: 4/╡ c_3=0x1 ╞ # « └─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[2], c[2]) qc.h(q[1]).c_if(c[1], True) qc.h(q[3]).c_if(c[3], True) qc.cx(0, 1).c_if(c[0], False) qc.cx(2, 3).c_if(c[2], False) qc.ch(0, 2).c_if(c[1], True) qc.ch(1, 3).c_if(c[3], True) self.assertEqual(qc.depth(), 4) def test_circuit_depth_bit_conditionals3(self): """Test circuit depth for single bit conditional gates #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├────────────────────────────────────── # ├───┤└╥┘ ┌───┐ ┌─┐ # q_1: ┤ H ├─╫────┤ H ├─────────────────────┤M├────── # ├───┤ ║ └─╥─┘ ┌───┐ └╥┘┌─┐ # q_2: ┤ H ├─╫──────╫──────┤ H ├─────────────╫─┤M├─── # ├───┤ ║ ║ └─╥─┘ ┌───┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──────╫────────╫──────┤ H ├────╫──╫─┤M├ # └───┘ ║ ║ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌────╨────┐┌──╨──┐┌────╨────┐ ║ ║ ║ # c: 4/══════╩═╡ c_0=0x1 ╞╡ 0x2 ╞╡ c_3=0x1 ╞═╩══╩══╩═ # 0 └─────────┘└─────┘└─────────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.h(1).c_if(c[0], True) qc.h(q[2]).c_if(c, 2) qc.h(3).c_if(c[3], True) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 6) def test_circuit_depth_measurements1(self): """Test circuit depth for measurements #1.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 2) def test_circuit_depth_measurements2(self): """Test circuit depth for measurements #2.""" # ┌───┐┌─┐┌─┐┌─┐┌─┐ # q_0: ┤ H ├┤M├┤M├┤M├┤M├ # ├───┤└╥┘└╥┘└╥┘└╥┘ # q_1: ┤ H ├─╫──╫──╫──╫─ # ├───┤ ║ ║ ║ ║ # q_2: ┤ H ├─╫──╫──╫──╫─ # ├───┤ ║ ║ ║ ║ # q_3: ┤ H ├─╫──╫──╫──╫─ # └───┘ ║ ║ ║ ║ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[0], c[1]) qc.measure(q[0], c[2]) qc.measure(q[0], c[3]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_measurements3(self): """Test circuit depth for measurements #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 0 0 0 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[0]) qc.measure(q[2], c[0]) qc.measure(q[3], c[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_barriers1(self): """Test circuit depth for barriers #1.""" # ┌───┐ ░ # q_0: ┤ H ├──■───░─────────── # └───┘┌─┴─┐ ░ # q_1: ─────┤ X ├─░─────────── # └───┘ ░ ┌───┐ # q_2: ───────────░─┤ H ├──■── # ░ └───┘┌─┴─┐ # q_3: ───────────░──────┤ X ├ # ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.barrier(q) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_barriers2(self): """Test circuit depth for barriers #2.""" # ┌───┐ ░ ░ ░ # q_0: ┤ H ├─░───■───░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ # q_1: ──────░─┤ X ├─░───────░────── # ░ └───┘ ░ ┌───┐ ░ # q_2: ──────░───────░─┤ H ├─░───■── # ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░───────░─┤ X ├ # ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.barrier(q) circ.cx(0, 1) circ.barrier(q) circ.h(2) circ.barrier(q) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_barriers3(self): """Test circuit depth for barriers #3.""" # ┌───┐ ░ ░ ░ ░ ░ # q_0: ┤ H ├─░───■───░──░──░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ ░ ░ # q_1: ──────░─┤ X ├─░──░──░───────░────── # ░ └───┘ ░ ░ ░ ┌───┐ ░ # q_2: ──────░───────░──░──░─┤ H ├─░───■── # ░ ░ ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░──░──░───────░─┤ X ├ # ░ ░ ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.barrier(q) circ.cx(0, 1) circ.barrier(q) circ.barrier(q) circ.barrier(q) circ.h(2) circ.barrier(q) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap1(self): """Test circuit depth for snapshots #1.""" # ┌───┐ ░ # q_0: ┤ H ├──■───░─────────── # └───┘┌─┴─┐ ░ # q_1: ─────┤ X ├─░─────────── # └───┘ ░ ┌───┐ # q_2: ───────────░─┤ H ├──■── # ░ └───┘┌─┴─┐ # q_3: ───────────░──────┤ X ├ # ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.append(Snapshot("snap", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap2(self): """Test circuit depth for snapshots #2.""" # ┌───┐ ░ ░ ░ # q_0: ┤ H ├─░───■───░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ # q_1: ──────░─┤ X ├─░───────░────── # ░ └───┘ ░ ┌───┐ ░ # q_2: ──────░───────░─┤ H ├─░───■── # ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░───────░─┤ X ├ # ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) circ.cx(0, 1) circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.append(Snapshot("snap2", num_qubits=4), [0, 1, 2, 3]) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap3(self): """Test circuit depth for snapshots #3.""" # ┌───┐ ░ ░ # q_0: ┤ H ├──■───░──░─────────── # └───┘┌─┴─┐ ░ ░ # q_1: ─────┤ X ├─░──░─────────── # └───┘ ░ ░ ┌───┐ # q_2: ───────────░──░─┤ H ├──■── # ░ ░ └───┘┌─┴─┐ # q_3: ───────────░──░──────┤ X ├ # ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_2qubit(self): """Test finding depth of two-qubit gates only.""" # ┌───┐ # q_0: ┤ H ├──■─────────────────── # └───┘┌─┴─┐┌─────────┐ ┌─┐ # q_1: ─────┤ X ├┤ Rz(0.1) ├─■─┤M├ # ┌───┐└───┘└─────────┘ │ └╥┘ # q_2: ┤ H ├──■──────────────┼──╫─ # └───┘┌─┴─┐ │ ║ # q_3: ─────┤ X ├────────────■──╫─ # └───┘ ║ # c: 1/═════════════════════════╩═ # 0 circ = QuantumCircuit(4, 1) circ.h(0) circ.cx(0, 1) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) self.assertEqual(circ.depth(lambda x: x.operation.num_qubits == 2), 2) def test_circuit_depth_multiqubit_or_conditional(self): """Test finding depth of multi-qubit or conditional gates.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├──■───────────────────────────┤ X ├─── # └───┘ │ ┌─────────┐ ┌─┐ └─╥─┘ # q_1: ───────■──┤ Rz(0.1) ├──────■─┤M├─────╫───── # ┌─┴─┐└──┬───┬──┘ │ └╥┘ ║ # q_2: ─────┤ X ├───┤ H ├─────■───┼──╫──────╫───── # └───┘ └───┘ ┌─┴─┐ │ ║ ║ # q_3: ─────────────────────┤ X ├─■──╫──────╫───── # └───┘ ║ ┌────╨────┐ # c: 1/══════════════════════════════╩═╡ c_0 = T ╞ # 0 └─────────┘ circ = QuantumCircuit(4, 1) circ.h(0) circ.ccx(0, 1, 2) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) circ.x(0).c_if(0, 1) self.assertEqual( circ.depth(lambda x: x.operation.num_qubits >= 2 or x.operation.condition is not None), 4, ) def test_circuit_depth_first_qubit(self): """Test finding depth of gates touching q0 only.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├──■─────┤ T ├───────── # └───┘┌─┴─┐┌──┴───┴──┐ ┌─┐ # q_1: ─────┤ X ├┤ Rz(0.1) ├─■─┤M├ # ┌───┐└───┘└─────────┘ │ └╥┘ # q_2: ┤ H ├──■──────────────┼──╫─ # └───┘┌─┴─┐ │ ║ # q_3: ─────┤ X ├────────────■──╫─ # └───┘ ║ # c: 1/═════════════════════════╩═ # 0 circ = QuantumCircuit(4, 1) circ.h(0) circ.cx(0, 1) circ.t(0) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) self.assertEqual(circ.depth(lambda x: circ.qubits[0] in x.qubits), 3) def test_circuit_size_empty(self): """Circuit.size should return 0 for an empty circuit.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) self.assertEqual(qc.size(), 0) def test_circuit_size_single_qubit_gates(self): """Circuit.size should increment for each added single qubit gate.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) self.assertEqual(qc.size(), 1) qc.h(q[1]) self.assertEqual(qc.size(), 2) def test_circuit_size_2qubit(self): """Circuit.size of only 2-qubit gates.""" size = 3 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.rz(0.1, q[1]) qc.rzz(0.1, q[1], q[2]) self.assertEqual(qc.size(lambda x: x.operation.num_qubits == 2), 2) def test_circuit_size_ignores_barriers_snapshots(self): """Circuit.size should not count barriers or snapshots.""" q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) self.assertEqual(qc.size(), 2) qc.barrier(q) self.assertEqual(qc.size(), 2) qc.append(Snapshot("snapshot_label", num_qubits=4), [0, 1, 2, 3]) self.assertEqual(qc.size(), 2) def test_circuit_count_ops(self): """Test circuit count ops.""" q = QuantumRegister(6, "q") qc = QuantumCircuit(q) qc.h(q) qc.x(q[1]) qc.y(q[2:4]) qc.z(q[3:]) result = qc.count_ops() expected = {"h": 6, "z": 3, "y": 2, "x": 1} self.assertIsInstance(result, dict) self.assertEqual(expected, result) def test_circuit_nonlocal_gates(self): """Test num_nonlocal_gates.""" # ┌───┐ ┌────────┐ # q_0: ┤ H ├───────────────────┤0 ├ # ├───┤ ┌───┐ │ │ # q_1: ┤ H ├───┤ X ├─────────■─┤ ├ # ├───┤ └───┘ │ │ │ # q_2: ┤ H ├─────■───────────X─┤ Iswap ├ # ├───┤ │ ┌───┐ │ │ │ # q_3: ┤ H ├─────┼─────┤ Z ├─X─┤ ├ # ├───┤┌────┴────┐├───┤ │ │ # q_4: ┤ H ├┤ Ry(0.1) ├┤ Z ├───┤1 ├ # ├───┤└──┬───┬──┘└───┘ └───╥────┘ # q_5: ┤ H ├───┤ Z ├───────────────╫───── # └───┘ └───┘ ┌──╨──┐ # c: 2/═════════════════════════╡ 0x2 ╞══ # └─────┘ q = QuantumRegister(6, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q, c) qc.h(q) qc.x(q[1]) qc.cry(0.1, q[2], q[4]) qc.z(q[3:]) qc.cswap(q[1], q[2], q[3]) qc.iswap(q[0], q[4]).c_if(c, 2) result = qc.num_nonlocal_gates() expected = 3 self.assertEqual(expected, result) def test_circuit_nonlocal_gates_no_instruction(self): """Verify num_nunlocal_gates does not include barriers.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4500 n = 3 qc = QuantumCircuit(n) qc.h(range(n)) qc.barrier() self.assertEqual(qc.num_nonlocal_gates(), 0) def test_circuit_connected_components_empty(self): """Verify num_connected_components is width for empty""" q = QuantumRegister(7, "q") qc = QuantumCircuit(q) self.assertEqual(7, qc.num_connected_components()) def test_circuit_connected_components_multi_reg(self): """Test tensor factors works over multi registers""" # ┌───┐ # q1_0: ┤ H ├──■───────────────── # ├───┤┌─┴─┐ # q1_1: ┤ H ├┤ X ├──■──────────── # ├───┤└───┘ │ ┌───┐ # q1_2: ┤ H ├───────┼──┤ X ├──■── # ├───┤ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├───────┼────┼──┤ X ├ # ├───┤ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├─────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_multi_reg2(self): """Test tensor factors works over multi registers #2.""" # q1_0: ──■──────────── # │ # q1_1: ──┼─────────■── # │ ┌───┐ │ # q1_2: ──┼──┤ X ├──┼── # │ └─┬─┘┌─┴─┐ # q2_0: ──┼────■──┤ X ├ # ┌─┴─┐ └───┘ # q2_1: ┤ X ├────────── # └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[1]) qc.cx(q2[0], q1[2]) qc.cx(q1[1], q2[0]) self.assertEqual(qc.num_connected_components(), 2) def test_circuit_connected_components_disconnected(self): """Test tensor factors works with 2q subspaces.""" # q1_0: ──■────────────────────── # │ # q1_1: ──┼────■───────────────── # │ │ # q1_2: ──┼────┼────■──────────── # │ │ │ # q1_3: ──┼────┼────┼────■─────── # │ │ │ │ # q1_4: ──┼────┼────┼────┼────■── # │ │ │ │ ┌─┴─┐ # q2_0: ──┼────┼────┼────┼──┤ X ├ # │ │ │ ┌─┴─┐└───┘ # q2_1: ──┼────┼────┼──┤ X ├───── # │ │ ┌─┴─┐└───┘ # q2_2: ──┼────┼──┤ X ├────────── # │ ┌─┴─┐└───┘ # q2_3: ──┼──┤ X ├─────────────── # ┌─┴─┐└───┘ # q2_4: ┤ X ├──────────────────── # └───┘ q1 = QuantumRegister(5, "q1") q2 = QuantumRegister(5, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[4]) qc.cx(q1[1], q2[3]) qc.cx(q1[2], q2[2]) qc.cx(q1[3], q2[1]) qc.cx(q1[4], q2[0]) self.assertEqual(qc.num_connected_components(), 5) def test_circuit_connected_components_with_clbits(self): """Test tensor components with classical register.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 4) def test_circuit_connected_components_with_cond(self): """Test tensor components with one conditional gate.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───■──────────── # ├───┤└╥┘ │ ┌─┐ # q_1: ┤ H ├─╫────┼───┤M├────── # ├───┤ ║ │ └╥┘┌─┐ # q_2: ┤ H ├─╫────┼────╫─┤M├─── # ├───┤ ║ ┌─┴─┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──┤ X ├──╫──╫─┤M├ # └───┘ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌──╨──┐ ║ ║ ║ # c: 4/══════╩═╡ 0x2 ╞═╩══╩══╩═ # 0 └─────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c, 2) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_with_cond2(self): """Test tensor components with two conditional gates.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├─┤ H ├──────── # ├───┤ └─╥─┘ # q_1: ┤ H ├───╫──────■─── # ├───┤ ║ ┌─┴─┐ # q_2: ┤ H ├───╫────┤ X ├─ # ├───┤ ║ └─╥─┘ # q_3: ┤ H ├───╫──────╫─── # └───┘┌──╨──┐┌──╨──┐ # c: 8/═════╡ 0x0 ╞╡ 0x4 ╞ # └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(2 * size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(0).c_if(c, 0) qc.cx(1, 2).c_if(c, 4) self.assertEqual(qc.num_connected_components(), 2) def test_circuit_connected_components_with_cond3(self): """Test tensor components with three conditional gates and measurements.""" # ┌───┐┌─┐ ┌───┐ # q0_0: ┤ H ├┤M├─┤ H ├────────────────── # ├───┤└╥┘ └─╥─┘ # q0_1: ┤ H ├─╫────╫──────■───────────── # ├───┤ ║ ║ ┌─┴─┐ ┌─┐ # q0_2: ┤ H ├─╫────╫────┤ X ├─┤M├─────── # ├───┤ ║ ║ └─╥─┘ └╥┘ ┌───┐ # q0_3: ┤ H ├─╫────╫──────╫────╫──┤ X ├─ # └───┘ ║ ║ ║ ║ └─╥─┘ # ║ ┌──╨──┐┌──╨──┐ ║ ┌──╨──┐ # c0: 4/══════╩═╡ 0x0 ╞╡ 0x1 ╞═╩═╡ 0x2 ╞ # 0 └─────┘└─────┘ 2 └─────┘ size = 4 q = QuantumRegister(size) c = ClassicalRegister(size) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.h(q[0]).c_if(c, 0) qc.cx(q[1], q[2]).c_if(c, 1) qc.measure(q[2], c[2]) qc.x(q[3]).c_if(c, 2) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_with_bit_cond(self): """Test tensor components with one single bit conditional gate.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────────■──────── # ├───┤└╥┘┌─┐ │ # q_1: ┤ H ├─╫─┤M├────────┼──────── # ├───┤ ║ └╥┘┌─┐ │ # q_2: ┤ H ├─╫──╫─┤M├─────┼──────── # ├───┤ ║ ║ └╥┘ ┌─┴─┐ ┌─┐ # q_3: ┤ H ├─╫──╫──╫────┤ X ├───┤M├ # └───┘ ║ ║ ║ └─╥─┘ └╥┘ # ║ ║ ║ ┌────╨────┐ ║ # c: 4/══════╩══╩══╩═╡ c_0=0x1 ╞═╩═ # 0 1 2 └─────────┘ 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c[0], True) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 3) def test_circuit_connected_components_with_bit_cond2(self): """Test tensor components with two bit conditional gates.""" # ┌───┐ ┌───┐ ┌───┐ # q_0: ┤ H ├───┤ H ├─────────────────┤ X ├─── # ├───┤ └─╥─┘ └─┬─┘ # q_1: ┤ H ├─────╫─────────────────────■───── # ├───┤ ║ ║ # q_2: ┤ H ├─────╫──────────■──────────╫───── # ├───┤ ║ │ ║ # q_3: ┤ H ├─────╫──────────■──────────╫───── # └───┘┌────╨────┐┌────╨────┐┌────╨────┐ # c: 6/═════╡ c_1=0x1 ╞╡ c_0=0x1 ╞╡ c_4=0x0 ╞ # └─────────┘└─────────┘└─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size + 2, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(0).c_if(c[1], True) qc.cx(1, 0).c_if(c[4], False) qc.cz(2, 3).c_if(c[0], True) self.assertEqual(qc.num_connected_components(), 5) def test_circuit_connected_components_with_bit_cond3(self): """Test tensor components with register and bit conditional gates.""" # ┌───┐ ┌───┐ # q0_0: ┤ H ├───┤ H ├─────────────────────── # ├───┤ └─╥─┘ # q0_1: ┤ H ├─────╫─────────■─────────────── # ├───┤ ║ ┌─┴─┐ # q0_2: ┤ H ├─────╫───────┤ X ├───────────── # ├───┤ ║ └─╥─┘ ┌───┐ # q0_3: ┤ H ├─────╫─────────╫──────┤ X ├──── # └───┘ ║ ║ └─╥─┘ # ┌────╨─────┐┌──╨──┐┌────╨─────┐ # c0: 4/═════╡ c0_0=0x1 ╞╡ 0x1 ╞╡ c0_2=0x1 ╞ # └──────────┘└─────┘└──────────┘ size = 4 q = QuantumRegister(size) c = ClassicalRegister(size) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[0]).c_if(c[0], True) qc.cx(q[1], q[2]).c_if(c, 1) qc.x(q[3]).c_if(c[2], True) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_unitary_factors1(self): """Test unitary factors empty circuit.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) self.assertEqual(qc.num_unitary_factors(), 4) def test_circuit_unitary_factors2(self): """Test unitary factors multi qregs""" q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q1, q2, c) self.assertEqual(qc.num_unitary_factors(), 4) def test_circuit_unitary_factors3(self): """Test unitary factors measurements and conditionals.""" # ┌───┐ ┌─┐ # q_0: ┤ H ├────────■──────────■────■──────────■──┤M├─── # ├───┤ │ │ │ ┌─┐ │ └╥┘ # q_1: ┤ H ├──■─────┼─────■────┼────┼──┤M├─────┼───╫──── # ├───┤┌─┴─┐ │ ┌─┴─┐ │ │ └╥┘┌─┐ │ ║ # q_2: ┤ H ├┤ X ├───┼───┤ X ├──┼────┼───╫─┤M├──┼───╫──── # ├───┤└───┘ ┌─┴─┐ └───┘┌─┴─┐┌─┴─┐ ║ └╥┘┌─┴─┐ ║ ┌─┐ # q_3: ┤ H ├──────┤ X ├──────┤ X ├┤ X ├─╫──╫─┤ X ├─╫─┤M├ # └───┘ └─╥─┘ └───┘└───┘ ║ ║ └───┘ ║ └╥┘ # ┌──╨──┐ ║ ║ ║ ║ # c: 4/══════════╡ 0x2 ╞════════════════╩══╩═══════╩══╩═ # └─────┘ 1 2 0 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[1], q[2]) qc.cx(q[1], q[2]) qc.cx(q[0], q[3]).c_if(c, 2) qc.cx(q[0], q[3]) qc.cx(q[0], q[3]) qc.cx(q[0], q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_unitary_factors(), 2) def test_circuit_unitary_factors4(self): """Test unitary factors measurements go to same cbit.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # q_4: ──────╫──╫──╫──╫─ # ║ ║ ║ ║ # c: 5/══════╩══╩══╩══╩═ # 0 0 0 0 size = 5 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[0]) qc.measure(q[2], c[0]) qc.measure(q[3], c[0]) self.assertEqual(qc.num_unitary_factors(), 5) def test_num_qubits_qubitless_circuit(self): """Check output in absence of qubits.""" c_reg = ClassicalRegister(3) circ = QuantumCircuit(c_reg) self.assertEqual(circ.num_qubits, 0) def test_num_qubits_qubitfull_circuit(self): """Check output in presence of qubits""" q_reg = QuantumRegister(4) c_reg = ClassicalRegister(3) circ = QuantumCircuit(q_reg, c_reg) self.assertEqual(circ.num_qubits, 4) def test_num_qubits_registerless_circuit(self): """Check output for circuits with direct argument for qubits.""" circ = QuantumCircuit(5) self.assertEqual(circ.num_qubits, 5) def test_num_qubits_multiple_register_circuit(self): """Check output for circuits with multiple quantum registers.""" q_reg1 = QuantumRegister(5) q_reg2 = QuantumRegister(6) q_reg3 = QuantumRegister(7) circ = QuantumCircuit(q_reg1, q_reg2, q_reg3) self.assertEqual(circ.num_qubits, 18) def test_calibrations_basis_gates(self): """Check if the calibrations for basis gates provided are added correctly.""" circ = QuantumCircuit(2) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) with pulse.build() as q1_y90: pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1)) # Add calibration circ.add_calibration(RXGate(3.14), [0], q0_x180) circ.add_calibration(RYGate(1.57), [1], q1_y90) self.assertEqual(set(circ.calibrations.keys()), {"rx", "ry"}) self.assertEqual(set(circ.calibrations["rx"].keys()), {((0,), (3.14,))}) self.assertEqual(set(circ.calibrations["ry"].keys()), {((1,), (1.57,))}) self.assertEqual( circ.calibrations["rx"][((0,), (3.14,))].instructions, q0_x180.instructions ) self.assertEqual(circ.calibrations["ry"][((1,), (1.57,))].instructions, q1_y90.instructions) def test_calibrations_custom_gates(self): """Check if the calibrations for custom gates with params provided are added correctly.""" circ = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibrations with a custom gate 'rxt' circ.add_calibration("rxt", [0], q0_x180, params=[1.57, 3.14, 4.71]) self.assertEqual(set(circ.calibrations.keys()), {"rxt"}) self.assertEqual(set(circ.calibrations["rxt"].keys()), {((0,), (1.57, 3.14, 4.71))}) self.assertEqual( circ.calibrations["rxt"][((0,), (1.57, 3.14, 4.71))].instructions, q0_x180.instructions ) def test_calibrations_no_params(self): """Check calibrations if the no params is provided with just gate name.""" circ = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) circ.add_calibration("h", [0], q0_x180) self.assertEqual(set(circ.calibrations.keys()), {"h"}) self.assertEqual(set(circ.calibrations["h"].keys()), {((0,), ())}) self.assertEqual(circ.calibrations["h"][((0,), ())].instructions, q0_x180.instructions) def test_has_calibration_for(self): """Test that `has_calibration_for` returns a correct answer.""" qc = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("h", [0], q0_x180) qc.h(0) qc.h(1) self.assertTrue(qc.has_calibration_for(qc.data[0])) self.assertFalse(qc.has_calibration_for(qc.data[1])) def test_has_calibration_for_legacy(self): """Test that `has_calibration_for` returns a correct answer when presented with a legacy 3 tuple.""" qc = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("h", [0], q0_x180) qc.h(0) qc.h(1) self.assertTrue( qc.has_calibration_for( (qc.data[0].operation, list(qc.data[0].qubits), list(qc.data[0].clbits)) ) ) self.assertFalse( qc.has_calibration_for( (qc.data[1].operation, list(qc.data[1].qubits), list(qc.data[1].clbits)) ) ) def test_metadata_copy_does_not_share_state(self): """Verify mutating the metadata of a circuit copy does not impact original.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/6057 qc1 = QuantumCircuit(1) qc1.metadata = {"a": 0} qc2 = qc1.copy() qc2.metadata["a"] = 1000 self.assertEqual(qc1.metadata["a"], 0) def test_metadata_is_dict(self): """Verify setting metadata to None in the constructor results in an empty dict.""" qc = QuantumCircuit(1) metadata1 = qc.metadata self.assertEqual(metadata1, {}) def test_metadata_raises(self): """Test that we must set metadata to a dict.""" qc = QuantumCircuit(1) with self.assertRaises(TypeError): qc.metadata = 1 def test_metdata_deprectation(self): """Test that setting metadata to None emits a deprecation warning.""" qc = QuantumCircuit(1) with self.assertWarns(DeprecationWarning): qc.metadata = None self.assertEqual(qc.metadata, {}) def test_scheduling(self): """Test cannot return schedule information without scheduling.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) with self.assertRaises(AttributeError): # pylint: disable=pointless-statement qc.op_start_times if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can show the phase of each state and use # degrees instead of radians from qiskit.quantum_info import DensityMatrix import numpy as np from qiskit import QuantumCircuit from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) qc.z(1) matrix = DensityMatrix(qc) plot_state_qsphere(matrix, show_state_phases = True, use_degrees = True)
https://github.com/usamisaori/quantum-expressibility-entangling-capability
usamisaori
import numpy as np import qiskit from qiskit import QuantumCircuit import matplotlib.pyplot as plt from qiskit.circuit import QuantumCircuit, Parameter import warnings warnings.filterwarnings('ignore') theta = Parameter("θ") phi = Parameter("φ") lamb = Parameter("λ") def sampleCircuitA(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(layer): for i in range(qubits - 1): circuit.cx(i, i + 1) circuit.cx(qubits - 1, 0) for i in range(qubits - 1): circuit.cx(i, i + 1) circuit.cx(qubits - 1, 0) circuit.barrier() for i in range(qubits): circuit.u3(theta, phi, lamb, i) return circuit circuitA = sampleCircuitA(qubits=4) circuitA.draw(output='mpl') def sampleCircuitB1(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(qubits): circuit.u1(theta, i) for i in range(layer): for j in range(qubits - 1): circuit.cz(j, j + 1) circuit.cz(qubits - 1, 0) circuit.barrier() for j in range(qubits): circuit.u1(theta, j) return circuit def sampleCircuitB2(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(qubits): circuit.u2(phi, lamb, i) for i in range(layer): for j in range(qubits - 1): circuit.cz(j, j + 1) circuit.cz(qubits - 1, 0) circuit.barrier() for j in range(qubits): circuit.u2(phi, lamb, j) return circuit def sampleCircuitB3(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(qubits): circuit.u3(theta, phi, lamb, i) for i in range(layer): for j in range(qubits - 1): circuit.cz(j, j + 1) circuit.cz(qubits - 1, 0) circuit.barrier() for j in range(qubits): circuit.u3(theta, phi, lamb, j) return circuit circuitB1 = sampleCircuitB1(qubits=4) circuitB1.draw(output='mpl') circuitB2 = sampleCircuitB2(qubits=4) circuitB2.draw(output='mpl') circuitB3 = sampleCircuitB3(qubits=4) circuitB3.draw(output='mpl') def sampleCircuitC(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(layer): for j in range(qubits): circuit.ry(theta, j) circuit.crx(theta, qubits - 1, 0) for j in range(qubits - 1, 0, -1): circuit.crx(theta, j - 1, j) circuit.barrier() for j in range(qubits): circuit.ry(theta, j) circuit.crx(theta, 3, 2) circuit.crx(theta, 0, 3) circuit.crx(theta, 1, 0) circuit.crx(theta, 2, 1) return circuit circuitC = sampleCircuitC(qubits=4) circuitC.draw(output='mpl') def sampleCircuitD(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(layer): for j in range(qubits): circuit.rx(theta, j) circuit.rz(theta, j) for j in range(qubits - 1, -1, -1): for k in range(qubits - 1, -1, -1): if j != k: circuit.crx(theta, j, k) circuit.barrier() for j in range(qubits): circuit.rx(theta, j) circuit.rz(theta, j) return circuit circuitD = sampleCircuitD(qubits=4) circuitD.draw(output='mpl') def sampleCircuitE(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(layer): for j in range(qubits): circuit.rx(theta, j) circuit.rz(theta, j) for j in range(1, qubits, 2): circuit.crx(theta, j, j - 1) for j in range(qubits): circuit.rx(theta, j) circuit.rz(theta, j) for j in range(2, qubits, 2): circuit.crx(theta, j, j - 1) return circuit circuitE = sampleCircuitE(qubits=4) circuitE.draw(output='mpl') def sampleCircuitF(layer=1, qubits=4): circuit = QuantumCircuit(qubits) for i in range(layer): for j in range(qubits): circuit.rx(theta, j) circuit.rz(theta, j) circuit.crx(theta, qubits - 1, 0) for j in range(qubits - 1, 0, -1): circuit.crx(theta, j - 1, j) return circuit circuitF = sampleCircuitF(qubits=4) circuitF.draw(output='mpl') def sampleEncoding(qubits): circuit = QuantumCircuit(qubits) for i in range(qubits): circuit.h(i) circuit.ry(theta, i) return circuit circuit = sampleEncoding(4) circuit.draw(output='mpl') # demo: circuit = sampleEncoding(5).compose(sampleCircuitB3(layer=2, qubits=5)) circuit.draw(output='mpl')
https://github.com/JackHidary/quantumcomputingbook
JackHidary
"""키스킷 간단한 예제 프로그램.""" # 키스킷 패키지를 가져오세요. import qiskit # 1개 큐비트를 갖는 양자 레지스터를 생성하세요. qreg = qiskit.QuantumRegister(1, name='qreg') # 1개 큐비트와 연결된 고전 레지스터를 생성하세요. creg = qiskit.ClassicalRegister(1, name='creg') # 위의 두 레지스터들로 구성된 양자 회로를 생성하세요. circ = qiskit.QuantumCircuit(qreg, creg) # NOT연산을 추가하세요. circ.x(qreg[0]) # 측정하기를 추가하세요. circ.measure(qreg, creg) # 회로를 출력합니다. print(circ.draw()) # 양자 회로를 실행할 시뮬레이터 백엔드를 가져옵니다. backend = qiskit.BasicAer.get_backend("qasm_simulator") # 회로를 가져온 백엔드 위에서 실행하고 측정결과를 얻습니다. job = qiskit.execute(circ, backend, shots=10) result = job.result() # 측정결과를 출력합니다. print(result.get_counts())
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 qiskit executors (qiskit_utils.py).""" import numpy as np import pytest from qiskit import QuantumCircuit from qiskit_ibm_runtime.fake_provider import FakeLima from mitiq import MeasurementResult, Observable, PauliString from mitiq.interface.mitiq_qiskit.qiskit_utils import ( compute_expectation_value_on_noisy_backend, execute, execute_with_noise, execute_with_shots, execute_with_shots_and_noise, initialized_depolarizing_noise, sample_bitstrings, ) NOISE = 0.007 ONE_QUBIT_GS_PROJECTOR = np.array([[1, 0], [0, 0]]) TWO_QUBIT_GS_PROJECTOR = np.diag([1, 0, 0, 0]) SHOTS = 1_000 def test_execute(): """Tests the Qiskit wavefunction simulation executor returns appropriate expectation value given an observable. """ circ = QuantumCircuit(1) expected_value = execute(circ, obs=ONE_QUBIT_GS_PROJECTOR) assert expected_value == 1.0 second_circ = QuantumCircuit(1) second_circ.x(0) expected_value = execute(second_circ, obs=ONE_QUBIT_GS_PROJECTOR) assert expected_value == 0.0 def test_execute_with_shots(): """Tests the Qiskit wavefunction sampling simulation executor returns appropriate expectation value given an observable. """ circ = QuantumCircuit(1, 1) expectation_value = execute_with_shots( circuit=circ, obs=ONE_QUBIT_GS_PROJECTOR, shots=SHOTS ) assert expectation_value == 1.0 second_circ = QuantumCircuit(1) second_circ.x(0) expectation_value = execute_with_shots( circuit=second_circ, obs=ONE_QUBIT_GS_PROJECTOR, shots=SHOTS ) assert expectation_value == 0.0 def test_execute_with_depolarizing_noise_single_qubit(): """Tests the noisy sampling executor across increasing levels of single qubit gate noise """ single_qubit_circ = QuantumCircuit(1) # noise model is defined on gates so include the gate to # demonstrate noise single_qubit_circ.z(0) noiseless_exp_value = 1.0 expectation_value = execute_with_noise( circuit=single_qubit_circ, obs=ONE_QUBIT_GS_PROJECTOR, noise_model=initialized_depolarizing_noise(NOISE), ) # anticipate that the expectation value will be less than # the noiseless simulation of the same circuit assert expectation_value < noiseless_exp_value def test_execute_with_depolarizing_noise_two_qubit(): """Tests the noisy sampling executor across increasing levels of two qubit gate noise. """ two_qubit_circ = QuantumCircuit(2) # noise model is defined on gates so include the gate to # demonstrate noise two_qubit_circ.cx(0, 1) noiseless_exp_value = 1.0 expectation_value = execute_with_noise( circuit=two_qubit_circ, obs=TWO_QUBIT_GS_PROJECTOR, noise_model=initialized_depolarizing_noise(NOISE), ) # anticipate that the expectation value will be less than # the noiseless simulation of the same circuit assert expectation_value < noiseless_exp_value def test_execute_with_shots_and_depolarizing_noise_single_qubit(): """Tests the noisy sampling executor across increasing levels of single qubit gate noise. """ single_qubit_circ = QuantumCircuit(1, 1) # noise model is defined on gates so include the gate to # demonstrate noise single_qubit_circ.z(0) noiseless_exp_value = 1.0 expectation_value = execute_with_shots_and_noise( circuit=single_qubit_circ, obs=ONE_QUBIT_GS_PROJECTOR, noise_model=initialized_depolarizing_noise(NOISE), shots=SHOTS, ) # anticipate that the expectation value will be less than # the noiseless simulation of the same circuit assert expectation_value < noiseless_exp_value def test_execute_with_shots_and_depolarizing_noise_two_qubit(): """Tests the noisy sampling executor across increasing levels of two qubit gate noise. """ two_qubit_circ = QuantumCircuit(2, 2) # noise model is defined on gates so include the gate to # demonstrate noise two_qubit_circ.cx(0, 1) noiseless_exp_value = 1.0 expectation_value = execute_with_shots_and_noise( circuit=two_qubit_circ, obs=TWO_QUBIT_GS_PROJECTOR, noise_model=initialized_depolarizing_noise(NOISE), shots=SHOTS, ) # anticipate that the expectation value will be less than # the noiseless simulation of the same circuit assert expectation_value < noiseless_exp_value def test_circuit_is_not_mutated_by_executors(): single_qubit_circ = QuantumCircuit(1, 1) single_qubit_circ.z(0) expected_circuit = single_qubit_circ.copy() execute_with_shots_and_noise( circuit=single_qubit_circ, obs=ONE_QUBIT_GS_PROJECTOR, noise_model=initialized_depolarizing_noise(NOISE), shots=SHOTS, ) assert single_qubit_circ.data == expected_circuit.data assert single_qubit_circ == expected_circuit execute_with_noise( circuit=single_qubit_circ, obs=ONE_QUBIT_GS_PROJECTOR, noise_model=initialized_depolarizing_noise(NOISE), ) assert single_qubit_circ.data == expected_circuit.data assert single_qubit_circ == expected_circuit def test_sample_bitstrings(): """Tests that the function sample_bitstrings returns a valid mitiq.MeasurementResult. """ two_qubit_circ = QuantumCircuit(2, 1) two_qubit_circ.cx(0, 1) two_qubit_circ.measure(0, 0) measurement_result = sample_bitstrings( circuit=two_qubit_circ, backend=None, noise_model=initialized_depolarizing_noise(0), shots=5, ) assert measurement_result.result == [[0], [0], [0], [0], [0]] assert measurement_result.qubit_indices == (0,) def test_sample_bitstrings_with_measure_all(): """Tests that the function sample_bitstrings returns a valid mitiq.MeasurementResult when "measure_all" is True. """ two_qubit_circ = QuantumCircuit(2) two_qubit_circ.cx(0, 1) measurement_result = sample_bitstrings( circuit=two_qubit_circ, backend=None, noise_model=initialized_depolarizing_noise(0), shots=2, measure_all=True, ) assert measurement_result.result == [[0, 0], [0, 0]] assert measurement_result.qubit_indices == (0, 1) assert isinstance(measurement_result, MeasurementResult) def test_sample_bitstrings_with_backend(): """Tests that the function sample_bitstrings returns a valid mitiq.MeasurementResult if a qiskit backend is used. """ two_qubit_circ = QuantumCircuit(2) two_qubit_circ.cx(0, 1) measurement_result = sample_bitstrings( circuit=two_qubit_circ, backend=FakeLima(), shots=5, measure_all=True, ) assert len(measurement_result.result) == 5 assert len(measurement_result.result[0]) == 2 assert measurement_result.qubit_indices == (0, 1) def test_sample_bitstrings_error_message(): """Tests that an error is given backend and nose_model are both None.""" two_qubit_circ = QuantumCircuit(2) two_qubit_circ.cx(0, 1) with pytest.raises(ValueError, match="Either a backend or a noise model"): sample_bitstrings( circuit=two_qubit_circ, shots=5, ) def test_compute_expectation_value_on_noisy_backend_with_noise_model(): """Tests the evaluation of an expectation value assuming a noise model.""" obs = Observable(PauliString("X")) qiskit_circuit = QuantumCircuit(1) qiskit_circuit.h(0) # First we try without noise noiseless_expval = compute_expectation_value_on_noisy_backend( qiskit_circuit, obs, noise_model=initialized_depolarizing_noise(0), ) assert isinstance(noiseless_expval, complex) assert np.isclose(np.imag(noiseless_expval), 0.0) assert np.isclose(np.real(noiseless_expval), 1.0) # Now we try with noise expval = compute_expectation_value_on_noisy_backend( qiskit_circuit, obs, noise_model=initialized_depolarizing_noise(0.01), ) assert isinstance(expval, complex) assert np.isclose(np.imag(expval), 0.0) # With noise the result is non-deterministic assert 0.9 < np.real(expval) < 1.0 def test_compute_expectation_value_on_noisy_backend_with_qiskit_backend(): """Tests the evaluation of an expectation value on a noisy backed""" obs = Observable(PauliString("X")) qiskit_circuit = QuantumCircuit(1) qiskit_circuit.h(0) expval = compute_expectation_value_on_noisy_backend( qiskit_circuit, obs, backend=FakeLima(), ) assert isinstance(expval, complex) assert np.isclose(np.imag(expval), 0.0) # With noise the result is non-deterministic assert 0.9 < np.real(expval) < 1.0
https://github.com/qiskit-community/prototype-quantum-kernel-training
qiskit-community
# pylint: disable=import-error, wrong-import-position # Python imports import os import sys # External imports from pylab import cm from sklearn import metrics import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Qiskit imports from qiskit.visualization import circuit_drawer from qiskit_algorithms.optimizers import SPSA from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer from qiskit_machine_learning.algorithms import QSVC # Put this repository on the Python path and import qkt pkgs module_path = os.path.abspath(os.path.join("../..")) sys.path.append(module_path) from qkt.feature_maps import CovariantFeatureMap from qkt.utils import train_test_split, QKTCallback # Load the dataset and split into train and test sets DATA_FILEPATH = "../../data/dataset_graph7.csv" X_train, y_train, X_test, y_test = train_test_split(DATA_FILEPATH) num_features = np.shape(X_train)[1] entangler_map = [[0, 2], [3, 4], [2, 5], [1, 4], [2, 3], [4, 6]] # Note that [[0,1],[2,3],[4,5],[6,7],[8,9],[1,2],[3,4],[5,6],[7,8]] # is a suitable input for the 10-qubit dataset fm = CovariantFeatureMap( feature_dimension=num_features, entanglement=entangler_map, single_training_parameter=True, ) circuit_drawer(fm) print(fm.training_parameters) # Instantiate quantum kernel quant_kernel = TrainableFidelityQuantumKernel( feature_map=fm, training_parameters=fm.training_parameters ) # Set up the optimizer cb_qkt = QKTCallback() spsa_opt = SPSA( maxiter=5, callback=cb_qkt.callback, learning_rate=0.1, perturbation=0.1 ) # Instantiate a quantum kernel trainer. qkt = QuantumKernelTrainer( quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[0.1] * len(fm.training_parameters), ) # Train the kernel using QKT directly qka_results = qkt.fit(X_train, y_train) optimized_kernel = qka_results.quantum_kernel # Use QSVC for classification qsvc = QSVC(quantum_kernel=optimized_kernel) # Fit the QSVC qsvc.fit(X_train, y_train) # Predict the labels labels_test = qsvc.predict(X_test) # Evaluate the test accuracy accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test) print(f"accuracy test: {accuracy_test}") plot_data = cb_qkt.get_callback_data() # callback data K = optimized_kernel.evaluate( X_train ) # kernel matrix evaluated on the training samples plt.rcParams["font.size"] = 20 fig, ax = plt.subplots(1, 2, figsize=(14, 5)) ax[0].plot( [i + 1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c="k", marker="o" ) ax[0].set_xlabel("Iterations") ax[0].set_ylabel("Loss") ax[1].imshow(K, cmap=cm.get_cmap("bwr", 20)) ax[1].axis("off") fig.tight_layout() plt.show() #import qiskit.tools.jupyter # #%qiskit_version_table #%qiskit_copyright
https://github.com/acfilok96/Quantum-Computation
acfilok96
import qiskit from qiskit import * print(qiskit.__version__) %matplotlib inline from qiskit.tools.visualization import plot_histogram from ibm_quantum_widgets import draw_circuit circuit = QuantumCircuit(2,2) circuit circuit.draw(output='mpl') circuit.x(0) circuit.draw(output='mpl') circuit.h(0) circuit.draw(output='mpl') circuit.cx(0,1) circuit.draw(output='mpl') circuit.measure([0,1],[1,1]) circuit.draw(output='mpl') draw_circuit(circuit) simulator = Aer.get_backend('qasm_simulator') simulator job = execute(circuit, backend=simulator, shots=1024) job result = job.result() result counts = result.get_counts() counts plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from sklearn.datasets import load_iris iris_data = load_iris() print(iris_data.DESCR) features = iris_data.data labels = iris_data.target from sklearn.preprocessing import MinMaxScaler features = MinMaxScaler().fit_transform(features) import pandas as pd import seaborn as sns df = pd.DataFrame(iris_data.data, columns=iris_data.feature_names) df["class"] = pd.Series(iris_data.target) sns.pairplot(df, hue="class", palette="tab10") from sklearn.model_selection import train_test_split from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=0.8, random_state=algorithm_globals.random_seed ) from sklearn.svm import SVC svc = SVC() _ = svc.fit(train_features, train_labels) # suppress printing the return value train_score_c4 = svc.score(train_features, train_labels) test_score_c4 = svc.score(test_features, test_labels) print(f"Classical SVC on the training dataset: {train_score_c4:.2f}") print(f"Classical SVC on the test dataset: {test_score_c4:.2f}") from qiskit.circuit.library import ZZFeatureMap num_features = features.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) feature_map.decompose().draw(output="mpl", fold=20) from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=num_features, reps=3) ansatz.decompose().draw(output="mpl", fold=20) from qiskit.algorithms.optimizers import COBYLA optimizer = COBYLA(maxiter=100) from qiskit.primitives import Sampler sampler = Sampler() from matplotlib import pyplot as plt from IPython.display import clear_output objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() import time from qiskit_machine_learning.algorithms.classifiers import VQC vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q4 = vqc.score(train_features, train_labels) test_score_q4 = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}") print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}") from sklearn.decomposition import PCA features = PCA(n_components=2).fit_transform(features) plt.rcParams["figure.figsize"] = (6, 6) sns.scatterplot(x=features[:, 0], y=features[:, 1], hue=labels, palette="tab10") train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=0.8, random_state=algorithm_globals.random_seed ) svc.fit(train_features, train_labels) train_score_c2 = svc.score(train_features, train_labels) test_score_c2 = svc.score(test_features, test_labels) print(f"Classical SVC on the training dataset: {train_score_c2:.2f}") print(f"Classical SVC on the test dataset: {test_score_c2:.2f}") num_features = features.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) ansatz = RealAmplitudes(num_qubits=num_features, reps=3) optimizer = COBYLA(maxiter=40) vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] # make the objective function plot look nicer. plt.rcParams["figure.figsize"] = (12, 6) start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q2_ra = vqc.score(train_features, train_labels) test_score_q2_ra = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset using RealAmplitudes: {train_score_q2_ra:.2f}") print(f"Quantum VQC on the test dataset using RealAmplitudes: {test_score_q2_ra:.2f}") from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=num_features, reps=3) optimizer = COBYLA(maxiter=40) vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q2_eff = vqc.score(train_features, train_labels) test_score_q2_eff = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset using EfficientSU2: {train_score_q2_eff:.2f}") print(f"Quantum VQC on the test dataset using EfficientSU2: {test_score_q2_eff:.2f}") print(f"Model | Test Score | Train Score") print(f"SVC, 4 features | {train_score_c4:10.2f} | {test_score_c4:10.2f}") print(f"VQC, 4 features, RealAmplitudes | {train_score_q4:10.2f} | {test_score_q4:10.2f}") print(f"----------------------------------------------------------") print(f"SVC, 2 features | {train_score_c2:10.2f} | {test_score_c2:10.2f}") print(f"VQC, 2 features, RealAmplitudes | {train_score_q2_ra:10.2f} | {test_score_q2_ra:10.2f}") print(f"VQC, 2 features, EfficientSU2 | {train_score_q2_eff:10.2f} | {test_score_q2_eff:10.2f}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/quantumyatra/quantum_computing
quantumyatra
import numpy as np from sklearn.datasets.samples_generator import make_blobs from qiskit.aqua.utils import split_dataset_to_data_and_labels from sklearn import svm from utility import breast_cancer_pca from matplotlib import pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 n = 2 # number of principal components kept training_dataset_size = 20 testing_dataset_size = 10 sample_Total, training_input, test_input, class_labels = breast_cancer_pca(training_dataset_size, testing_dataset_size, n) data_train, _ = split_dataset_to_data_and_labels(training_input) data_test, _ = split_dataset_to_data_and_labels(test_input) print (f"data_train[0].shape: {data_train[0].shape}" ) print (f"data_train[1].shape: {data_train[1].shape}" ) # We use the function of scikit learn to generate linearly separable blobs centers = [(2.5,0),(0,2.5)] x, y = make_blobs(n_samples=100, centers=centers, n_features=2,random_state=0,cluster_std=0.5) fig,ax=plt.subplots(1,2,figsize=(12,4)) ax[0].scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1]) ax[0].set_title('Breast Cancer dataset'); ax[1].scatter(x[:,0],x[:,1],c=y) ax[1].set_title('Blobs linearly separable'); plt.scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1]) plt.title('Breast Cancer dataset'); model= svm.LinearSVC() model.fit(data_train[0], data_train[1]) #small utility function # some utility functions def make_meshgrid(x, y, h=.02): x_min, x_max = x.min() - 1, x.max() + 1 y_min, y_max = y.min() - 1, y.max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) return xx, yy def plot_contours(ax, clf, xx, yy, **params): Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) out = ax.contourf(xx, yy, Z, **params) return out accuracy_train = model.score(data_train[0], data_train[1]) accuracy_test = model.score(data_test[0], data_test[1]) X0, X1 = data_train[0][:, 0], data_train[0][:, 1] xx, yy = make_meshgrid(X0, X1) Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) fig,ax=plt.subplots(1,2,figsize=(15,5)) ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm) ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1]) ax[0].set_title('Accuracy on the training set: '+str(accuracy_train)); ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm) ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1]) ax[1].set_title('Accuracy on the test set: '+str(accuracy_test)); clf = svm.SVC(gamma = 'scale') clf.fit(data_train[0], data_train[1]); accuracy_train = clf.score(data_train[0], data_train[1]) accuracy_test = clf.score(data_test[0], data_test[1]) X0, X1 = data_train[0][:, 0], data_train[0][:, 1] xx, yy = make_meshgrid(X0, X1) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) fig,ax=plt.subplots(1,2,figsize=(15,5)) ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm) ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1]) ax[0].set_title('Accuracy on the training set: '+str(accuracy_train)); ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm) ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1]) ax[1].set_title('Accuracy on the test set: '+str(accuracy_test)); import qiskit as qk # Creating Qubits q = qk.QuantumRegister(2) # Creating Classical Bits c = qk.ClassicalRegister(2) circuit = qk.QuantumCircuit(q, c) circuit.draw('mpl') # Initialize empty circuit circuit = qk.QuantumCircuit(q, c) # Hadamard Gate on the first Qubit circuit.h(q[0]) # CNOT Gate on the first and second Qubits circuit.cx(q[0], q[1]) # Measuring the Qubits circuit.measure(q, c) circuit.draw('mpl') # Using Qiskit Aer's Qasm Simulator: Define where do you want to run the simulation. simulator = qk.BasicAer.get_backend('qasm_simulator') # Simulating the circuit using the simulator to get the result job = qk.execute(circuit, simulator, shots=100) result = job.result() # Getting the aggregated binary outcomes of the circuit. counts = result.get_counts(circuit) print (counts) from qiskit.aqua.components.feature_maps import SecondOrderExpansion feature_map = SecondOrderExpansion(feature_dimension=2, depth=1) x = np.array([0.6, 0.3]) #feature_map.construct_circuit(x) print(feature_map.construct_circuit(x)) from qiskit.aqua.algorithms import QSVM qsvm = QSVM(feature_map, training_input, test_input) #from qiskit.aqua import run_algorithm, QuantumInstance from qiskit.aqua import algorithm, QuantumInstance from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=10598, seed_transpiler=10598) result = qsvm.run(quantum_instance) plt.scatter(training_input['Benign'][:,0], training_input['Benign'][:,1]) plt.scatter(training_input['Malignant'][:,0], training_input['Malignant'][:,1]) length_data = len(training_input['Benign']) + len(training_input['Malignant']) print("size training set: {}".format(length_data)) #print("Matrix dimension: {}".format(result['kernel_matrix_training'].shape)) print("testing success ratio: ", result['testing_accuracy']) test_set = np.concatenate((test_input['Benign'], test_input['Malignant'])) y_test = qsvm.predict(test_set, quantum_instance) plt.scatter(test_set[:, 0], test_set[:,1], c=y_test) plt.show() plt.scatter(test_input['Benign'][:,0], test_input['Benign'][:,1]) plt.scatter(test_input['Malignant'][:,0], test_input['Malignant'][:,1]) plt.show()
https://github.com/Interlin-q/diskit
Interlin-q
import os from qiskit import * import qiskit.tools.visualization as qt from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi import matplotlib.pyplot as plt %matplotlib inline qreg_q = QuantumRegister(2, 'q') creg_c = ClassicalRegister(2, 'c') circuits = [] for i in range(0, 4): circuits.append(QuantumCircuit(qreg_q, creg_c)) circuits[0].reset(qreg_q[0]) circuits[0].reset(qreg_q[1]) circuits[0].cx(qreg_q[0], qreg_q[1]) circuits[0].measure(qreg_q[0], creg_c[0]) circuits[0].measure(qreg_q[1], creg_c[1]) circuits[0].draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result00 = execute(circuits[0], backend = simulator, shots = 1).result() counts00 = result00.get_counts() print(counts00) qt.plot_histogram(counts00, title="Histogram with the evaluating of |00> state under CNOT transformation") circuits[1].reset(qreg_q[0]) circuits[1].x(qreg_q[1]) circuits[1].cx(qreg_q[0], qreg_q[1]) circuits[1].measure(qreg_q[0], creg_c[0]) circuits[1].measure(qreg_q[1], creg_c[1]) circuits[1].draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result01 = execute(circuits[1], backend = simulator, shots = 1).result() counts01 = result01.get_counts() print(counts01) qt.plot_histogram(counts01, title="Histogram with the evaluating of |01> state under CNOT transformation") circuits[2].x(qreg_q[0]) circuits[2].reset(qreg_q[1]) circuits[2].cx(qreg_q[0], qreg_q[1]) circuits[2].measure(qreg_q[0], creg_c[0]) circuits[2].measure(qreg_q[1], creg_c[1]) circuits[2].draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result10 = execute(circuits[2], backend = simulator, shots = 1).result() counts10 = result10.get_counts() print(counts10) qt.plot_histogram(counts10, title="Histogram with the evaluating of |10> state under CNOT transformation") circuits[3].x(qreg_q[0]) circuits[3].x(qreg_q[1]) circuits[3].cx(qreg_q[0], qreg_q[1]) circuits[3].measure(qreg_q[0], creg_c[0]) circuits[3].measure(qreg_q[1], creg_c[1]) circuits[3].draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result11 = execute(circuits[3], backend = simulator, shots = 1).result() counts11 = result11.get_counts() print(counts11) qt.plot_histogram(counts11, title="Histogram with the evaluating of |11> state under CNOT transformation")
https://github.com/suvoooo/Qubits-Qiskit
suvoooo
# !pip3 install qiskit import qiskit as q import matplotlib.pyplot as plt import numpy as np def build_circ(num_qbits, num_cbits): qr = q.QuantumRegister(num_qbits) cr = q.ClassicalRegister(num_cbits) final_circ = q.QuantumCircuit(qr, cr) return final_circ, qr, cr def h_gates(qcirc, a, b): # 2 inputs and h gates in parallel qcirc.h(a) qcirc.h(b) hadamard_front, qr, cr = build_circ(2, 2) h_gates(hadamard_front, qr[0], qr[1]) hadamard_front.draw() ### define the oracle for state 00 hadamard_front.x(qr[0]) hadamard_front.x(qr[1]) hadamard_front.cz(qr[0], qr[1]) hadamard_front.x(qr[0]) hadamard_front.x(qr[1]) hadamard_front.draw() ### We apply the steps below to create the reflection about the original superposition state ### 1. Apply H to each qubit in the register. ### 2. A conditional phase shift of −1 to every computational basis state except |0⟩. ### This can be represented by the unitary operation −O_0, as O_0 represents the conditional phase shift to |0⟩ only. ### 3. Apply H to each qubit in the register. ### reflection about state |0> can be thought of as circuit below ### apply z gate to both qubits, then add a cz gate def reflection_psi(qcirc, a, b): h_gates(qcirc, a, b) qcirc.z(a) qcirc.z(b) qcirc.cz(a, b) h_gates(qcirc, a, b) reflection_psi_circ, qr_rf, cr_rf = build_circ(2, 2) reflection_psi(reflection_psi_circ, qr_rf[0], qr_rf[1]) reflection_psi_circ.draw() # !pip3 install pylatexenc complete_circuit = hadamard_front.compose(reflection_psi_circ) for n in range(2): complete_circuit.measure(n, n) complete_circuit.draw('mpl', filename=path+'Grover_Algo_00.png', scale=1.1) statevec_sim = q.Aer.get_backend("statevector_simulator") def statevec_exec(circ): statevec = q.execute(circ, backend=statevec_sim).result().get_statevector() return statevec complete_circuit_statevec = statevec_exec(complete_circuit) q.visualization.plot_bloch_multivector(complete_circuit_statevec) qasm_sim = q.Aer.get_backend('qasm_simulator') counts = q.execute(complete_circuit, backend=qasm_sim, shots=1024).result().get_counts() q.visualization.plot_histogram([counts], legend=['output']) from qiskit import IBMQ IBMQ.save_account('find your token') IBMQ.load_account() provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') # check which computer has 0 jobs on queue job = q.execute(complete_circuit, backend=qcomp) q_result = job.result() q.visualization.plot_histogram(q_result.get_counts(complete_circuit)) check_circ = q.QuantumCircuit(2) # check_circ.iswap(0, 1) check_circ.rz(np.pi/2, 0) check_circ.rz(np.pi/2, 1) check_circ.cz(0, 1) check_circ.rz(np.pi/2, 0) check_circ.rz(np.pi/2, 1) qasm_sim = q.Aer.get_backend('unitary_simulator') # we need to make a copy of the circuit with the 'save_statevector' # instruction to run on the Aer simulator job = q.execute(check_circ, qasm_sim) result = job.result() print(result.get_unitary(check_circ, decimals=2)) from google.colab import drive drive.mount('/content/drive') path = '/content/drive/My Drive/' ### let's use the oracke above to check whether we get 00 state as solution or not hadamard_front_check, qr_check, cr_check = build_circ(2, 2) h_gates(hadamard_front_check, qr_check[0], qr_check[1]) #### oracle with rz and cz gate hadamard_front_check.rz(np.pi/2, qr_check[0]) hadamard_front_check.rz(np.pi/2, qr_check[1]) hadamard_front_check.cz(qr_check[0], qr_check[1]) hadamard_front_check.rz(np.pi/2, qr_check[0]) hadamard_front_check.rz(np.pi/2, qr_check[1]) #### reflection_psi_circ_check, qr_rf_check, cr_rf_check = build_circ(2, 2) reflection_psi(reflection_psi_circ_check, qr_rf_check[0], qr_rf_check[1]) complete_circuit_check = hadamard_front_check.compose(reflection_psi_circ_check) for n in range(2): complete_circuit_check.measure(n, n) style = {'backgroundcolor': 'lavender', 'dpi':200, 'subfontsize':10} complete_circuit_check.draw('mpl', scale=0.8, style=style, filename=path+'Grover_Algo_RZ_00.png') qasm_sim = q.Aer.get_backend('qasm_simulator') counts = q.execute(complete_circuit_check, backend=qasm_sim, shots=1024).result().get_counts() q.visualization.plot_histogram([counts], legend=['output']) provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') # check which computer has 0 jobs on queue job = q.execute(complete_circuit_check, backend=qcomp) q_result = job.result() q.visualization.plot_histogram(q_result.get_counts(complete_circuit_check))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # 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. """Decorator for using with Qiskit unit tests.""" import functools import os import sys import unittest from .utils import Path from .http_recorder import http_recorder from .testing_options import get_test_options def is_aer_provider_available(): """Check if the C++ simulator can be instantiated. Returns: bool: True if simulator executable is available """ # TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC if sys.platform == 'darwin': return False try: import qiskit.providers.aer # pylint: disable=unused-import except ImportError: return False return True def requires_aer_provider(test_item): """Decorator that skips test if qiskit aer provider is not available Args: test_item (callable): function or class to be decorated. Returns: callable: the decorated function. """ reason = 'Aer provider not found, skipping test' return unittest.skipIf(not is_aer_provider_available(), reason)(test_item) def slow_test(func): """Decorator that signals that the test takes minutes to run. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(*args, **kwargs): skip_slow = not TEST_OPTIONS['run_slow'] if skip_slow: raise unittest.SkipTest('Skipping slow tests') return func(*args, **kwargs) return _wrapper def _get_credentials(test_object, test_options): """Finds the credentials for a specific test and options. Args: test_object (QiskitTestCase): The test object asking for credentials test_options (dict): Options after QISKIT_TESTS was parsed by get_test_options. Returns: Credentials: set of credentials Raises: ImportError: if the Exception: when the credential could not be set and they are needed for that set of options """ try: from qiskit.providers.ibmq.credentials import (Credentials, discover_credentials) except ImportError: raise ImportError('qiskit-ibmq-provider could not be found, and is ' 'required for mocking or executing online tests.') dummy_credentials = Credentials( 'dummyapiusersloginWithTokenid01', 'https://quantumexperience.ng.bluemix.net/api') if test_options['mock_online']: return dummy_credentials if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''): # Special case: instead of using the standard credentials mechanism, # load them from different environment variables. This assumes they # will always be in place, as is used by the Travis setup. return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL')) else: # Attempt to read the standard credentials. discovered_credentials = discover_credentials() if discovered_credentials: # Decide which credentials to use for testing. if len(discovered_credentials) > 1: try: # Attempt to use QE credentials. return discovered_credentials[dummy_credentials.unique_id()] except KeyError: pass # Use the first available credentials. return list(discovered_credentials.values())[0] # No user credentials were found. if test_options['rec']: raise Exception('Could not locate valid credentials. You need them for ' 'recording tests against the remote API.') test_object.log.warning('No user credentials were detected. ' 'Running with mocked data.') test_options['mock_online'] = True return dummy_credentials def requires_qe_access(func): """Decorator that signals that the test uses the online API: It involves: * determines if the test should be skipped by checking environment variables. * if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is set, it reads the credentials from an alternative set of environment variables. * if the test is not skipped, it reads `qe_token` and `qe_url` from `Qconfig.py`, environment variables or qiskitrc. * if the test is not skipped, it appends `qe_token` and `qe_url` as arguments to the test function. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(self, *args, **kwargs): if TEST_OPTIONS['skip_online']: raise unittest.SkipTest('Skipping online tests') credentials = _get_credentials(self, TEST_OPTIONS) self.using_ibmq_credentials = credentials.is_ibmq() kwargs.update({'qe_token': credentials.token, 'qe_url': credentials.url}) decorated_func = func if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']: # For recording or for replaying existing cassettes, the test # should be decorated with @use_cassette. vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none' decorated_func = http_recorder( vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func) return decorated_func(self, *args, **kwargs) return _wrapper TEST_OPTIONS = get_test_options()
https://github.com/quantumyatra/quantum_computing
quantumyatra
import numpy as np import pylab as plt from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.draw('mpl') # UROT_2 gate to x1 depending on x2 from numpy import pi qc.cu1(pi/2, 1, 2) # CROT from qubit 1 to qubit 2 hence the angle: pi/2^{2-1} qc.draw('mpl') qc.cu1(pi/4, 0, 2) # CROT from qubit 2 to qubit 0 hence the angle: pi/2^{2-0} qc.draw('mpl') # Repeat the process for 2 and 3 qc.h(1) # Hadamard on 1 qc.cu1(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 hence the angle: pi/2^{1-0} qc.h(0) # Hadamard on 0 qc.draw('mpl') # Now swap the qubit 0 and 2 to complete QFT. [NOT CLEAR TO ME] qc.swap(0,2) qc.draw('mpl') def qft_rotations(ckt, n): if n == 0: return ckt n -= 1 ckt.h(n) for qubit in range(n): ckt.cu1( pi/2**(n-qubit), qubit, n ) qc = QuantumCircuit(4) qft_rotations(qc,4) qc.draw('mpl') def qft_rotations(ckt, n): if n == 0: return ckt n -= 1 ckt.h(n) for qubit in range(n): ckt.cu1( pi/2**(n-qubit), qubit, n ) qft_rotations(ckt, n) qc = QuantumCircuit(4) qft_rotations(qc,4) qc.draw('mpl') from qiskit_textbook.widgets import scalable_circuit scalable_circuit(qft_rotations) def swap_registers(ckt, n): for qubit in range(n//2): ckt.swap(qubit, n-qubit-1) return ckt def qft(ckt, n): qft_rotations(ckt, n) swap_registers(ckt, n) return ckt qc = QuantumCircuit(4) qft(qc, 4) qc.draw('mpl') print (f"5 and it's binary: {bin(5)}") #bin(9) qc = QuantumCircuit(3) qc.x(0) qc.x(2) qc.draw('mpl') backend = Aer.get_backend('statevector_simulator') sv = execute(qc, backend=backend).result().get_statevector() plot_bloch_multivector(sv) print (sv.real) qft(qc, 3) qc.draw('mpl') sv = execute(qc, backend=backend).result().get_statevector() plot_bloch_multivector(sv) print ('The statevectors are:\n', sv.round(1)) print ('Angle subtended by each states (as a factor of pi):\n',(np.angle(sv)/np.pi).round(2)) # 10 qc = QuantumCircuit(2) qc.x(0) qc.draw('mpl') backend = Aer.get_backend('statevector_simulator') sv = execute(qc, backend=backend).result().get_statevector() plot_bloch_multivector(sv) qft(qc, 2) qc.draw('mpl') backend = Aer.get_backend('statevector_simulator') sv = execute(qc, backend=backend).result().get_statevector() plot_bloch_multivector(sv) def inverse_qft(circuit, n): """Does the inverse QFT on the first n qubits in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(n), n) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits in our existing circuit circuit.append(invqft_circ, circuit.qubits[:n]) # use .decompose() which allows us to see the individual gates return circuit.decompose() nqubits = 3 number = 6 qc = QuantumCircuit(nqubits) for qubit in range(nqubits): qc.h(qubit) qc.u1(number*pi/4,0) qc.u1(number*pi/2,1) qc.u1(number*pi,2) qc.draw('mpl') backend = Aer.get_backend("statevector_simulator") sv = execute(qc, backend=backend).result().get_statevector() plot_bloch_multivector(sv) print ('The statevectors are:\n', sv.round(1)) print ('Angle subtended by each states (as a factor of pi):\n',(np.angle(sv)/np.pi).round(2)) qc = inverse_qft(qc,nqubits) qc.measure_all() qc.draw('mpl') backend = Aer.get_backend("qasm_simulator") shots = 2048 job = execute(qc, backend=backend, shots=shots, optimization_level=3) counts = job.result().get_counts() plot_histogram(counts) from qiskit import circuit, quantum_info num_qubits = 6 qft = circuit.library.QFT(num_qubits, approximation_degree=0, insert_barriers=False) qft.draw('mpl', fold=500, reverse_bits = True) # Plot classical vs. quantum Fourier transform, for all basis states.. # By linearity of Fourier transform, all states map correctly. # The difference in height is due to normalization in quantum. plt.figure(figsize=(16,16)) for i, basis_state in enumerate([0, 1, 2, 3]): state = quantum_info.Statevector.from_int(basis_state, dims=2**num_qubits) #print (state) classical_fourier = np.fft.ifft(state.data) # classical library function quantum_fourier = state.evolve(qft).data # quantum library (simulation via quantum_info) width = 0.5 #fig.suptitle('Input State: ' + str(basis_state), fontsize=16) plt.subplot(4,2, 2*i+1) plt.title('state: %1i real'%i) plt.bar(np.arange(2**num_qubits)-width/2., classical_fourier.real, width, label='classical') plt.bar(np.arange(2**num_qubits)+width/2., quantum_fourier.real, width, label='quantum') plt.legend(frameon=False) plt.subplot(4,2, 2*i+2) plt.title('state: %1i Imaginary part'%i) plt.bar(np.arange(2**num_qubits)-width/2., classical_fourier.imag, width, label='classical') plt.bar(np.arange(2**num_qubits)+width/2., quantum_fourier.imag, width, label='quantum') plt.legend(frameon=False) import matplotlib.pyplot as plt Nt = 256 t = np.arange(Nt) fft = np.fft.fft(np.sin(t)) ifft = np.fft.ifft(np.sin(t)) freq = np.fft.fftfreq(Nt) plt.figure(figsize=(16,4)) plt.subplot(121) plt.title('real') plt.plot(freq, fft.real, '-o', label='fft (real)') plt.plot(freq, Nt*ifft.real, '-o', label='Nt * ifft (real)') plt.legend(fontsize='large') plt.xlabel('frequency', fontsize='large') plt.subplot(122) plt.title('imag') plt.plot(freq, fft.imag, '-o', label='fft (imag)') plt.plot(freq, Nt*ifft.imag, '-o', label='Nt * ifft (imag)') plt.legend(fontsize='large') plt.xlabel('frequency', fontsize='large') plt.show() from qiskit import circuit, quantum_info num_qubits = 6 qft = circuit.library.QFT(num_qubits, insert_barriers=False) qft.draw('mpl', fold=500, reverse_bits = True) basis_state = 2 state = quantum_info.Statevector.from_int(basis_state, dims=2**num_qubits) quantum_fourier = state.evolve(qft).data width = 0.5 plt.subplot(121) plt.bar(np.arange(2**num_qubits)+width/2., quantum_fourier.real, width, label='real') plt.subplot(122) plt.bar(np.arange(2**num_qubits)+width/2., quantum_fourier.imag, width, label='imag') plt.legend(frameon=False)
https://github.com/pratjz/IBM-Qiskit-Certification-Exam-Prep
pratjz
import numpy as np from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.quantum_info import Statevector # Load your IBM Quantum account(s) provider = IBMQ.load_account() # here we create the four bell states # This statevector object do not need simulation to get the information bell1 = QuantumCircuit(2) bell1.h(0) bell1.cx(0,1) sv = Statevector.from_label('00') # here .from_label() is used, we could also use .from_int(), for more check docs! sv_ev1 = sv.evolve(bell1) # then evolve this initial state through the circuit, What is evolve ? sv_ev1.draw('latex') bell2 = QuantumCircuit(2) bell2.h(0) bell2.cx(0,1) bell2.z(0) sv_ev2 = sv.evolve(bell2) sv_ev2.draw('latex') bell3 = QuantumCircuit(2) bell3.h(0) bell3.x(1) bell3.cx(0,1) sv_ev3 = sv.evolve(bell3) sv_ev3.draw('latex') bell4 = QuantumCircuit(2) bell4.h(0) bell4.x(1) bell4.cx(0,1) bell4.z(1) sv_ev4 = sv.evolve(bell4) sv_ev4.draw('latex') # the Statevector object can be drawn on a qsphere # with the .draw() method by changing the call from 'latex' to 'qsphere' sv_ev1.draw('qsphere') sv_ev2.draw('qsphere') sv_ev3.draw('qsphere') sv_ev4.draw('qsphere') # What is GHZ State ? (Greenberger–Horne–Zeilinger state) ghz = QuantumCircuit(3) ghz.h(0) ghz.cx([0,0],[1,2]) # using []s notation we can apply 2 cx gates in same statement ghz.draw() # or use 'mpl' or 'text', leaving blank default uses mpl sv = Statevector.from_int(0,2**3) # what is from _int ? sv_ev = sv.evolve(ghz) sv_ev.draw('latex') sv = Statevector.from_label('000') #doing the same with .from_label() sv_ev = sv.evolve(ghz) sv_ev.draw('latex') sv_ev.draw('qsphere') # we can also plot hinton directly!, What is Hinton ? is similar to city graph but flat & represent matrix density distribution sv_ev.draw('hinton') # BasicAer has 3 main simulators: # 1-'qasm_simulator' # 2-'statevector_simulator' # 3-'unitary_simulator' BasicAer.backends() backend_sv = BasicAer.get_backend('statevector_simulator') # get the statevector_simulator job = execute(ghz, backend_sv, shots=1024) # specify job, which circuit to execute and how many times/shots result = job.result() # results from the job sv_ev2 = result.get_statevector(ghz) # get statevector from the result # this way of getting the statevector does not have the method '.draw()' in order to visualize you need plotting functions directly plot_state_city(sv_ev2, title='my_city',color=['red','blue']) plot_state_hinton(sv_ev2, title='my_hinton') plot_state_qsphere(sv_ev2) plot_state_paulivec(sv_ev2) plot_bloch_multivector(sv_ev2) # The multivector as we saw plots a state coming from a circuit # whereas the bloch_vector needs coordinate specifications the coordinates can be cartesian, or spherical plot_bloch_vector([1,1,1]) # here for [x,y,z]; x=Tr[Xρ] and similar for y and z q_a = QuantumRegister(1,'q_a') q_b = QuantumRegister(1, 'q_b') qc = QuantumCircuit(q_a, q_b) qc.h(0) qc.z(0) qc.draw() qc.measure_all() # measure_all() will create a barrier & classical register for a circuit that doesn't have one #NOTE: this also means, if your circuit already had a classical register, it would create another one! #so measure_all() is usually used for circuits that do not have a classical register qasm_sim = BasicAer.get_backend('qasm_simulator') result = execute(qc, qasm_sim).result() counts = result.get_counts() plot_histogram(counts) meas = QuantumCircuit(3,3) meas.barrier() meas.measure([0,1,2],[0,1,2]) # here we measure respective quantum registers into respective classical registers, the ordering is important! meas.draw('mpl') circ = meas.compose(ghz,range(3),front=True) # compose to extend the circuit the front=True gets GHZ before the measure circ.draw() backend = BasicAer.get_backend('qasm_simulator') circ = transpile(circ, backend) job = backend.run(circ, shots=1024) #notice here we use .run instead of execute most usually we employ 'execute' though because it is more flexible result = job.result() counts = result.get_counts() print(counts) #now, we could also just print our counts in an un-spectacular way compared to plotting the histograms! import qiskit.tools.jupyter #%qiskit_job_watcher #this creates a pop up of your jobs from qiskit.tools import job_monitor #quito = provider.get_backend('ibmq_quito') # to call a real backend QPU, we use 'provider' object instead of BasicAer you can check which backends are available for you too! #job = execute(circ, quito) #job_monitor(job) #result = job.result() #counts = result.get_counts() #plot_histogram(counts) from qiskit.quantum_info import Operator U = Operator(ghz) # we can turn our ghz circuit from above into an operator! U.data # this is very similar to getting the Statevector object directly, # if needed we can round all these numbers by using np.around and specify how many decimals we want np.around(U.data, 3) backend_uni = BasicAer.get_backend('unitary_simulator') U = execute(ghz,backend_uni).result().get_unitary(decimals=3) U from qiskit_textbook.tools import array_to_latex array_to_latex(U, pretext="\\text{Statevector} = ") q = QuantumRegister(2,'q_reg') c = ClassicalRegister(2,'c_reg') qc = QuantumCircuit(q,c) qc.h(q[0:2]) qc.cx(q[0], q[1]) qc.draw('mpl') U_bell = Operator(qc) np.around(U_bell.data,3) # rounding decimal places a = 1/np.sqrt(3) # we can define a state ourselves, we could also get a random state, desired_state = [a,np.sqrt(1-a**2)] # state is defined such that it is a valid one! q_reg = QuantumRegister(2,'q') qc = QuantumCircuit(q_reg) qc.initialize(desired_state,1) qc.draw('mpl') decomp = qc.decompose() decomp.draw() #but what is this |0> ? It is a reset! Meaning that initialize as a whole is NOT a Gate! #It is irreversible because it has a reset! check docs for more c_reg = ClassicalRegister(1,'c') meas = QuantumCircuit(q_reg, c_reg) meas.measure(0,0) circ = meas.compose(qc, range(2), front=True) circ.draw('mpl') #squaring the amplitudes alpha_squared = 0.577 ** 2 beta_squared = 0.816 ** 2 print(alpha_squared, beta_squared, alpha_squared+beta_squared) back = BasicAer.get_backend('qasm_simulator') job = execute(circ, back, shots=1000) counts = job.result().get_counts() print(counts) plot_histogram(counts,title='test_title') # state_fidelity back_sv = BasicAer.get_backend('statevector_simulator') result = execute(qc, back_sv).result() qc_sv = result.get_statevector(qc) qc_sv from qiskit.quantum_info import state_fidelity state_fidelity(desired_state, qc_sv) # this compares the statevector we got from simulation vs the state we wanted to initialize # here we see they match perfectly, as expected because it is a simulator on actual hardware they may not have matched so perfectly # average_gate_fidelity from qiskit.circuit.library import XGate from qiskit.quantum_info import Operator, average_gate_fidelity, process_fidelity op_a = Operator(XGate()) op_b = np.exp(1j / 2) * op_a # these differ only by a phase so the gate and process fidelities are expected to be 1 a = average_gate_fidelity(op_a,op_b) a # process_fidelity b = process_fidelity(op_a, op_b) a == b back_uni = BasicAer.get_backend('unitary_simulator') job = execute(qc, back_uni) result = job.result() U_qc = result.get_unitary(decimals=3) U_qc qc = QuantumCircuit(3) qc.mct([0,1],2) # What does it do ? qc.cx(0,2) qc.h(1) qc.z(0) qc.draw('mpl') qc_gate = qc.to_gate() qc_gate.name = 'my_gate_ϕ' # optionally we can give it a name! circ = QuantumCircuit(3) circ.append(qc_gate, [0,1,2]) circ.draw('mpl') circ_decomp = circ.decompose() # decompose it back! circ_decomp.draw('mpl') from qiskit.circuit.library import HGate ch = HGate().control(2) # specify how many controls we want qc = QuantumCircuit(3) qc.append(ch, [0,1,2]) # the [a,b,c] correspond to controls and target respectively qc.draw('mpl') # another little more complex example circ = QuantumCircuit(4) circ.h(range(2)) circ.cx(0,1) circ.cx(0,3) circ.crz(np.pi/2,0,2) my_gate = circ.to_gate().control(2) #this qc = QuantumCircuit(6) qc.append(my_gate, [0,5,1,2,3,4]) qc.draw() circ = qc.decompose() circ.draw() # Again simpler circuit! qc = QuantumCircuit(3) qc.mct([0,1],2) qc.cx(0,2) qc.h(1) qc.z(0) trans = transpile(qc, basis_gates = ['u3','cx','s']) trans.draw('mpl') q_a = QuantumRegister(2, 'q_a') q_b = QuantumRegister(4, 'q_b') c_a = ClassicalRegister(2,'c_a') c_b = ClassicalRegister(4,'c_b') qc = QuantumCircuit(q_a, q_b,c_a, c_b) qc.x(0) qc.h(1) qc.cx(0,1) qc.barrier() qc.cz(0,1) qc.cx(0,4) qc.h(3) qc.h(4) qc.barrier() qc.x(3) qc.ccx(0,3,5) qc.barrier() qc.measure(q_a, c_a) qc.measure(q_b, c_b) qc.draw() #Now look at all the crazy things we can do with the .draw() method! Who would've imagined! qc.draw(reverse_bits=True, plot_barriers=False,scale=0.5, style = {'backgroundcolor': 'gray'}) from qiskit.tools.visualization import circuit_drawer circuit_drawer(qc, output='text') # circuit_drawer is also there qc = QuantumCircuit(3,3) qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.barrier() qc.measure([0,1,2],[0,1,2]) qc.draw() qasm_str = qc.qasm() #returning a qasm string, THIS SIMPLE qasm_str circ = QuantumCircuit.from_qasm_str(qasm_str) #you got to be kidding! circ.draw() #you can also read a file directly with .from_qasm_file('path'), check out docs! #what do you think the circuit depth of this picture is? #hint: not 2 circ = QuantumCircuit(3) circ.h(0) circ.x(1) circ.h(2) circ.draw() circ.depth() qc =QuantumCircuit(3,3) qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.h(2) qc.barrier() qc.cx(2,0) qc.barrier() print(qc.depth()) # Barriers do not count for depth qiskit.__version__ %qiskit_version_table # # this will give all the information on all the hardware available # import qiskit.tools.jupyter # %qiskit_backend_overview from qiskit.visualization import plot_gate_map backend = provider.get_backend('ibmq_manila') plot_gate_map(backend, plot_directed=True) plot_error_map(backend) qc = QuantumCircuit(3) qc.measure_all() sim = BasicAer.get_backend('qasm_simulator') couple_map = [[0,1],[1,2]] # specify some linear connection job = execute(qc, sim, shots=1000, coupling_map=couple_map) result = job.result() counts = result.get_counts() print(counts) #Answer is D qc.draw('mpl',filename='test.png') ## check the folder where the notebook is located qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector.from_instruction(qc) state.draw('latex') plot_state_paulivec(state, color=['midnightblue','green','orange'],title="New PauliVec plot") qc = QuantumCircuit(3) qc.x(0) qc.y(1) qc.cx(0,1) qc.ccx(0,1,2) backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result() output = result.get_statevector() output.draw('latex') plot_state_paulivec(output, title = 'MY CITY', color = ['red','green']) # 21) Which one of the following output results are correct when the given code is executed? q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q,c) qc.h(q[0]) qc.x(q[1]) qc.h(q[1]) sim = Aer.get_backend('unitary_simulator') job = execute(qc, sim) unitary = job.result().get_unitary() unitary from qiskit_textbook.tools import array_to_latex array_to_latex(unitary, pretext="\\text{Statevector} = ") # 22) Which one of the following output results are correct when the given code is executed? qc = QuantumCircuit(2,2) qc.h(0) qc.z(1) backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) statevector = job.result().get_statevector() print(statevector) array_to_latex(statevector, pretext="\\text{Statevector} = ") # 37) When executed, which one of the following codes produces the given image? qc = QuantumCircuit(2,2) qc.x(0) qc.h(1) qc.crz(np.pi,0,1) qc.measure([0,1],[0,1]) #qc.draw('mpl') #qc.draw() #qc.draw('latex') qc.draw('text') # 42) Which one of the following codes will create a random circuit? from qiskit.circuit.random import random_circuit #circ = random_circuit(2, 2, reset=reset, measure=True) #circ = random_circuit(2, 2,conditional=True, measurement=measure) circ = random_circuit(2, 2, measure=False) #circ = random_circuit(2, 2, max_operands=True) circ.draw() # 17) Which operator is the O/P of the following circuit? qc = QuantumCircuit(2) qc.x(0) qc.cx(0,1) op = Operator(qc) array_to_latex(op, pretext="\\text{Operator} = ") # Q Given this code, which two inserted code fragments result in the state vector represented by this Bloch sphere? qc = QuantumCircuit(1,1) qc.h(0) #qc.rx(np.pi/4,0) #qc.ry(-np.pi/4,0) qc.rz(-np.pi/4,0) #qc.ry(np.pi,0) simulator = Aer.get_backend('statevector_simulator') job = execute(qc, simulator) result = job.result() outputstate = result.get_statevector(qc) plot_bloch_multivector(outputstate) qc = QuantumCircuit(2) qc.mct([0],1) qc.draw() q = QuantumRegister(1) qc = QuantumCircuit(q) qc.x(q[0]) qc.h(q[0]) style = {'backgroundcolor': 'lightgreen'} qc.draw(output='mpl', style=style, scale=3.5, plot_barriers=False, reverse_bits=False) qc = QuantumCircuit(1) qc.h(0) qc.x(0) qc.ry(np.pi/2,0) qc.rx(-np.pi/2,0) qc.x(0) simulator = Aer.get_backend('statevector_simulator') job = execute(qc, simulator) result = job.result() outputstate = result.get_statevector(qc) plot_bloch_multivector(outputstate) qc = QuantumCircuit(3) qc.x(0) qc.y(1) qc.cx(0,1) qc.ccx(0,1,2) backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result() output = result.get_statevector() plot_state_paulivec(output, title = 'MY CITY', color = ['red','green']) array_to_latex(output, pretext="\\text{Operator} = ") output qc = QuantumCircuit(3,3) qc.h(0) qc.cx(0,1) qc.cry(np.pi,0,1) qc.barrier() qc.cx(0,2) qc.rz(np.pi/3,1) qc.ccx(0,2,1) qc.measure_all() qc.draw('mpl', scale=1, reverse_bits=True) qc = QuantumCircuit(2,2) qc.x(0) qc.cx(1,0) qc.h(1) qc.measure(range(2),range(2)) backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend).result() counts1 = result.get_counts() counts2 = result.get_counts() legend = counts1, counts2 plot_histogram([counts1,counts2], legend=legend, title = 'HISTOGRAM') qc = QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.cx(1,0) backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend, shots=1024) result = job.result() sv = result.get_statevector(qc) plot_state_qsphere(sv) qc = QuantumCircuit(3,3) qc.h(0) qc.x(1) qc.ccx(0,2,1) qc.measure(range(3),range(3)) backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend).result() counts = result.get_counts() plot_histogram(counts) q = QuantumRegister(2,'hello') c = QuantumRegister(2,'hey') qc = QuantumCircuit(q,c) qc.x([0,1]) qc.h(3) qc.cz(0,1) qc.draw() qc= QuantumCircuit(1,1) pi = np.pi qc.z(0) #4 qc.t(0) #5 qc.sdg(0) #2 qc.h(0) #3 qc.x(0) #1 simulator = Aer.get_backend('statevector_simulator') job = execute(qc, simulator) result = job.result() outputstate = result.get_statevector(qc) plot_bloch_multivector(outputstate) array_to_latex(statevector, pretext="\\text{Operator} = ") cords=[1,1,1] #cords=[0,1,0] #cords=[1,0,0] #cords=[0,0,1] plot_bloch_vector(cords, title='Image') q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.x(q[1]) qc.h(q[1]) sim = Aer.get_backend('unitary_simulator') job = execute(qc, sim) unitary = job.result().get_unitary() array_to_latex(unitary, pretext="\\text{Operator} = ") qc = QuantumCircuit(3,3) qc.h(0) qc.cx(0,1) qc.cry(pi,0,1) qc.barrier() qc.cx(0,2) qc.rz(pi/3,1) qc.ccx(0,2,1) qc.measure_all() qc.draw('mpl', scale=1, reverse_bits=True)
https://github.com/MonitSharma/qiskit-projects
MonitSharma
from functions import Knapsack,KnapsackNewApproach,new_eq_optimal_knapsack,get_figure_knapsack,eval_constrains_knapsack from functions import mapping_cost from qiskit.algorithms import QAOA, NumPyMinimumEigensolver from qiskit_optimization.algorithms import CplexOptimizer, MinimumEigenOptimizer from qiskit.algorithms.optimizers import COBYLA import numpy as np import matplotlib.pyplot as plt from qiskit import Aer backend = Aer.get_backend("qasm_simulator") cases = 10 solutions_new = {} optimal_new = [] ratio_new = []; new =[] result_classical = []; result_qaoa_new = [] np.random.seed(15) num_items = 4 # number of items max_weight = 15 # max weight of a bin values = np.random.randint(1, max_weight, num_items) # Randomly picking the item weight weights = []#np.random.randint(1, max_weight, num_items) # Randomly picking the item weight qaoa = MinimumEigenOptimizer(QAOA(optimizer=COBYLA(maxiter=100), reps=4, quantum_instance=backend)) for i in range(cases): # Testing 5 different randomly selected configurations of the problem print(f"----------- Case {i+1} -------------") weights.append(np.random.randint(1, max_weight, num_items)) # Randomly picking the item weight qubo_classical, qp = Knapsack(values, weights[i], max_weight) qubo_new = KnapsackNewApproach(values, weights[i], max_weight, alpha=1) result_classical.append(CplexOptimizer().solve(qubo_classical)) optimal_new.append(new_eq_optimal_knapsack(qubo_new, qubo_classical)) result_qaoa_new.append(CplexOptimizer().solve(qubo_new)) solutions_new = result_qaoa_new[-1].fval check_const = eval_constrains_knapsack(qp, result_qaoa_new[-1]) print(check_const) for i in range(len(result_classical)): fig = get_figure_knapsack(result_classical[i].x,values, weights[i], max_weight, title=f"-------Case {i+1}-----") fig = get_figure_knapsack(result_qaoa_new[i].x,values, weights[i], max_weight, title="New") n = 20 alpha = np.linspace(0, 2*np.pi, n) beta = np.linspace(0, np.pi, n) map_cost = mapping_cost(alpha, beta, qubo_new) plt.figure(figsize=(10,10)) plt.imshow(map_cost) plt.xticks([0,9,19], ["0", r"$\pi/2$", r"$\pi$"]) plt.yticks([0,9,19], ["0", r"$\pi$", r"2$\pi$"]) plt.xlabel(r"$\beta$", fontsize=22) plt.ylabel(r"$\alpha$", fontsize=22)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc)
https://github.com/qiskit-community/qopt-best-practices
qiskit-community
import json import networkx as nx graph_file = "data/graph_2layers_0seed.json" data = json.load(open(graph_file, "r")) graph = nx.from_edgelist(data["Original graph"]) nx.draw(graph, with_labels=True) num_qubits = len(graph.nodes) print(num_qubits) from qopt_best_practices.utils import build_max_cut_paulis, build_max_cut_graph original_hamiltonian = build_max_cut_paulis(graph) print(original_hamiltonian) original_graph = build_max_cut_graph(original_hamiltonian) nx.draw(original_graph, with_labels=True) from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import SwapStrategy swap_strategy = SwapStrategy.from_line([i for i in range(num_qubits)]) from qopt_best_practices.sat_mapping import SATMapper sm = SATMapper() remapped_g, sat_map, min_sat_layers = sm.remap_graph_with_sat( graph=graph, swap_strategy=swap_strategy ) print("Map from old to new edges: ", sat_map) print("Min SAT layers:", min_sat_layers) nx.draw(remapped_g, with_labels=True) from qopt_best_practices.utils import build_max_cut_paulis from qiskit.quantum_info import SparsePauliOp pauli_list = build_max_cut_paulis(remapped_g) print(pauli_list) # define a qiskit SparsePauliOp from the list of paulis qaoa_hamiltonian = SparsePauliOp.from_list(pauli_list) print(qaoa_hamiltonian) from qopt_best_practices.swap_strategies import create_qaoa_swap_circuit theta = [1, 1, 0, 1] # we define the edge_coloring map so that RZZGates are positioned next to SWAP gates to exploit CX cancellations edge_coloring = {(idx, idx + 1): (idx + 1) % 2 for idx in range(qaoa_hamiltonian.num_qubits)} qaoa_circ = create_qaoa_swap_circuit(qaoa_hamiltonian, swap_strategy, edge_coloring, qaoa_layers=2) qaoa_circ.draw("mpl") qaoa_circ.decompose(reps=2).draw("mpl") # SIMULATED FAKE BACKEND --> BackendSampler from qiskit_ibm_runtime.fake_provider import FakeGuadalupe from qiskit.primitives import BackendSampler backend = FakeGuadalupe() sampler = BackendSampler(backend=backend, skip_transpilation=True) ## UNCOMMENT TO RUN ON: ## REAL BACKEND --> Sampler from qiskit_ibm_runtime # from qiskit_ibm_runtime import Sampler, Options, QiskitRuntimeService # service = QiskitRuntimeService(channel='ibm_quantum') # backend = service.get_backend('Guadalupe') # options = Options() # options.transpiler.skip_transpilation = True # sampler = Sampler(backend=backend, options=options) from qopt_best_practices.qubit_selection import BackendEvaluator path_finder = BackendEvaluator(backend) # the Backend Evaluator accepts custom subset definitions and metrics, # but defaults to finding the line with the best fidelity path, fidelity, num_subsets = path_finder.evaluate(num_qubits) print("Best path: ", path) print("Best path fidelity", fidelity) print("Num. evaluated paths", num_subsets) from qiskit.transpiler import Layout initial_layout = Layout.from_intlist(path, qaoa_circ.qregs[0]) # needs qaoa_circ from qiskit.transpiler import CouplingMap, PassManager from qiskit.transpiler.passes import ( FullAncillaAllocation, EnlargeWithAncilla, ApplyLayout, SetLayout, ) from qiskit import transpile basis_gates = ["rz", "sx", "x", "cx"] backend_cmap = CouplingMap(backend.configuration().coupling_map) pass_manager_post = PassManager( [ SetLayout(initial_layout), FullAncillaAllocation(backend_cmap), EnlargeWithAncilla(), ApplyLayout(), ] ) # Map to initial_layout and finally enlarge with ancilla. qaoa_circ = pass_manager_post.run(qaoa_circ) # Now transpile to sx, rz, x, cx basis qaoa_circ = transpile(qaoa_circ, basis_gates=basis_gates) qaoa_circ.draw("mpl", idle_wires=False) from qopt_best_practices.cost_function import evaluate_sparse_pauli def cost_func_sampler(params, ansatz, hamiltonian, sampler): job = sampler.run(ansatz, params) sampler_result = job.result() sampled = sampler_result.quasi_dists[0] # a dictionary containing: {state: (measurement probability, value)} evaluated = { state: (probability, evaluate_sparse_pauli(state, hamiltonian)) for state, probability in sampled.items() } result = sum(probability * value for probability, value in evaluated.values()) return result import numpy as np # TQA initialization parameters dt = 0.75 p = 2 # 2 qaoa layers grid = np.arange(1, p + 1) - 0.5 init_params = np.concatenate((1 - grid * dt / p, grid * dt / p)) print(init_params) from scipy.optimize import minimize result = minimize( cost_func_sampler, init_params, args=(qaoa_circ, qaoa_hamiltonian, sampler), method="COBYLA", ) print(result) # auxiliary functions to sample most likely bitstring def to_bitstring(integer, num_bits): result = np.binary_repr(integer, width=num_bits) return [int(digit) for digit in result] def sample_most_likely_bitstring(state_vector, num_bits): values = list(state_vector.values()) most_likely = np.argmax(np.abs(values)) most_likely_bitstring = to_bitstring(most_likely, num_bits) most_likely_bitstring.reverse() return np.asarray(most_likely_bitstring) qc = qaoa_circ.assign_parameters(result.x) samp_dist = sampler.run(qc, shots=int(1e4)).result().quasi_dists[0] best_result = sample_most_likely_bitstring(samp_dist, len(graph)) print(best_result) import matplotlib.pyplot as plt import networkx as nx # auxiliary function to plot graphs def plot_result(G, x): colors = ["r" if i == 0 else "b" for i in x] pos, default_axes = nx.spring_layout(G), plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.8, pos=pos) plot_result(graph, best_result)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors=scale_factors, fac_type="lin") target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/codigoscupom/QuantumAlgs
codigoscupom
## Programming Quantum Computers ## by Eric Johnston, Nic Harrigan and Mercedes Gimeno-Segovia ## O'Reilly Media ## ## More samples like this can be found at http://oreilly-qc.github.io ## This sample generates a single random bit. from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer import math ## Uncomment the next line to see diagrams when running in a notebook #%matplotlib inline ## Example 2-1: Random bit # Set up the program reg = QuantumRegister(1, name='reg') reg_c = ClassicalRegister(1, name='regc') qc = QuantumCircuit(reg, reg_c) qc.reset(reg) # write the value 0 qc.h(reg) # put it into a superposition of 0 and 1 result = qc.measure(reg, reg_c) # read the result as a digital bit backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() print('result: ', result) counts = result.get_counts(qc) print('counts:',counts) # outputstate = result.get_statevector(qc, decimals=3) # print(outputstate) # qc.draw() # draw the circuit
https://github.com/iremsener/Quantum-Programming-Algorithms-with-Qiskit
iremsener
from qiskit import * %matplotlib inline circuit = QuantumCircuit(2,2) #quantum_register = QuantumRegister(2) #classical_register = ClassicalRegister(2) #circuit = QuantumCircuit(quantum_register,classical_register) circuit.draw() circuit.h(0) circuit.draw() circuit.cx(0,1) # 0-> control qubit, 1-> target qubit circuit.measure([0,1],[0,1]) circuit.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(circuit,backend=simulator).result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) from qiskit.tools.visualization import plot_bloch_multivector from qiskit.visualization import plot_histogram import math # identification of simulators qasm_simulator = Aer.get_backend('qasm_simulator') statevector_simulator = Aer.get_backend('statevector_simulator') # We run our circuit in the simulators we define using a single function. def run_on_simulators(circuit): statevec_job = execute(circuit, backend=statevector_simulator) result = statevec_job.result() statevec = result.get_statevector() num_qubits = circuit.num_qubits circuit.measure([i for i in range(num_qubits)], [i for i in range(num_qubits)]) qasm_job = execute(circuit, backend=qasm_simulator, shots=1024).result() counts = qasm_job.get_counts() return statevec, counts circuit = QuantumCircuit(2,2) statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) # Qubit 0 enters superposition state with hadamard circuit.h(0) statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) circuit = QuantumCircuit(2,2) circuit.h(0) circuit.cx(0,1) # Controlled-X (CX) statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) plot_histogram([counts]) circuit = QuantumCircuit(2,2) circuit.rx(math.pi/4, 0) # rx() , performs rotation on the X axis. circuit.rx(math.pi / 2, 1) # rx() , performs rotation on the X axis. statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) circuit = QuantumCircuit(2,2) circuit.ry(math.pi/4, 0) # ry() , performs rotation on the Y axis. circuit.ry(math.pi / 2, 1) # ry() , performs rotation on the Y axis. statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) circuit = QuantumCircuit(1,1) circuit.h(0) statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) circuit = QuantumCircuit(1,1) circuit.h(0) circuit.z(0) # Z Gate statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) plot_histogram([counts]) circuit = QuantumCircuit(3,3) circuit.x(0) # optional, we want to transfer state 1 in this example circuit.barrier() circuit.h(1) circuit.cx(1,2) circuit.barrier() circuit.draw() circuit.cx(0,1) circuit.h(0) circuit.barrier() circuit.draw() circuit.measure([0, 1], [0, 1]) circuit.barrier() circuit.draw() circuit.cx(1, 2) circuit.cz(0, 2) # Controlled-Z (CZ) Gate circuit.measure([2], [2]) circuit.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1024).result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) secretNumber = '10101010100' circuit = QuantumCircuit(len(secretNumber)+1,len(secretNumber)) circuit.h(range(len(secretNumber))) circuit.x(len(secretNumber)) circuit.h(len(secretNumber)) circuit.barrier() for index, one in enumerate(reversed(secretNumber)): print(f"index{index} is {one}") if one == "1": circuit.cx(index,len(secretNumber)) circuit.barrier() circuit.h(range(len(secretNumber))) circuit.barrier() circuit.measure(range(len(secretNumber)),range(len(secretNumber))) circuit.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1).result() counts = result.get_counts() print(counts) plot_histogram([counts]) circuit = QuantumCircuit(2,1) circuit.h(0) circuit.x(1) circuit.h(1) circuit.barrier() circuit.draw() circuit.cx(0,1) circuit.barrier() circuit.h(0) circuit.barrier() circuit.draw() circuit.measure(0,0) circuit.draw() backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=backend, shots=1024).result() counts = result.get_counts(circuit) plot_histogram([counts]) myList = [5,4,6,9,1,2,3,7,8,0] def oracle(number): winningNumber = 8 if number == winningNumber: response = True else: response = False return response for index, number in enumerate(myList): if oracle(number) is True: print(f"winning number index: {index}") print(f"execution count: {index+1}") break oracleCircuit = QuantumCircuit(2,name='oracleCircuit') oracleCircuit.cz(0,1) oracleCircuit.to_gate() oracleCircuit.draw() mainCircuit = QuantumCircuit(2,2) mainCircuit.h([0,1]) mainCircuit.append(oracleCircuit,[0,1]) mainCircuit.draw(output='mpl') reflectionCircuit = QuantumCircuit(2,name="reflectionCircuit") reflectionCircuit.h([0,1]) reflectionCircuit.z([0,1]) reflectionCircuit.cz(0,1) reflectionCircuit.h([0,1]) reflectionCircuit.to_gate() reflectionCircuit.draw() mainCircuit.append(reflectionCircuit,[0,1]) mainCircuit.measure([0,1],[0,1]) mainCircuit.draw() backend = Aer.get_backend('qasm_simulator') result = execute(mainCircuit,backend=backend,shots=1).result() counts = result.get_counts(mainCircuit) plot_histogram([counts])
https://github.com/qiskit-community/qiskit-cold-atom
qiskit-community
# 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. """Fermionic simulator backend that uses ffsim.""" from __future__ import annotations import datetime import time import uuid import warnings from collections import Counter from typing import Any, Dict, List, Optional, Union import ffsim # pylint: disable=import-error import numpy as np import scipy.linalg from qiskit import QuantumCircuit from qiskit.circuit.library import Barrier, Measure from qiskit.providers import Options from qiskit.providers.models import BackendConfiguration from qiskit.result import Result from qiskit_aer import AerJob from qiskit_nature.second_q.operators import FermionicOp from scipy.sparse.linalg import expm_multiply from qiskit_cold_atom.circuit_tools import CircuitTools from qiskit_cold_atom.fermions.base_fermion_backend import BaseFermionBackend from qiskit_cold_atom.fermions.fermion_gate_library import ( FermionicGate, FRXGate, FRYGate, FRZGate, Hop, Interaction, LoadFermions, Phase, ) class FfsimBackend(BaseFermionBackend): """Fermionic simulator backend that uses ffsim. This is a high-performance simulator backend for fermionic circuits that uses `ffsim`_. It computes the state vector and simulate measurements with vastly improved efficiency compared with the :class:`~.FermionSimulator` backend. Unlike :class:`~.FermionSimulator`, it does not compute the full unitary of a circuit. Currently, this simulator only supports simulations with 1 or 2 species of fermions. The number of fermions of each species is assumed to be preserved, so that the dimension of the state vector can be determined from the number of species and the number of particles of each species. In particular, when simulating 2 species of fermions, gates that mix particles of different species, such as :class:`~.FRXGate` and :class:`FRYGate`, are not supported. In this respect, the behavior of this simulator differs from :class:`FermionSimulator`, which would automatically resort to a single-species simulation in which particles of each species are not distinguished. This backend is not supported on Windows, and in order for it to be available, Qiskit Cold Atom must be installed with the ``ffsim`` extra, e.g. .. code:: pip install "qiskit-cold-atom[ffsim]" .. _ffsim: https://github.com/qiskit-community/ffsim """ _DEFAULT_CONFIGURATION = { "backend_name": "ffsim_simulator", "backend_version": "0.0.1", "n_qubits": 100, "basis_gates": None, "gates": [], "local": False, "simulator": True, "conditional": False, "open_pulse": False, "memory": True, "max_shots": 1e6, "coupling_map": None, "description": "ffsim simulator for fermionic circuits. Instead of qubits, each wire represents" " a single fermionic mode", "supported_instructions": None, } def __init__(self, config_dict: Dict[str, Any] = None, provider=None): """Initializing the backend from a configuration dictionary""" if config_dict is None: config_dict = self._DEFAULT_CONFIGURATION super().__init__( configuration=BackendConfiguration.from_dict(config_dict), provider=provider ) @classmethod def _default_options(cls): return Options(shots=1) def _execute(self, data: Dict[str, Any], job_id: str = ""): """Helper function to execute a job. The circuit and all relevant parameters are given in the data dict. Performs validation checks on the received circuits and utilizes ffsim to perform the numerical simulations. Args: data: Data dictionary that that contains the experiments to simulate, given in the shape: data = { "num_species": int, "shots": int, "seed": int, "experiments": Dict[str, QuantumCircuit], } job_id: The job id assigned by the run method Returns: result: A qiskit job result. """ # Start timer start = time.time() output = {"results": []} num_species = data["num_species"] shots = data["shots"] seed = data["seed"] for exp_i, exp_name in enumerate(data["experiments"]): experiment = data["experiments"][exp_name] circuit = experiment["circuit"] # perform compatibility checks with the backend configuration in case gates and supported # instructions are constrained by the backend's configuration if self.configuration().gates and self.configuration().supported_instructions: CircuitTools.validate_circuits(circuits=circuit, backend=self, shots=shots) # check whether all wires are measured measured_wires = [] for inst in circuit.data: name = inst[0].name if name == "measure": for wire in inst[1]: index = circuit.qubits.index(wire) if index in measured_wires: warnings.warn( f"Wire {index} has already been measured, " f"second measurement is ignored" ) else: measured_wires.append(index) if measured_wires and len(measured_wires) != len(circuit.qubits): warnings.warn( f"Number of wires in circuit ({len(circuit.qubits)}) exceeds number of wires " + f" with assigned measurement instructions ({len(measured_wires)}). " + "This simulator backend only supports measurement of the entire quantum register " "which will instead be performed." ) # If there are no measurements, set shots to None if not measured_wires: shots = None simulation_result = _simulate_ffsim(circuit, num_species, shots, seed) output["results"].append( { "header": {"name": exp_name, "random_seed": seed}, "shots": shots, "status": "DONE", "success": True, } ) # add the simulation result at the correct place in the result dictionary output["results"][exp_i]["data"] = simulation_result output["job_id"] = job_id output["date"] = datetime.datetime.now().isoformat() output["backend_name"] = self.name() output["backend_version"] = self.configuration().backend_version output["time_taken"] = time.time() - start output["success"] = True output["qobj_id"] = None return Result.from_dict(output) # pylint: disable=arguments-differ, unused-argument def run( self, circuits: Union[QuantumCircuit, List[QuantumCircuit]], shots: int = 1000, seed: Optional[int] = None, num_species: int = 1, **run_kwargs, ) -> AerJob: """ Method to run circuits on the backend. Args: circuits: QuantumCircuit applying fermionic gates to run on the backend shots: Number of measurement shots taken in case the circuit has measure instructions seed: seed for the random number generator of the measurement simulation num_species: number of different fermionic species described by the circuits run_kwargs: Additional keyword arguments that might be passed down when calling qiskit.execute() which will have no effect on this backend. Returns: aer_job: a job object containing the result of the simulation Raises: ValueError: FfsimBackend only supports num_species=1 or 2. """ if num_species not in (1, 2): raise ValueError(f"FfsimBackend only supports num_species=1 or 2. Got {num_species}.") if isinstance(circuits, QuantumCircuit): circuits = [circuits] data = { "num_species": num_species, "shots": shots, "seed": seed, "experiments": {}, } for idx, circuit in enumerate(circuits): data["experiments"][f"experiment_{idx}"] = { "circuit": circuit, } job_id = str(uuid.uuid4()) aer_job = AerJob(self, job_id, self._execute, data) aer_job.submit() return aer_job def _simulate_ffsim( circuit: QuantumCircuit, num_species: int, shots: int | None = None, seed=None ) -> dict[str, Any]: assert circuit.num_qubits % num_species == 0 norb = circuit.num_qubits // num_species occ_a, occ_b = _get_initial_occupations(circuit, num_species) nelec = len(occ_a), len(occ_b) vec = ffsim.slater_determinant(norb, (occ_a, occ_b)) qubit_indices = {q: i for i, q in enumerate(circuit.qubits)} for instruction in circuit.data: op, qubits, _ = instruction.operation, instruction.qubits, instruction.clbits if isinstance(op, Hop): orbs = [qubit_indices[q] for q in qubits] spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species) vec = _simulate_hop( vec, np.array(op.params), spatial_orbs, norb=norb, nelec=nelec, num_species=num_species, copy=False, ) elif isinstance(op, Interaction): orbs = [qubit_indices[q] for q in qubits] spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species) (interaction,) = op.params vec = _simulate_interaction( vec, interaction, spatial_orbs, norb=norb, nelec=nelec, num_species=num_species, copy=False, ) elif isinstance(op, Phase): orbs = [qubit_indices[q] for q in qubits] spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species) vec = _simulate_phase( vec, np.array(op.params), spatial_orbs, norb=norb, nelec=nelec, num_species=num_species, copy=False, ) elif isinstance(op, FRZGate): orbs = [qubit_indices[q] for q in qubits] # pass num_species=1 here due to the definition of FRZGate spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species=1) (phi,) = op.params vec = _simulate_frz( vec, phi, spatial_orbs, norb=norb, nelec=nelec, num_species=num_species, copy=False, ) elif isinstance(op, FRXGate): if num_species != 1: raise RuntimeError( f"Encountered FRXGate even though num_species={num_species}. " "FRXGate is only supported for num_species=1." ) orbs = [qubit_indices[q] for q in qubits] spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species=1) (phi,) = op.params vec = ffsim.apply_tunneling_interaction( vec, -phi, spatial_orbs, norb, nelec, copy=False ) elif isinstance(op, FRYGate): if num_species != 1: raise RuntimeError( f"Encountered FRXGate even though num_species={num_species}. " "FRXGate is only supported for num_species=1." ) orbs = [qubit_indices[q] for q in qubits] spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species=1) (phi,) = op.params vec = ffsim.apply_givens_rotation(vec, -phi, spatial_orbs, norb, nelec, copy=False) elif isinstance(op, FermionicGate): orbs = [qubit_indices[q] for q in qubits] spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species) ferm_op = _fermionic_op_to_fermion_operator(op.generator, spatial_orbs) linop = ffsim.linear_operator(ferm_op, norb, nelec) # TODO use ferm_op.values once it's available scale = sum(abs(ferm_op[k]) for k in ferm_op) vec = expm_multiply(-1j * linop, vec, traceA=scale) elif isinstance(op, (LoadFermions, Measure, Barrier)): # these gates are handled separately or are no-ops pass else: warnings.warn(f"Unrecognized gate type {type(op)}, skipping it...") result = {"statevector": vec} if shots is None: result["memory"] = [] result["counts"] = {} else: rng = np.random.default_rng(seed) probs = np.abs(vec) ** 2 samples = rng.choice(np.arange(len(vec)), size=shots, replace=True, p=probs) bitstrings = ffsim.indices_to_strings(samples, norb, nelec) # flip beta-alpha to alpha-beta ordering bitstrings = [f"{b[len(b) // 2 :]}{b[: len(b) // 2]}" for b in bitstrings] # remove bits from absent spins bitstrings = [b[: num_species * norb] for b in bitstrings] result["memory"] = bitstrings result["counts"] = Counter(bitstrings) return result def _get_initial_occupations(circuit: QuantumCircuit, num_species: int): norb = circuit.num_qubits // num_species occ_a, occ_b = set(), set() occupations = [occ_a, occ_b] active_qubits = set() for instruction in circuit.data: if isinstance(instruction.operation, LoadFermions): for q in instruction.qubits: if q in active_qubits: raise ValueError( f"Encountered Load instruction on qubit {q} after it has " "already been operated on." ) spin, orb = divmod(circuit.qubits.index(q), norb) # reverse index due to qiskit convention occupations[spin].add(norb - 1 - orb) else: active_qubits |= set(instruction.qubits) return tuple(occ_a), tuple(occ_b) def _get_spatial_orbitals(orbs: list[int], norb: int, num_species: int) -> list[int]: assert len(orbs) % num_species == 0 alpha_orbs = orbs[: len(orbs) // num_species] if num_species == 2: beta_orbs = [orb - norb for orb in orbs[len(orbs) // 2 :]] assert alpha_orbs == beta_orbs # reverse orbitals due to qiskit convention alpha_orbs = [norb - 1 - orb for orb in alpha_orbs] return alpha_orbs def _simulate_hop( vec: np.ndarray, coeffs: np.ndarray, target_orbs: list[int], norb: int, nelec: tuple[int, int], num_species: int, copy: bool, ) -> np.ndarray: if num_species == 1: return _simulate_hop_spinless( vec=vec, coeffs=coeffs, target_orbs=target_orbs, norb=norb, nelec=nelec, copy=copy, ) else: # num_species == 2 return _simulate_hop_spinful( vec=vec, coeffs=coeffs, target_orbs=target_orbs, norb=norb, nelec=nelec, copy=copy, ) def _simulate_hop_spinless( vec: np.ndarray, coeffs: np.ndarray, target_orbs: list[int], norb: int, nelec: tuple[int, int], copy: bool, ) -> np.ndarray: assert norb % 2 == 0 assert len(target_orbs) % 2 == 0 mat = np.zeros((norb, norb)) for i, val in zip(range(len(target_orbs) // 2 - 1), coeffs): j, k = target_orbs[i], target_orbs[i + 1] mat[j, k] = -val mat[k, j] = -val for i, val in zip(range(len(target_orbs) // 2, len(target_orbs) - 1), coeffs): j, k = target_orbs[i], target_orbs[i + 1] mat[j, k] = -val mat[k, j] = -val coeffs, orbital_rotation = scipy.linalg.eigh(mat) return ffsim.apply_num_op_sum_evolution( vec, coeffs, 1.0, norb=norb, nelec=nelec, orbital_rotation=orbital_rotation, copy=copy, ) def _simulate_hop_spinful( vec: np.ndarray, coeffs: np.ndarray, target_orbs: list[int], norb: int, nelec: tuple[int, int], copy: bool, ) -> np.ndarray: mat = np.zeros((norb, norb)) for i, val in zip(range(len(target_orbs) - 1), coeffs): j, k = target_orbs[i], target_orbs[i + 1] mat[j, k] = -val mat[k, j] = -val coeffs, orbital_rotation = scipy.linalg.eigh(mat) return ffsim.apply_num_op_sum_evolution( vec, coeffs, 1.0, norb=norb, nelec=nelec, orbital_rotation=orbital_rotation, copy=copy, ) def _simulate_interaction( vec: np.ndarray, interaction: float, target_orbs: list[int], norb: int, nelec: tuple[int, int], num_species: int, copy: bool, ) -> np.ndarray: if num_species == 1: return _simulate_interaction_spinless( vec=vec, interaction=interaction, target_orbs=target_orbs, norb=norb, nelec=nelec, copy=copy, ) else: # num_species == 2 return _simulate_interaction_spinful( vec=vec, interaction=interaction, target_orbs=target_orbs, norb=norb, nelec=nelec, copy=copy, ) def _simulate_interaction_spinless( vec: np.ndarray, interaction: float, target_orbs: list[int], norb: int, nelec: tuple[int, int], copy: bool, ) -> np.ndarray: assert len(target_orbs) % 2 == 0 n_spatial_orbs = len(target_orbs) // 2 mat = np.zeros((norb, norb)) mat[target_orbs[:n_spatial_orbs], target_orbs[n_spatial_orbs:]] = interaction mat[target_orbs[n_spatial_orbs:], target_orbs[:n_spatial_orbs]] = interaction return ffsim.apply_diag_coulomb_evolution( vec, mat=mat, time=1.0, norb=norb, nelec=nelec, copy=copy, ) def _simulate_interaction_spinful( vec: np.ndarray, interaction: float, target_orbs: list[int], norb: int, nelec: tuple[int, int], copy: bool, ) -> np.ndarray: mat_alpha_beta = np.zeros((norb, norb)) mat_alpha_beta[target_orbs, target_orbs] = interaction return ffsim.apply_diag_coulomb_evolution( vec, mat=np.zeros((norb, norb)), mat_alpha_beta=mat_alpha_beta, time=1.0, norb=norb, nelec=nelec, copy=copy, ) def _simulate_phase( vec: np.ndarray, mu: np.ndarray, target_orbs: list[int], norb: int, nelec: tuple[int, int], num_species: int, copy: bool, ) -> np.ndarray: if num_species == 1: return _simulate_phase_spinless( vec=vec, mu=mu, target_orbs=target_orbs, norb=norb, nelec=nelec, copy=copy, ) else: # num_species == 2 return _simulate_phase_spinful( vec=vec, mu=mu, target_orbs=target_orbs, norb=norb, nelec=nelec, copy=copy, ) def _simulate_phase_spinless( vec: np.ndarray, mu: np.ndarray, target_orbs: list[int], norb: int, nelec: tuple[int, int], copy: bool, ) -> np.ndarray: assert len(target_orbs) % 2 == 0 n_spatial_orbs = len(target_orbs) // 2 coeffs = np.zeros(norb) coeffs[target_orbs[:n_spatial_orbs]] = mu coeffs[target_orbs[n_spatial_orbs:]] = mu return ffsim.apply_num_op_sum_evolution( vec, coeffs, time=1.0, norb=norb, nelec=nelec, copy=copy ) def _simulate_phase_spinful( vec: np.ndarray, mu: np.ndarray, target_orbs: list[int], norb: int, nelec: tuple[int, int], copy: bool, ) -> np.ndarray: coeffs = np.zeros(norb) coeffs[target_orbs] = mu return ffsim.apply_num_op_sum_evolution( vec, coeffs, time=1.0, norb=norb, nelec=nelec, copy=copy ) def _simulate_frz( vec: np.ndarray, phi: np.ndarray, target_orbs: list[int], norb: int, nelec: tuple[int, int], num_species: int, copy: bool, ) -> np.ndarray: if num_species == 1: a, b = target_orbs vec = ffsim.apply_num_interaction(vec, -phi, a, norb, nelec, copy=copy) vec = ffsim.apply_num_interaction(vec, phi, b, norb, nelec, copy=False) return vec else: # num_species == 2 a, b = target_orbs spin_a, orb_a = divmod(a, norb) spin_b, orb_b = divmod(b, norb) spins = (ffsim.Spin.ALPHA, ffsim.Spin.BETA) vec = ffsim.apply_num_interaction(vec, -phi, orb_a, norb, nelec, spins[spin_a], copy=copy) vec = ffsim.apply_num_interaction(vec, phi, orb_b, norb, nelec, spins[spin_b], copy=False) return vec def _fermionic_op_to_fermion_operator( # pylint: disable=invalid-name op: FermionicOp, target_orbs: list[int] ) -> ffsim.FermionOperator: """Convert a Qiskit Nature FermionicOp to an ffsim FermionOperator.""" norb_small = len(target_orbs) coeffs = {} for term, coeff in op.terms(): fermion_actions = [] for action_str, index in term: action = action_str == "+" spin, orb = divmod(index, norb_small) fermion_actions.append((action, bool(spin), target_orbs[orb])) coeffs[tuple(fermion_actions)] = coeff return ffsim.FermionOperator(coeffs)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.visualization.timeline import draw as timeline_draw from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") timeline_draw(circ)
https://github.com/usamisaori/qLipschitz
usamisaori
import numpy as np from qiskit import QuantumCircuit def createInputCircuit(data): qubits_num = len(data) qcircuit = QuantumCircuit(qubits_num, qubits_num) qubits = qcircuit.qubits for i, d in enumerate(data): qcircuit.rx(d * np.pi, qubits[i]) return qcircuit def createModelCircuit(params): qubits_num = len(params[0]) qcircuit = QuantumCircuit(qubits_num, qubits_num) qubits = qcircuit.qubits for i in range(qubits_num): qcircuit.u3(*params[0][i], qubits[i]) for i in range(qubits_num - 1): qcircuit.cz(qubits[i], qubits[i + 1]) qcircuit.cz(qubits[0], qubits[qubits_num - 1]) for i in range(qubits_num): qcircuit.u3(*params[1][i], qubits[i]) return qcircuit def createCircuit(params, data): input_circuit = createInputCircuit(data) model_circuit = createModelCircuit(params) full_circuit = input_circuit.compose(model_circuit) return full_circuit from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.utils import insert_noise from qiskit.providers.aer.noise import pauli_error, depolarizing_error def createNoiseModel(p, errorType): # QuantumError objects if errorType == 'bit_flip': error = pauli_error([('X', p), ('I', 1 - p)]) elif errorType == 'phase_flip': error = pauli_error([('Z', p), ('I', 1 - p)]) elif errorType == 'depolarizing': error = depolarizing_error(p, num_qubits=1) ## two-qubits quantumError objects if errorType == 'depolarizing': error_2qubits = depolarizing_error(p, num_qubits=2) else: error_2qubits = error.tensor(error) # Add errors to noise model noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, ['u3']) noise_model.add_all_qubit_quantum_error(error_2qubits, ['cz']) return noise_model def createNoisyModelCircuit(params, p, errorType): noise_model = createNoiseModel(p, errorType) model_circuit = createModelCircuit(params) return insert_noise(model_circuit, noise_model) __all__ = ['createModelCircuit', 'createNoisyModelCircuit']
https://github.com/qiskit-community/qiskit-cold-atom
qiskit-community
import numpy as np import matplotlib.pyplot as plt import time from qiskit_cold_atom.fermions import FermionSimulator, FfsimBackend from qiskit_cold_atom.fermions.fermion_gate_library import FermiHubbard from qiskit_nature.operators.second_quantization import FermionicOp from qiskit.circuit import Parameter backend = FermionSimulator() backend_ffsim = FfsimBackend() def prep_init_states(dmax: int, with_hole: bool) -> tuple[list, list]: """ Prepares a list of initial states for the Fermi-Hubbard model. Args: dmax: the maximum distance from the center with_hole: whether to include a hole in the initial state Returns: two lists of initial states starting with spin-up and spin-down, respectively """ Nsites = 2 * dmax + 1 # the up state state_up = [i % 2 for i in range(Nsites)] state_down = [(i + 1) % 2 for i in range(Nsites)] if with_hole: state_up[dmax] = 0 state_down[dmax] = 0 init_state_1 = [state_up, state_down] init_state_2 = [state_down, state_up] return init_state_1, init_state_2 dmax = 3 Nsites = 2 * dmax + 1 init_state_1, init_state_2 = prep_init_states(dmax, with_hole=True) hop_param = Parameter("hop_param") int_param = Parameter("int_param") # initialize one spin-up and one spin-down atom in the left tweezer qc_1 = backend.initialize_circuit(init_state_1) # apply a global Fermi-Hubbard gate with interaction qc_1.fhubbard(j=hop_param * np.ones(Nsites - 1), u=int_param, mu=np.zeros(Nsites), modes=range(2*Nsites)) qc_1.measure_all() # qc_1.draw(output="mpl") hop_param_down = Parameter("hop_param") int_param_down = Parameter("int_param") # initialize one spin-up and one spin-down atom in the left tweezer qc_2 = backend.initialize_circuit(init_state_2) # apply a global Fermi-Hubbard gate with interaction qc_2.fhubbard( j=hop_param_down * np.ones(Nsites - 1), u=int_param_down, mu=np.zeros(Nsites), modes=range(2 * Nsites), ) qc_2.measure_all() circuit_up_init = qc_1.bind_parameters({hop_param: 0, int_param: 0}) job_up_init = backend.run(circuit_up_init, shots=5, num_species=2) circuit_down_init = qc_2.bind_parameters({hop_param_down: 0, int_param_down: 0}) job_down_init = backend.run(circuit_down_init, shots=5, num_species=2) def nocc_from_counts(counts: dict[str, int], Nsites: int) -> np.ndarray: """ The calculates the occupation from all observed configurations. Args: counts: the counts of the observed configurations Nsites: the number of sites in the system Returns: 1D array The occupation for each site """ nocc_t = np.zeros(Nsites) Nobs = 0 for occ_string, observations in counts.items(): # get the occupation of each site in the observed configuration nocc = np.zeros(Nsites) for site_index in range(Nsites): nocc[site_index] = int(occ_string[site_index]) + int(occ_string[site_index + Nsites]) # now add the value to the correct time step and with it by the number of observations Nobs = Nobs + observations nocc_t = nocc_t + nocc * observations return nocc_t / Nobs def squeezed_spin_corr_from_counts(counts: dict[str, int], Nsites: int) -> np.ndarray: """ The calculates the spin projection from all observed configurations. However, we filter out situations with a hole and a doublon in the system. Args: counts: the counts of the observed configurations Nsites: the number of sites in the system Returns: 1D array The occupation for each site """ sz_squeeze = np.zeros(Nsites) szvar = np.zeros(Nsites) Nobs = 0 Nobs_var = np.zeros(Nsites) Nobs = np.zeros(Nsites) for occ_string, observations in counts.items(): occ_int = [int(occ) for occ in occ_string] # get the spin of each site in the observed configuration sz = np.zeros(Nsites) nocc = np.zeros(Nsites) for site_index in range(Nsites): sz[site_index] = 1 / 2 * (occ_int[site_index] - occ_int[site_index + Nsites]) nocc[site_index] = occ_int[site_index] + occ_int[site_index + Nsites] # now obtain the symmetrized variance # first for the first site site_index = 0 if nocc[site_index] == 1 and nocc[site_index + 1] == 1: szvar[site_index] = ( szvar[site_index] + sz[site_index] * sz[site_index + 1] * observations ) Nobs_var[site_index] = Nobs_var[site_index] + observations # then for the last site site_index = Nsites - 1 if nocc[site_index] == 1 and nocc[site_index - 1] == 1: szvar[site_index] = ( szvar[site_index] + sz[site_index] * sz[site_index - 1] * observations ) Nobs_var[site_index] = Nobs_var[site_index] + observations # and finally for all the other sites for site_index in range(1,Nsites-1): if ( nocc[site_index] == 1 and nocc[site_index + 1] == 1 and nocc[site_index - 1] == 1 ): szvar[site_index] = ( szvar[site_index] + 1 / 2 * sz[site_index] * (sz[site_index + 1] + sz[site_index - 1]) * observations ) Nobs_var[site_index] = Nobs_var[site_index] + observations elif ( nocc[site_index] == 1 and nocc[site_index + 1] == 1 and nocc[site_index - 1] == 0 ): szvar[site_index] = ( szvar[site_index] + sz[site_index] * sz[site_index + 1] * observations ) Nobs_var[site_index] = Nobs_var[site_index] + observations elif ( nocc[site_index] == 1 and nocc[site_index + 1] == 0 and nocc[site_index - 1] == 1 ): szvar[site_index] = ( szvar[site_index] + sz[site_index] * sz[site_index - 1] * observations ) Nobs_var[site_index] = Nobs_var[site_index] + observations sz_squeeze += sz * (nocc == 1) * observations Nobs += (nocc == 1) * observations # regularize the observations var_weight = 1 / Nobs_var var_weight[np.isinf(var_weight)] = 0 mean_weight = 1 / Nobs mean_weight[np.isinf(mean_weight)] = 0 # now that we have gone through all observations, we can average fluc = np.zeros(Nsites) for site_index in range(Nsites): if site_index == 0: fluc[site_index] = 4 * ( szvar[site_index] * var_weight[site_index] - sz_squeeze[site_index] * mean_weight[site_index] * sz_squeeze[site_index + 1] * mean_weight[site_index + 1] ) elif site_index == Nsites - 1: fluc[site_index] = 4 * ( szvar[site_index] * var_weight[site_index] - sz_squeeze[site_index] * mean_weight[site_index] * sz_squeeze[site_index - 1] * mean_weight[site_index - 1] ) else: fluc[site_index] = 4 * ( szvar[site_index] * var_weight[site_index] - sz_squeeze[site_index] * mean_weight[site_index] * ( sz_squeeze[site_index + 1] * mean_weight[site_index + 1] + sz_squeeze[site_index - 1] * mean_weight[site_index - 1] ) / 2 ) return fluc, Nobs_var, Nobs noccs_init = np.zeros( Nsites) corrs_init = np.zeros(Nsites) counts_1 = job_up_init.result().get_counts() counts_2 = job_down_init.result().get_counts() total_counts = counts_1 total_counts.update(counts_2) nocc = nocc_from_counts(total_counts, Nsites) corr, _, _ = squeezed_spin_corr_from_counts(total_counts, Nsites) f, ax = plt.subplots() ax.plot(np.arange(Nsites) - dmax, nocc, "bo", label="nocc") ax.plot(np.arange(Nsites) - dmax, corr, "ro", label="corr", alpha = 0.5) ax.legend() ax.set_xlabel("site index") # the experimental parameters J = 2 * np.pi * 250 # hopping parameter in units of hbar U = 15 * J # interaction parameter Ntimes = 8 tmax = 1.5 times = np.linspace(0, tmax, Ntimes) * 1e-3 Nshots = 500 # create list of circuits with interaction circuits_1 = [qc_1.bind_parameters({hop_param: J * t, int_param: U * t}) for t in times] # measure the observable from simulated shots jobs_1 = backend.run(circuits_1, shots=Nshots, num_species=2) # create list of circuits with interaction circuits_2 = [qc_2.bind_parameters({hop_param_down: J * t, int_param_down: U * t}) for t in times] # measure the observable from simulated shots jobs_2 = backend.run(circuits_2, shots=Nshots, num_species=2) noccs = np.zeros((Ntimes, Nsites)) corrs = np.zeros((Ntimes, Nsites)) start_time = time.time() count_list_1 = jobs_1.result().get_counts() count_list_2 = jobs_2.result().get_counts() end_time = time.time() print(f"Duration for of the two jobs: {end_time - start_time} seconds") for ii in range(Ntimes): counts_1 = count_list_1[ii] counts_2 = count_list_2[ii] total_counts = counts_1 total_counts.update(counts_2) nocc = nocc_from_counts(total_counts, Nsites) corr, _,_ = squeezed_spin_corr_from_counts(total_counts, Nsites) noccs[ii, :] = nocc corrs[ii, :] = corr f, [ax1, ax2] = plt.subplots(1, 2, sharey=True) # color plot of the occupation in a heatmap velo = J ax1.pcolor(np.arange(Nsites) - dmax, times * 1e3, corrs, cmap="Reds") ax1.set_xlabel("time [ms]") ax1.set_xlabel("site index") ax1.set_title("Spin") ax2.pcolor(np.arange(Nsites) - dmax, times * 1e3, noccs, cmap="Blues") ax2.set_xlabel("site index") ax2.set_title("Density") stds_spin = np.zeros(Ntimes) for ii, corr in enumerate(corrs): mass_func = corr + 1 mean_position = np.average(np.arange(len(mass_func)), weights=mass_func) # Calculate the standard deviation of the position std_position = np.sqrt( np.average((np.arange(len(mass_func)) - mean_position) ** 2, weights=mass_func) ) stds_spin[ii] = std_position stds_density = np.zeros(Ntimes) for ii, nocc in enumerate(noccs): # print(nocc) mass_func = 1 - nocc mean_position = np.average(np.arange(len(mass_func)), weights=mass_func) # Calculate the standard deviation of the position std_position = np.sqrt( np.average((np.arange(len(mass_func)) - mean_position) ** 2, weights=mass_func) ) stds_density[ii] = std_position f, ax = plt.subplots() ax.plot(times * 1e3, stds_spin, "ro", label="spin") ax.plot(times * 1e3, stds_density, "bo", label="density") ax.set_xlabel("time [ms]") ax.set_ylabel("standard deviation") ax.legend() # prepare the jobs jobs_1_ffsim = backend_ffsim.run(circuits_1, shots=Nshots, num_species=2) jobs_2_ffsim = backend_ffsim.run(circuits_2, shots=Nshots, num_species=2) # run them and time it start_time = time.time() count_list_1 = jobs_1_ffsim.result().get_counts() count_list_2 = jobs_2_ffsim.result().get_counts() end_time = time.time() print(f"Duration for of the two jobs: {end_time - start_time} seconds") hop_long = Parameter("hop_long") int_long = Parameter("int_long") # initialize one spin-up and one spin-down atom in the left tweezer qc_long = backend_ffsim.initialize_circuit(init_state_1) # apply a global Fermi-Hubbard gate with interaction qc_long.fhubbard( j=hop_long * np.ones(Nsites - 1), u=int_long, mu=np.zeros(Nsites), modes=range(2 * Nsites) ) qc_long.measure_all() tmax = 1 / U circuit_long = qc_long.bind_parameters({hop_long: J * tmax, int_long: U * tmax}) job_long = backend.run(circuit_long, shots=5, num_species=2) start_time = time.time() count_long = job_long.result().get_counts() end_time = time.time() print(f"Duration for of the two jobs: {end_time - start_time:.2f} seconds") time_step = 1/(4*U) print(f"time step = {time_step*1e3:.2f} ms") Ntrott = int(tmax / time_step) print(f"Number of trotter steps: {Ntrott}") trott_hop = Parameter("trott_hop") trott_int = Parameter("trott_int") # initialize one spin-up and one spin-down atom in the left tweezer qc_trott = backend_ffsim.initialize_circuit(init_state_1) for ii in range(Ntrott): # apply a global Fermi-Hubbard gate with interaction qc_trott.fhop( j=trott_hop * np.ones(Nsites - 1), modes=range(2 * Nsites), ) qc_trott.fint(u=trott_int, modes=range(2 * Nsites)) # apply a global Fermi-Hubbard gate with interaction qc_trott.measure_all() circuit_trott = qc_trott.bind_parameters({trott_hop: J * time_step, trott_int: U * time_step}) job_trott = backend_ffsim.run(circuit_trott, shots=5, num_species=2) start_time = time.time() count_long = job_long.result().get_counts() end_time = time.time() print(f"Duration for of the two jobs: {(end_time - start_time)*1e3:.2f} ms") import qiskit.tools.jupyter %qiskit_version_table
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q # TODO: This example should use a real mock backend. backend = FakeOpenPulse3Q() d2 = pulse.DriveChannel(2) with pulse.build(backend) as bell_prep: pulse.u2(0, math.pi, 0) pulse.cx(0, 1) with pulse.build(backend) as decoupled_bell_prep_and_measure: # We call our bell state preparation schedule constructed above. with pulse.align_right(): pulse.call(bell_prep) pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2) pulse.barrier(0, 1, 2) registers = pulse.measure_all() decoupled_bell_prep_and_measure.draw()
https://github.com/UST-QuAntiL/qiskit-service
UST-QuAntiL
# ****************************************************************************** # Copyright (c) 2024 University of Stuttgart # # See the NOTICE file(s) distributed with this work for additional # information regarding copyright ownership. # # 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 base64 import json from flask import jsonify, abort, request from qiskit import transpile from qiskit.providers.ibmq import IBMQAccountError from qiskit.transpiler.exceptions import TranspilerError from app import app, benchmarking, aws_handler, ibmq_handler, implementation_handler, db, parameters, circuit_analysis, \ analysis, ionq_handler from app.benchmark_model import Benchmark from app.generated_circuit_model import Generated_Circuit from app.qpu_metrics import generate_deterministic_uuid, get_all_qpus_and_metrics_as_json_str from app.result_model import Result @app.route('/qiskit-service/api/v1.0/generate-circuit', methods=['POST']) def generate_circuit(): if not request.json: abort(400) impl_language = request.json.get('impl-language', '') impl_url = request.json.get('impl-url', "") input_params = request.json.get('input-params', "") bearer_token = request.json.get("bearer-token", "") impl_data = '' if input_params: input_params = parameters.ParameterDictionary(input_params) if impl_url is not None and impl_url != "": impl_url = request.json['impl-url'] elif 'impl-data' in request.json: impl_data = base64.b64decode(request.json.get('impl-data').encode()).decode() else: abort(400) job = app.implementation_queue.enqueue('app.tasks.generate', impl_url=impl_url, impl_data=impl_data, impl_language=impl_language, input_params=input_params, bearer_token=bearer_token) result = Generated_Circuit(id=job.get_id()) db.session.add(result) db.session.commit() app.logger.info('Returning HTTP response to client...') content_location = '/qiskit-service/api/v1.0/generated-circuits/' + result.id response = jsonify({'Location': content_location}) response.status_code = 202 response.headers['Location'] = content_location response.autocorrect_location_header = True return response @app.route('/qiskit-service/api/v1.0/generated-circuits/<generated_circuit_id>', methods=['GET']) def get_generated_circuit(generated_circuit_id): """Return result when it is available.""" generated_circuit = Generated_Circuit.query.get(generated_circuit_id) if generated_circuit.complete: input_params_dict = json.loads(generated_circuit.input_params) return jsonify( {'id': generated_circuit.id, 'complete': generated_circuit.complete, 'input_params': input_params_dict, 'generated-circuit': generated_circuit.generated_circuit, 'original-depth': generated_circuit.original_depth, 'original-width': generated_circuit.original_width, 'original-total-number-of-operations': generated_circuit.original_total_number_of_operations, 'original-number-of-multi-qubit-gates': generated_circuit.original_number_of_multi_qubit_gates, 'original-number-of-measurement-operations': generated_circuit.original_number_of_measurement_operations, 'original-number-of-single-qubit-gates': generated_circuit.original_number_of_single_qubit_gates, 'original-multi-qubit-gate-depth': generated_circuit.original_multi_qubit_gate_depth}), 200 else: return jsonify({'id': generated_circuit.id, 'complete': generated_circuit.complete}), 200 @app.route('/qiskit-service/api/v1.0/transpile', methods=['POST']) def transpile_circuit(): """Get implementation from URL. Pass input into implementation. Generate and transpile circuit and return depth and width.""" if not request.json or not 'qpu-name' in request.json: abort(400) # Default value is ibmq for services that do not support multiple providers and expect the IBMQ provider provider = request.json.get('provider', 'ibmq') qpu_name = request.json['qpu-name'] impl_language = request.json.get('impl-language', '') input_params = request.json.get('input-params', "") impl_url = request.json.get('impl-url', "") bearer_token = request.json.get("bearer-token", "") if input_params: input_params = parameters.ParameterDictionary(input_params) if provider == 'ibmq' or provider == 'ionq': if 'token' in input_params: token = input_params['token'] elif 'token' in request.json: token = request.json.get('token') else: abort(400) elif provider == 'aws': if 'aws-access-key-id' in input_params and 'aws-secret-access-key' in input_params: aws_access_key_id = input_params['aws-access-key-id'] aws_secret_access_key = input_params['aws-secret-access-key'] elif 'aws-access-key-id' in request.json and 'aws-secret-access-key' in request.json: aws_access_key_id = request.json.get('aws-access-key-id') aws_secret_access_key = request.json.get('aws-secret-access-key') else: abort(400) if impl_url is not None and impl_url != "": impl_url = request.json['impl-url'] if impl_language.lower() == 'openqasm': short_impl_name = 'no name' circuit = implementation_handler.prepare_code_from_qasm_url(impl_url, bearer_token) else: short_impl_name = "untitled" try: circuit = implementation_handler.prepare_code_from_url(impl_url, input_params, bearer_token) except ValueError: abort(400) elif 'impl-data' in request.json: impl_data = base64.b64decode(request.json.get('impl-data').encode()).decode() short_impl_name = 'no short name' if impl_language.lower() == 'openqasm': circuit = implementation_handler.prepare_code_from_qasm(impl_data) else: try: circuit = implementation_handler.prepare_code_from_data(impl_data, input_params) except ValueError: abort(400) elif 'qasm-string' in request.json: short_impl_name = 'no short name' app.logger.info(request.json.get('qasm-string')) circuit = implementation_handler.prepare_code_from_qasm(request.json.get('qasm-string')) else: abort(400) try: non_transpiled_depth_old = 0 non_transpiled_depth = circuit.depth() while non_transpiled_depth_old < non_transpiled_depth: non_transpiled_depth_old = non_transpiled_depth circuit = circuit.decompose() non_transpiled_depth = circuit.depth() non_transpiled_width = circuit_analysis.get_width_of_circuit(circuit) non_transpiled_total_number_of_operations = circuit.size() non_transpiled_number_of_multi_qubit_gates = circuit.num_nonlocal_gates() non_transpiled_number_of_measurement_operations = circuit_analysis.get_number_of_measurement_operations(circuit) non_transpiled_number_of_single_qubit_gates = non_transpiled_total_number_of_operations - non_transpiled_number_of_multi_qubit_gates - non_transpiled_number_of_measurement_operations non_transpiled_multi_qubit_gate_depth, non_transpiled_circuit = circuit_analysis.get_multi_qubit_gate_depth( circuit.copy()) print(f"Non transpiled width {non_transpiled_width} & non transpiled depth {non_transpiled_depth}") if not circuit: app.logger.warn(f"{short_impl_name} not found.") abort(404) except Exception as e: app.logger.info(f"Transpile {short_impl_name} for {qpu_name}: {str(e)}") return jsonify({'error': str(e)}), 200 backend = None credentials = {} if provider == 'ibmq': if 'url' in input_params: credentials['url'] = input_params['url'] if 'hub' in input_params: credentials['hub'] = input_params['hub'] if 'group' in input_params: credentials['group'] = input_params['group'] if 'project' in input_params: credentials['project'] = input_params['project'] backend = ibmq_handler.get_qpu(token, qpu_name, **credentials) elif provider == 'ionq': backend = ionq_handler.get_qpu(token, qpu_name) elif provider == 'aws': if 'region' in input_params: credentials['region'] = input_params['region'] backend = aws_handler.get_qpu(access_key=aws_access_key_id, secret_access_key=aws_secret_access_key, qpu_name=qpu_name, **credentials) if not backend: app.logger.warn(f"{qpu_name} not found.") abort(404) try: if provider == 'aws': transpiled_circuit = transpile(circuit, backend=backend) else: transpiled_circuit = transpile(circuit, backend=backend, optimization_level=3) width = circuit_analysis.get_width_of_circuit(transpiled_circuit) depth = transpiled_circuit.depth() total_number_of_operations = transpiled_circuit.size() number_of_multi_qubit_gates = transpiled_circuit.num_nonlocal_gates() number_of_measurement_operations = circuit_analysis.get_number_of_measurement_operations(transpiled_circuit) number_of_single_qubit_gates = total_number_of_operations - number_of_multi_qubit_gates - number_of_measurement_operations multi_qubit_gate_depth, transpiled_circuit = circuit_analysis.get_multi_qubit_gate_depth(transpiled_circuit) except TranspilerError: app.logger.info(f"Transpile {short_impl_name} for {qpu_name}: too many qubits required") return jsonify({'error': 'too many qubits required'}), 200 app.logger.info(f"Transpile {short_impl_name} for {qpu_name}: w={width}, " f"d={depth}, " f"multi qubit gate depth={multi_qubit_gate_depth}, " f"total number of operations={total_number_of_operations}, " f"number of single qubit gates={number_of_single_qubit_gates}, " f"number of multi qubit gates={number_of_multi_qubit_gates}, " f"number of measurement operations={number_of_measurement_operations}") return jsonify({'original-depth': non_transpiled_depth, 'original-width': non_transpiled_width, 'original-total-number-of-operations': non_transpiled_total_number_of_operations, 'original-number-of-multi-qubit-gates': non_transpiled_number_of_multi_qubit_gates, 'original-number-of-measurement-operations': non_transpiled_number_of_measurement_operations, 'original-number-of-single-qubit-gates': non_transpiled_number_of_single_qubit_gates, 'original-multi-qubit-gate-depth': non_transpiled_multi_qubit_gate_depth, 'depth': depth, 'multi-qubit-gate-depth': multi_qubit_gate_depth, 'width': width, 'total-number-of-operations': total_number_of_operations, 'number-of-single-qubit-gates': number_of_single_qubit_gates, 'number-of-multi-qubit-gates': number_of_multi_qubit_gates, 'number-of-measurement-operations': number_of_measurement_operations, 'transpiled-qasm': transpiled_circuit.qasm()}), 200 @app.route('/qiskit-service/api/v1.0/analyze-original-circuit', methods=['POST']) def analyze_original_circuit(): if not request.json: abort(400) impl_language = request.json.get('impl-language', '') impl_url = request.json.get('impl-url', "") input_params = request.json.get('input-params', "") bearer_token = request.json.get("bearer-token", "") if input_params: input_params = parameters.ParameterDictionary(input_params) if impl_url is not None and impl_url != "": impl_url = request.json['impl-url'] if impl_language.lower() == 'openqasm': short_impl_name = 'no name' circuit = implementation_handler.prepare_code_from_qasm_url(impl_url, bearer_token) else: short_impl_name = "untitled" try: circuit = implementation_handler.prepare_code_from_url(impl_url, input_params, bearer_token) except ValueError: abort(400) elif 'impl-data' in request.json: impl_data = base64.b64decode(request.json.get('impl-data').encode()).decode() short_impl_name = 'no short name' if impl_language.lower() == 'openqasm': circuit = implementation_handler.prepare_code_from_qasm(impl_data) else: try: circuit = implementation_handler.prepare_code_from_data(impl_data, input_params) except ValueError: abort(400) elif 'qasm-string' in request.json: short_impl_name = 'no short name' app.logger.info(request.json.get('qasm-string')) circuit = implementation_handler.prepare_code_from_qasm(request.json.get('qasm-string')) else: abort(400) try: non_transpiled_depth_old = 0 non_transpiled_depth = circuit.depth() while non_transpiled_depth_old < non_transpiled_depth: non_transpiled_depth_old = non_transpiled_depth circuit = circuit.decompose() non_transpiled_depth = circuit.depth() non_transpiled_width = circuit_analysis.get_width_of_circuit(circuit) non_transpiled_total_number_of_operations = circuit.size() non_transpiled_number_of_multi_qubit_gates = circuit.num_nonlocal_gates() non_transpiled_number_of_measurement_operations = circuit_analysis.get_number_of_measurement_operations(circuit) non_transpiled_number_of_single_qubit_gates = non_transpiled_total_number_of_operations - non_transpiled_number_of_multi_qubit_gates - non_transpiled_number_of_measurement_operations non_transpiled_multi_qubit_gate_depth, non_transpiled_circuit = circuit_analysis.get_multi_qubit_gate_depth( circuit) print(f"Non transpiled width {non_transpiled_width} & non transpiled depth {non_transpiled_depth}") if not circuit: app.logger.warn(f"{short_impl_name} not found.") abort(404) except Exception as e: return jsonify({'error': str(e)}), 200 return jsonify({'original-depth': non_transpiled_depth, 'original-width': non_transpiled_width, 'original-total-number-of-operations': non_transpiled_total_number_of_operations, 'original-number-of-multi-qubit-gates': non_transpiled_number_of_multi_qubit_gates, 'original-number-of-measurement-operations': non_transpiled_number_of_measurement_operations, 'original-number-of-single-qubit-gates': non_transpiled_number_of_single_qubit_gates, 'original-multi-qubit-gate-depth': non_transpiled_multi_qubit_gate_depth}), 200 @app.route('/qiskit-service/api/v1.0/execute', methods=['POST']) def execute_circuit(): """Put execution jobs in queue. Return location of the later results.""" if not request.json or not 'qpu-name' in request.json: abort(400) # Default value is ibmq for services that do not support multiple providers and expect the IBMQ provider provider = request.json.get('provider', 'ibmq') correlation_id = request.json.get('correlation-id', None) qpu_name = request.json['qpu-name'] impl_language = request.json.get('impl-language', '') impl_url = request.json.get('impl-url') if type(impl_url) is str: impl_url = [impl_url] impl_data = request.json.get('impl-data') if type(impl_data) is str: impl_data = [impl_data] qasm_string = request.json.get('qasm-string') if type(qasm_string) is str: qasm_string = [qasm_string] transpiled_qasm = request.json.get('transpiled-qasm') if type(transpiled_qasm) is str: transpiled_qasm = [transpiled_qasm] bearer_token = request.json.get("bearer-token", "") input_params = request.json.get('input-params', "") noise_model = request.json.get("noise-model") only_measurement_errors = request.json.get("only-measurement-errors") optimization_level = request.json.get('transpilation-optimization-level', 3) if input_params: input_params = parameters.ParameterDictionary(input_params) token = '' aws_access_key_id = '' aws_secret_access_key = '' if provider == 'ibmq' or provider == 'ionq': if 'token' in input_params: token = input_params['token'] elif 'token' in request.json: token = request.json.get('token') else: abort(400) elif provider == 'aws': if 'aws-access-key-id' in input_params and 'aws-secret-access-key' in input_params: aws_access_key_id = input_params['aws-access-key-id'] aws_secret_access_key = input_params['aws-secret-access-key'] elif 'aws-access-key-id' in request.json and 'aws-secret-access-key' in request.json: aws_access_key_id = request.json.get('aws-access-key-id') aws_secret_access_key = request.json.get('aws-secret-access-key') else: abort(400) # Check parameters required for using premium accounts, de.imbq and reservations credentials = {} if provider == 'ibmq': if 'url' in input_params: credentials['url'] = input_params['url'] if 'hub' in input_params: credentials['hub'] = input_params['hub'] if 'group' in input_params: credentials['group'] = input_params['group'] if 'project' in input_params: credentials['project'] = input_params['project'] elif provider == 'aws': if 'region' in input_params: credentials['region'] = input_params['region'] shots = request.json.get('shots', 1024) job = app.execute_queue.enqueue('app.tasks.execute', correlation_id=correlation_id, provider=provider, impl_url=impl_url, impl_data=impl_data, impl_language=impl_language, transpiled_qasm=transpiled_qasm, qpu_name=qpu_name, token=token, access_key_aws=aws_access_key_id, secret_access_key_aws=aws_secret_access_key, input_params=input_params, noise_model=noise_model, only_measurement_errors=only_measurement_errors, optimization_level=optimization_level, shots=shots, bearer_token=bearer_token, qasm_string=qasm_string, **credentials) result = Result(id=job.get_id(), backend=qpu_name, shots=shots) db.session.add(result) db.session.commit() app.logger.info('Returning HTTP response to client...') content_location = '/qiskit-service/api/v1.0/results/' + result.id response = jsonify({'Location': content_location}) response.status_code = 202 response.headers['Location'] = content_location response.autocorrect_location_header = True return response @app.route('/qiskit-service/api/v1.0/calculate-calibration-matrix', methods=['POST']) def calculate_calibration_matrix(): """Put calibration matrix calculation job in queue. Return location of the later result.""" if not request.json or not 'qpu-name' in request.json or not 'token' in request.json: abort(400) qpu_name = request.json['qpu-name'] token = request.json['token'] shots = request.json.get('shots', 8192) job = app.execute_queue.enqueue('app.tasks.calculate_calibration_matrix', qpu_name=qpu_name, token=token, shots=shots) result = Result(id=job.get_id()) db.session.add(result) db.session.commit() app.logger.info('Returning HTTP response to client...') content_location = '/qiskit-service/api/v1.0/results/' + result.id response = jsonify({'Location': content_location}) response.status_code = 202 response.headers['Location'] = content_location response.autocorrect_location_header = True return response @app.route('/qiskit-service/api/v1.0/calc-wd/<qpu_name>', methods=['GET']) def calc_wd(qpu_name): """calculates wd-value of a given Quantum Computer based on the clifford data in your database and returns it""" wd = benchmarking.calc_wd(qpu_name) return jsonify(wd) # TODO: after Qiskit ignis is deprecated, the generation of Clifford gate circuits has to be adapted @app.route('/qiskit-service/api/v1.0/randomize', methods=['POST']) def randomize(): # """Create randomized circuits of given properties to run benchmarks and return locations to their results""" # if not request.json: # abort(400) # # qpu_name = request.json['qpu-name'] # num_of_qubits = request.json['number-of-qubits'] # min_depth_of_circuit = request.json['min-depth-of-circuit'] # max_depth_of_circuit = request.json['max-depth-of-circuit'] # num_of_circuits = request.json['number-of-circuits'] # clifford = request.json.get('clifford', False) # shots = request.json.get('shots', 1024) # token = request.json['token'] # # locations = benchmarking.randomize(qpu_name=qpu_name, num_of_qubits=num_of_qubits, shots=shots, # min_depth_of_circuit=min_depth_of_circuit, # max_depth_of_circuit=max_depth_of_circuit, num_of_circuits=num_of_circuits, # clifford=clifford, token=token) # # return jsonify(locations) return jsonify(0) @app.route('/qiskit-service/api/v1.0/results/<result_id>', methods=['GET']) def get_result(result_id): """Return result when it is available.""" result = Result.query.get(result_id) if result.complete: result_dict = json.loads(result.result) if result.post_processing_result: post_processing_result_dict = json.loads(result.post_processing_result) return jsonify( {'id': result.id, 'complete': result.complete, 'result': result_dict, 'backend': result.backend, 'shots': result.shots, 'generated-circuit-id': result.generated_circuit_id, 'post-processing-result': post_processing_result_dict}), 200 else: return jsonify( {'id': result.id, 'complete': result.complete, 'result': result_dict, 'backend': result.backend, 'shots': result.shots}), 200 else: return jsonify({'id': result.id, 'complete': result.complete}), 200 @app.route('/qiskit-service/api/v1.0/benchmarks/<benchmark_id>', methods=['GET']) def get_benchmark(benchmark_id): """Return summary of benchmark when it is available. Includes result of both simulator and quantum computer if available """ benchmark_sim = None benchmark_real = None # get the simulator's and quantum computer's result from the db i = 1 # for testing simulator can be benchmarked for benchmark in Benchmark.query.filter(Benchmark.benchmark_id == benchmark_id): if benchmark.backend == 'ibmq_qasm_simulator' and i > 0: benchmark_sim = benchmark i = i - 1 else: benchmark_real = benchmark # check which backend has finished execution and adapt response to that if (benchmark_sim is not None) and (benchmark_real is not None): if benchmark_sim.complete and benchmark_real.complete: if benchmark_sim.result == "" or benchmark_real.result == "": # one backend failed during the execution return json.dumps({'error': 'execution failed'}) # both backends finished execution return jsonify({'id': int(benchmark_id), 'benchmarking-complete': True, 'histogram-intersection': analysis.calc_intersection( json.loads(benchmark_sim.counts).copy(), json.loads(benchmark_real.counts).copy(), benchmark_real.shots), 'perc-error': analysis.calc_percentage_error(json.loads(benchmark_sim.counts), json.loads(benchmark_real.counts)), 'correlation': analysis.calc_correlation(json.loads(benchmark_sim.counts).copy(), json.loads(benchmark_real.counts).copy(), benchmark_real.shots), 'chi-square': analysis.calc_chi_square_distance(json.loads(benchmark_sim.counts).copy(), json.loads(benchmark_real.counts).copy()), 'benchmarking-results': [get_benchmark_body(benchmark_backend=benchmark_sim), get_benchmark_body(benchmark_backend=benchmark_real)]}), 200 elif benchmark_sim.complete and not benchmark_real.complete: if benchmark_sim.result == "": # execution on simulator failed return json.dumps({'error': 'execution failed'}) # simulator finished execution, quantum computer not yet return jsonify({'id': int(benchmark_id), 'benchmarking-complete': False, 'benchmarking-results': [get_benchmark_body(benchmark_backend=benchmark_sim), {'result-id': benchmark_real.id, 'complete': benchmark_real.complete}]}), 200 elif not benchmark_sim.complete and benchmark_real.complete: if benchmark_real.result == "": # execution on quantum computer failed return json.dumps({'error': 'execution failed'}) # quantum computer finished execution, simulator not yet return jsonify({'id': int(benchmark_id), 'benchmarking-complete': False, 'benchmarking-results': [ {'result-id': benchmark_sim.id, 'complete': benchmark_sim.complete}, get_benchmark_body(benchmark_backend=benchmark_real)]}), 200 else: # both backends did not finish execution yet return jsonify({'id': int(benchmark_id), 'benchmarking-complete': False, 'benchmarking-results': [ {'result-id': benchmark_sim.id, 'complete': benchmark_sim.complete}, {'result-id': benchmark_real.id, 'complete': benchmark_real.complete}]}), 200 else: abort(404) @app.route('/qiskit-service/api/v1.0/providers', methods=['GET']) def get_providers(): """Return available providers.""" return jsonify({"_embedded": {"providerDtoes": [ {"id": str(generate_deterministic_uuid("ibmq", "provider")), "name": "ibmq", "offeringURL": "https://quantum-computing.ibm.com/", }, {"id": str(generate_deterministic_uuid("aws", "provider")), "name": "aws", "offeringURL": "https://aws.amazon.com/braket/", }]}}), 200 @app.route('/qiskit-service/api/v1.0/providers/<provider_id>/qpus', methods=['GET']) def get_qpus_and_metrics_of_provider(provider_id: str): """Return qpus and metrics of the specified provider.""" if 'token' not in request.headers: return jsonify({"message": "Error: token missing in request"}), 401 token = request.headers.get('token') if provider_id == str(generate_deterministic_uuid("ibmq", "provider")): try: return get_all_qpus_and_metrics_as_json_str(token), 200 except IBMQAccountError: return jsonify({"message": "the provided token is wrong"}), 401 else: return jsonify({"message": "Error: unknown provider ID."}), 400 @app.route('/qiskit-service/api/v1.0/analysis', methods=['GET']) def get_analysis(): """Return analysis of all benchmarks saved in the database""" return jsonify(benchmarking.analyse()) @app.route('/qiskit-service/api/v1.0/analysis/<qpu_name>', methods=['GET']) def get_analysis_qpu(qpu_name): """Return analysis of all benchmarks from a specific quantum computer saved in the database""" benchmarks = Benchmark.query.all() list = [] for i in range(0, len(benchmarks), 2): if (benchmarks[i].complete and benchmarks[i + 1].complete) and ( benchmarks[i].benchmark_id == benchmarks[i + 1].benchmark_id) and ( benchmarks[i].result != "" and benchmarks[i + 1].result != "") and ( benchmarks[i + 1].backend == qpu_name): counts_sim = json.loads(benchmarks[i].counts) counts_real = json.loads(benchmarks[i + 1].counts) shots = benchmarks[i + 1].shots perc_error = analysis.calc_percentage_error(counts_sim, counts_real) correlation = analysis.calc_correlation(counts_sim.copy(), counts_real.copy(), shots) chi_square = analysis.calc_chi_square_distance(counts_sim.copy(), counts_real.copy()) intersection = analysis.calc_intersection(counts_sim.copy(), counts_real.copy(), shots) list.append({'benchmark-' + str(benchmarks[i].benchmark_id): { 'benchmark-location': '/qiskit-service/api/v1.0/benchmarks/' + str(benchmarks[i].benchmark_id), 'counts-sim': counts_sim, 'counts-real': counts_real, 'percentage-error': perc_error, 'chi-square': chi_square, 'correlation': correlation, 'histogram-intersection': intersection}}) return jsonify(list) @app.route('/qiskit-service/api/v1.0/version', methods=['GET']) def version(): return jsonify({'version': '1.0'}) def get_benchmark_body(benchmark_backend): return {'result-id': benchmark_backend.id, 'result-location': '/qiskit-service/api/v1.0/results/' + benchmark_backend.id, 'backend': benchmark_backend.backend, 'counts': json.loads(benchmark_backend.counts), 'original-depth': benchmark_backend.original_depth, 'original-width': benchmark_backend.original_width, 'original-number-of-multi-qubit-gates': benchmark_backend.original_number_of_multi_qubit_gates, 'transpiled-depth': benchmark_backend.transpiled_depth, 'transpiled-width': benchmark_backend.transpiled_width, 'transpiled-number-of-multi-qubit-gates': benchmark_backend.transpiled_number_of_multi_qubit_gates, 'clifford': benchmark_backend.clifford, 'benchmark-id': benchmark_backend.benchmark_id, 'complete': benchmark_backend.complete, 'shots': benchmark_backend.shots}
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for an Imaginary McLachlan's Variational Principle.""" from __future__ import annotations import warnings from collections.abc import Sequence import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import Estimator from qiskit.quantum_info.operators.base_operator import BaseOperator from .imaginary_variational_principle import ImaginaryVariationalPrinciple from ....exceptions import AlgorithmError from ....gradients import ( BaseEstimatorGradient, BaseQGT, DerivativeType, LinCombQGT, LinCombEstimatorGradient, ) class ImaginaryMcLachlanPrinciple(ImaginaryVariationalPrinciple): """Class for an Imaginary McLachlan's Variational Principle. It aims to minimize the distance between both sides of the Wick-rotated Schrödinger equation with a quantum state given as a parametrized trial state. The principle leads to a system of linear equations handled by a linear solver. The imaginary variant means that we consider imaginary time dynamics. """ def __init__( self, qgt: BaseQGT | None = None, gradient: BaseEstimatorGradient | None = None, ) -> None: """ Args: qgt: Instance of a the GQT class used to compute the QFI. If ``None`` provided, ``LinCombQGT`` is used. gradient: Instance of a class used to compute the state gradient. If ``None`` provided, ``LinCombEstimatorGradient`` is used. Raises: AlgorithmError: If the gradient instance does not contain an estimator. """ self._validate_grad_settings(gradient) if gradient is not None: try: estimator = gradient._estimator except Exception as exc: raise AlgorithmError( "The provided gradient instance does not contain an estimator primitive." ) from exc else: estimator = Estimator() gradient = LinCombEstimatorGradient(estimator) if qgt is None: qgt = LinCombQGT(estimator) super().__init__(qgt, gradient) def evolution_gradient( self, hamiltonian: BaseOperator, ansatz: QuantumCircuit, param_values: Sequence[float], gradient_params: Sequence[Parameter] | None = None, ) -> np.ndarray: """ Calculates an evolution gradient according to the rules of this variational principle. Args: hamiltonian: Operator used for Variational Quantum Time Evolution. ansatz: Quantum state in the form of a parametrized quantum circuit. param_values: Values of parameters to be bound. gradient_params: List of parameters with respect to which gradients should be computed. If ``None`` given, gradients w.r.t. all parameters will be computed. Returns: An evolution gradient. Raises: AlgorithmError: If a gradient job fails. """ try: evolution_grad_lse_rhs = ( self.gradient.run([ansatz], [hamiltonian], [param_values], [gradient_params]) .result() .gradients[0] ) except Exception as exc: raise AlgorithmError("The gradient primitive job failed!") from exc return -0.5 * evolution_grad_lse_rhs @staticmethod def _validate_grad_settings(gradient): if ( gradient is not None and hasattr(gradient, "_derivative_type") and gradient._derivative_type != DerivativeType.REAL ): warnings.warn( "A gradient instance with a setting for calculating imaginary part of " "the gradient was provided. This variational principle requires the" "real part. The setting to real was changed automatically." ) gradient._derivative_type = DerivativeType.REAL
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from math import pi import numpy as np import rustworkx as rx from qiskit_nature.second_q.hamiltonians.lattices import ( BoundaryCondition, HyperCubicLattice, Lattice, LatticeDrawStyle, LineLattice, SquareLattice, TriangularLattice, ) from qiskit_nature.second_q.hamiltonians import FermiHubbardModel num_nodes = 11 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() line_lattice.draw_without_boundary() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC edge_parameter = 1.0 + 1.0j onsite_parameter = 1.0 line_lattice = LineLattice( num_nodes=num_nodes, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(line_lattice.graph.weighted_edge_list()) line_lattice.to_adjacency_matrix() line_lattice.to_adjacency_matrix(weighted=True) rows = 5 cols = 4 boundary_condition = BoundaryCondition.OPEN square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 edge_parameter = (1.0, 1.0 + 1.0j) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction onsite_parameter = 1.0 square_lattice = SquareLattice( rows=rows, cols=cols, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(square_lattice.graph.weighted_edge_list()) size = (3, 4, 5) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.OPEN, BoundaryCondition.OPEN, ) cubic_lattice = HyperCubicLattice(size=size, boundary_condition=boundary_condition) # function for setting the positions def indextocoord_3d(index: int, size: tuple, angle) -> list: z = index // (size[0] * size[1]) a = index % (size[0] * size[1]) y = a // size[0] x = a % size[0] vec_x = np.array([1, 0]) vec_y = np.array([np.cos(angle), np.sin(angle)]) vec_z = np.array([0, 1]) return_coord = x * vec_x + y * vec_y + z * vec_z return return_coord.tolist() pos = dict([(index, indextocoord_3d(index, size, angle=pi / 4)) for index in range(np.prod(size))]) cubic_lattice.draw(style=LatticeDrawStyle(pos=pos)) rows = 4 cols = 3 boundary_condition = BoundaryCondition.OPEN triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() rows = 4 cols = 3 boundary_condition = BoundaryCondition.PERIODIC triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() graph = rx.PyGraph(multigraph=False) # multigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) # make a lattice general_lattice = Lattice(graph) set(general_lattice.graph.weighted_edge_list()) general_lattice.draw() general_lattice.draw(self_loop=True) general_lattice.draw(self_loop=True, style=LatticeDrawStyle(with_labels=True)) square_lattice = SquareLattice(rows=5, cols=4, boundary_condition=BoundaryCondition.PERIODIC) t = -1.0 # the interaction parameter v = 0.0 # the onsite potential u = 5.0 # the interaction parameter U fhm = FermiHubbardModel( square_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) ham = fhm.second_q_op().simplify() print(ham) graph = rx.PyGraph(multigraph=False) # multiigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) general_lattice = Lattice(graph) # the lattice whose weights are seen as the interaction matrix. u = 5.0 # the interaction parameter U fhm = FermiHubbardModel(lattice=general_lattice, onsite_interaction=u) ham = fhm.second_q_op().simplify() print(ham) from qiskit_nature.second_q.problems import LatticeModelProblem num_nodes = 4 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) fhm = FermiHubbardModel( line_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) lmp = LatticeModelProblem(fhm) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper numpy_solver = NumPyMinimumEigensolver() qubit_mapper = JordanWignerMapper() calc = GroundStateEigensolver(qubit_mapper, numpy_solver) res = calc.solve(lmp) print(res) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/matheusmtta/Quantum-Computing
matheusmtta
from qiskit import BasicAer, execute from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit.library.standard_gates import PhaseGate from qiskit.circuit.library.basis_change import QFT import math from src.util.util import run_qc q = QuantumRegister(3) b = QuantumRegister(1) c = ClassicalRegister(3) qc = QuantumCircuit(q, b, c) qc.x(q[0]) qc.draw(output='mpl') def increment(circuit, register, apply_QFT=True): q = register num = len(q) qc = circuit if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=num, approximation_degree=0, do_swaps=True, \ inverse=False, insert_barriers=True, name='qft')) qc.barrier() for i, qubit in enumerate(q): qc.rz(math.pi/2**(num-1-i), qubit) if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=num, approximation_degree=0, do_swaps=True, \ inverse=True, insert_barriers=True, name='iqft')) qc.barrier() return qc test = increment(qc, q) test.draw(output='mpl') def control_increment(circuit, qregister, cregister, apply_QFT=True): q = qregister c = cregister numq = len(q) numc = len(c) qc = circuit if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=numq, approximation_degree=0, do_swaps=True, \ inverse=False, insert_barriers=True, name='qft')) qc.barrier() for i, qubit in enumerate(q): ncp = PhaseGate(math.pi/2**(numq-i-1)).control(numc) qc.append(ncp, [*c, qubit]) if apply_QFT == True: qc.barrier() qc = qc.compose(QFT(num_qubits=numq, approximation_degree=0, do_swaps=True, \ inverse=True, insert_barriers=True, name='iqft')) qc.barrier() return qc test2 = control_increment(qc, q, b) test2.draw(output='mpl') ## Test increment without control test = increment(qc, q) test.measure(q[:], c[:]) run_qc(qc) test.draw(output='mpl') # Test control increment q = QuantumRegister(3) b = QuantumRegister(1) c = ClassicalRegister(3) qc = QuantumCircuit(q, b, c) qc.x(q[0]) qc = control_increment(qc, q, b) # Flipping control qubit to 1 qc.x(b[0]) qc = control_increment(qc, q, b) # Flipping control qubit to 1 qc.x(b[0]) qc = control_increment(qc, q, b) # Should equal 010 qc.measure(q[:], c[:]) run_qc(qc) qc.draw(output="mpl")
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/rickapocalypse/final_paper_qiskit_sat
rickapocalypse
""" Test Script """ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qrx = QuantumRegister(1, 'q0') qry = QuantumRegister(1, 'q1') cr = ClassicalRegister(1, 'c') qc = QuantumCircuit(qrx, qry, cr) qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() qc.x(qry) qc.barrier() qc.h(qrx) qc.h(qry) qc.measure(qrx, cr) qc.draw("mpl") from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram sim = AerSimulator() job = execute(qc, backend = sim, shots = 1000) result = job.result() counts = result.get_counts(qc) print("Counts: ", counts) plot_histogram(counts)
https://github.com/usamisaori/Grover
usamisaori
import qiskit from qiskit import QuantumCircuit from qiskit.visualization import plot_histogram import numpy as np from qiskit import execute, Aer simulator = Aer.get_backend('qasm_simulator') import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') from qiskit.quantum_info import DensityMatrix, Statevector, Operator def getDensityMatrix(circuit): return DensityMatrix(circuit).data state_0 = np.array([1, 0]) state_1 = np.array([0, 1]) from functools import reduce Dag = lambda matrix: matrix.conj().T Kron = lambda *matrices: reduce(np.kron, matrices) def pm(matrix): for row in range(len(matrix)): for col in range (len(matrix[row])): print("{:.3f}".format(matrix[row][col]), end = " ") print() # H R H, where R = 2|0><0| - I # A R A^(-1) def initAACircuit(n): circuit = QuantumCircuit(n, n) circuit.x(0) circuit.h(1) circuit.z(1) circuit.h(0) circuit.barrier() return circuit inputAACircuit = initAACircuit(2) inputAACircuit.draw(output='mpl') A = Operator(initAACircuit(2)) np.allclose(A.data @ Dag(A.data), np.eye(4)) inputAACircuit.measure([0, 1], [0, 1]) job = execute(inputAACircuit, simulator, shots = 10000) results = job.result() counts = results.get_counts(inputAACircuit) print(counts) plot_histogram(counts, figsize=(7, 5), color="#CCCC66", title="measurements result of A") def createOracle_3(): circuit = QuantumCircuit(2, 2) # Oracle for find 3 # U_f circuit.cz(0, 1) circuit.barrier() return circuit oracleCircuit_3 = createOracle_3() oracleCircuit_3.draw(output='mpl') def createR_2q(): circuit = QuantumCircuit(2, 2) circuit.z(0) circuit.z(1) circuit.cz(0, 1) return circuit def createAADiffuser(): circuit = QuantumCircuit(2, 2) circuit.append(A, [0, 1]) circuit = circuit.compose(createR_2q()) circuit.append(A.conjugate(), [0, 1]) circuit.barrier() return circuit diffuserAACircuit = createAADiffuser() diffuserAACircuit.draw(output='mpl') def createGroverIteration(oracle, diffuser): return oracle.compose(diffuser) aaGroverIteration = createGroverIteration(createOracle_3(), createAADiffuser()) aaGroverIteration.draw(output='mpl') def createDiffuser_2q(): circuit = QuantumCircuit(2, 2) circuit.h(0) circuit.h(1) circuit = circuit.compose(createR_2q()) circuit.h(0) circuit.h(1) circuit.barrier() return circuit incorrectGroverIteration = createGroverIteration(createOracle_3(), createDiffuser_2q()) grover_incorrect_diffuser = initAACircuit(2).compose(incorrectGroverIteration) grover_incorrect_diffuser.draw(output='mpl') grover_incorrect_diffuser.measure([0, 1], [0, 1]) job = execute(grover_incorrect_diffuser, simulator, shots = 10000) results = job.result() counts = results.get_counts(grover_incorrect_diffuser) print(counts) plot_histogram(counts, figsize=(1, 5), color="#99CC33", title="using incorrect diffuser - find 3") ### 3.5.2 correct diffuser
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit.random import random_circuit circuit = random_circuit(2, 2, seed=0).decompose(reps=1) display(circuit.draw("mpl")) from qiskit.quantum_info import SparsePauliOp observable = SparsePauliOp("XZ") print(f">>> Observable: {observable.paulis}") from qiskit.primitives import Estimator estimator = Estimator() job = estimator.run(circuit, observable) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() print(f">>> {result}") print(f" > Expectation value: {result.values[0]}") circuit = random_circuit(2, 2, seed=1).decompose(reps=1) observable = SparsePauliOp("IY") job = estimator.run(circuit, observable) result = job.result() display(circuit.draw("mpl")) print(f">>> Observable: {observable.paulis}") print(f">>> Expectation value: {result.values[0]}") circuits = ( random_circuit(2, 2, seed=0).decompose(reps=1), random_circuit(2, 2, seed=1).decompose(reps=1), ) observables = ( SparsePauliOp("XZ"), SparsePauliOp("IY"), ) job = estimator.run(circuits, observables) result = job.result() [display(cir.draw("mpl")) for cir in circuits] print(f">>> Observables: {[obs.paulis for obs in observables]}") print(f">>> Expectation values: {result.values.tolist()}") from qiskit.circuit.library import RealAmplitudes circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1) observable = SparsePauliOp("ZI") parameter_values = [0, 1, 2, 3, 4, 5] job = estimator.run(circuit, observable, parameter_values) result = job.result() display(circuit.draw("mpl")) print(f">>> Observable: {observable.paulis}") print(f">>> Parameter values: {parameter_values}") print(f">>> Expectation value: {result.values[0]}") from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_quantum") backend = service.backend("ibmq_qasm_simulator") from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp circuit = random_circuit(2, 2, seed=0).decompose(reps=1) display(circuit.draw("mpl")) observable = SparsePauliOp("XZ") print(f">>> Observable: {observable.paulis}") from qiskit_ibm_runtime import Estimator estimator = Estimator(session=backend) job = estimator.run(circuit, observable) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() print(f">>> {result}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Options options = Options(optimization_level=3, environment={"log_level": "INFO"}) from qiskit_ibm_runtime import Options options = Options() options.resilience_level = 1 options.execution.shots = 2048 estimator = Estimator(session=backend, options=options) result = estimator.run(circuit, observable).result() print(f">>> Metadata: {result.metadata[0]}") estimator = Estimator(session=backend, options=options) result = estimator.run(circuit, observable, shots=1024).result() print(f">>> Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Options # optimization_level=3 adds dynamical decoupling # resilience_level=1 adds readout error mitigation options = Options(optimization_level=3, resilience_level=1) estimator = Estimator(session=backend, options=options) result = estimator.run(circuit, observable).result() print(f">>> Expectation value: {result.values[0]}") print(f">>> Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Session, Estimator with Session(backend=backend, max_time="1h"): estimator = Estimator() result = estimator.run(circuit, observable).result() print(f">>> Expectation value from the first run: {result.values[0]}") result = estimator.run(circuit, observable).result() print(f">>> Expectation value from the second run: {result.values[0]}") from qiskit.circuit.random import random_circuit sampler_circuit = random_circuit(2, 2, seed=0).decompose(reps=1) sampler_circuit.measure_all() display(circuit.draw("mpl")) from qiskit_ibm_runtime import Session, Sampler, Estimator with Session(backend=backend): sampler = Sampler() estimator = Estimator() result = sampler.run(sampler_circuit).result() print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}") result = estimator.run(circuit, observable).result() print(f">>> Expectation value from the estimator job: {result.values[0]}") from qiskit_ibm_runtime import Session, Sampler, Estimator with Session(backend=backend): sampler = Sampler() estimator = Estimator() sampler_job = sampler.run(sampler_circuit) estimator_job = estimator.run(circuit, observable) print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}") print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}") from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options # 1. Initialize account service = QiskitRuntimeService(channel="ibm_quantum") # 2. Specify options, such as enabling error mitigation options = Options(resilience_level=1) # 3. Select a backend. backend = service.backend("ibmq_qasm_simulator") # 4. Create a session with Session(backend=backend): # 5. Create primitive instances sampler = Sampler(options=options) estimator = Estimator(options=options) # 6. Submit jobs sampler_job = sampler.run(sampler_circuit) estimator_job = estimator.run(circuit, observable) # 7. Get results print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}") print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}") import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table %qiskit_copyright
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. # pylint: disable=cyclic-import """ ========= Schedules ========= .. currentmodule:: qiskit.pulse Schedules are Pulse programs. They describe instruction sequences for the control hardware. The Schedule is one of the most fundamental objects to this pulse-level programming module. A ``Schedule`` is a representation of a *program* in Pulse. Each schedule tracks the time of each instruction occuring in parallel over multiple signal *channels*. .. autosummary:: :toctree: ../stubs/ Schedule ScheduleBlock """ import abc import copy import functools import itertools import multiprocessing as mp import re import sys import warnings from typing import List, Tuple, Iterable, Union, Dict, Callable, Set, Optional, Any import numpy as np import rustworkx as rx from qiskit.circuit.parameter import Parameter from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType from qiskit.pulse.channels import Channel from qiskit.pulse.exceptions import PulseError, UnassignedReferenceError from qiskit.pulse.instructions import Instruction, Reference from qiskit.pulse.utils import instruction_duration_validation from qiskit.pulse.reference_manager import ReferenceManager from qiskit.utils.multiprocessing import is_main_process Interval = Tuple[int, int] """An interval type is a tuple of a start time (inclusive) and an end time (exclusive).""" TimeSlots = Dict[Channel, List[Interval]] """List of timeslots occupied by instructions for each channel.""" class Schedule: """A quantum program *schedule* with exact time constraints for its instructions, operating over all input signal *channels* and supporting special syntaxes for building. Pulse program representation for the original Qiskit Pulse model [1]. Instructions are not allowed to overlap in time on the same channel. This overlap constraint is immediately evaluated when a new instruction is added to the ``Schedule`` object. It is necessary to specify the absolute start time and duration for each instruction so as to deterministically fix its execution time. The ``Schedule`` program supports some syntax sugar for easier programming. - Appending an instruction to the end of a channel .. code-block:: python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) - Appending an instruction shifted in time by a given amount .. code-block:: python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) << 30 - Merge two schedules .. code-block:: python sched1 = Schedule() sched1 += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) sched2 = Schedule() sched2 += Play(Gaussian(160, 0.1, 40), DriveChannel(1)) sched2 = sched1 | sched2 A :obj:`.PulseError` is immediately raised when the overlap constraint is violated. In the schedule representation, we cannot parametrize the duration of instructions. Thus we need to create a new schedule object for each duration. To parametrize an instruction's duration, the :class:`~qiskit.pulse.ScheduleBlock` representation may be used instead. References: [1]: https://arxiv.org/abs/2004.06755 """ # Prefix to use for auto naming. prefix = "sched" # Counter to count instance number. instances_counter = itertools.count() def __init__( self, *schedules: Union["ScheduleComponent", Tuple[int, "ScheduleComponent"]], name: Optional[str] = None, metadata: Optional[dict] = None, ): """Create an empty schedule. Args: *schedules: Child Schedules of this parent Schedule. May either be passed as the list of schedules, or a list of ``(start_time, schedule)`` pairs. name: Name of this schedule. Defaults to an autogenerated string if not provided. metadata: Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the :attr:`~qiskit.pulse.Schedule.metadata` attribute. It will not be directly used in the schedule. Raises: TypeError: if metadata is not a dict. """ from qiskit.pulse.parameter_manager import ParameterManager if name is None: name = self.prefix + str(next(self.instances_counter)) if sys.platform != "win32" and not is_main_process(): name += f"-{mp.current_process().pid}" self._name = name self._parameter_manager = ParameterManager() if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} self._duration = 0 # These attributes are populated by ``_mutable_insert`` self._timeslots = {} self._children = [] for sched_pair in schedules: try: time, sched = sched_pair except TypeError: # recreate as sequence starting at 0. time, sched = 0, sched_pair self._mutable_insert(time, sched) @classmethod def initialize_from(cls, other_program: Any, name: Optional[str] = None) -> "Schedule": """Create new schedule object with metadata of another schedule object. Args: other_program: Qiskit program that provides metadata to new object. name: Name of new schedule. Name of ``schedule`` is used by default. Returns: New schedule object with name and metadata. Raises: PulseError: When `other_program` does not provide necessary information. """ try: name = name or other_program.name if other_program.metadata: metadata = other_program.metadata.copy() else: metadata = None return cls(name=name, metadata=metadata) except AttributeError as ex: raise PulseError( f"{cls.__name__} cannot be initialized from the program data " f"{other_program.__class__.__name__}." ) from ex @property def name(self) -> str: """Name of this Schedule""" return self._name @property def metadata(self) -> Dict[str, Any]: """The user provided metadata associated with the schedule. User provided ``dict`` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. """ return self._metadata @metadata.setter def metadata(self, metadata): """Update the schedule metadata""" if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @property def timeslots(self) -> TimeSlots: """Time keeping attribute.""" return self._timeslots @property def duration(self) -> int: """Duration of this schedule.""" return self._duration @property def start_time(self) -> int: """Starting time of this schedule.""" return self.ch_start_time(*self.channels) @property def stop_time(self) -> int: """Stopping time of this schedule.""" return self.duration @property def channels(self) -> Tuple[Channel]: """Returns channels that this schedule uses.""" return tuple(self._timeslots.keys()) @property def children(self) -> Tuple[Tuple[int, "ScheduleComponent"], ...]: """Return the child schedule components of this ``Schedule`` in the order they were added to the schedule. Notes: Nested schedules are returned as-is. If you want to collect only instructions, use py:meth:`~Schedule.instructions` instead. Returns: A tuple, where each element is a two-tuple containing the initial scheduled time of each ``NamedValue`` and the component itself. """ return tuple(self._children) @property def instructions(self) -> Tuple[Tuple[int, Instruction]]: """Get the time-ordered instructions from self.""" def key(time_inst_pair): inst = time_inst_pair[1] return time_inst_pair[0], inst.duration, sorted(chan.name for chan in inst.channels) return tuple(sorted(self._instructions(), key=key)) @property def parameters(self) -> Set: """Parameters which determine the schedule behavior.""" return self._parameter_manager.parameters def ch_duration(self, *channels: Channel) -> int: """Return the time of the end of the last instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ return self.ch_stop_time(*channels) def ch_start_time(self, *channels: Channel) -> int: """Return the time of the start of the first instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ try: chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots) return min(intervals[0][0] for intervals in chan_intervals) except ValueError: # If there are no instructions over channels return 0 def ch_stop_time(self, *channels: Channel) -> int: """Return maximum start time over supplied channels. Args: *channels: Channels within ``self`` to include. """ try: chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots) return max(intervals[-1][1] for intervals in chan_intervals) except ValueError: # If there are no instructions over channels return 0 def _instructions(self, time: int = 0): """Iterable for flattening Schedule tree. Args: time: Shifted time due to parent. Yields: Iterable[Tuple[int, Instruction]]: Tuple containing the time each :class:`~qiskit.pulse.Instruction` starts at and the flattened :class:`~qiskit.pulse.Instruction` s. """ for insert_time, child_sched in self.children: yield from child_sched._instructions(time + insert_time) def shift(self, time: int, name: Optional[str] = None, inplace: bool = False) -> "Schedule": """Return a schedule shifted forward by ``time``. Args: time: Time to shift by. name: Name of the new schedule. Defaults to the name of self. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ if inplace: return self._mutable_shift(time) return self._immutable_shift(time, name=name) def _immutable_shift(self, time: int, name: Optional[str] = None) -> "Schedule": """Return a new schedule shifted forward by `time`. Args: time: Time to shift by name: Name of the new schedule if call was mutable. Defaults to name of self """ shift_sched = Schedule.initialize_from(self, name) shift_sched.insert(time, self, inplace=True) return shift_sched def _mutable_shift(self, time: int) -> "Schedule": """Return this schedule shifted forward by `time`. Args: time: Time to shift by Raises: PulseError: if ``time`` is not an integer. """ if not isinstance(time, int): raise PulseError("Schedule start time must be an integer.") timeslots = {} for chan, ch_timeslots in self._timeslots.items(): timeslots[chan] = [(ts[0] + time, ts[1] + time) for ts in ch_timeslots] _check_nonnegative_timeslot(timeslots) self._duration = self._duration + time self._timeslots = timeslots self._children = [(orig_time + time, child) for orig_time, child in self.children] return self def insert( self, start_time: int, schedule: "ScheduleComponent", name: Optional[str] = None, inplace: bool = False, ) -> "Schedule": """Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``. Args: start_time: Time to insert the schedule. schedule: Schedule to insert. name: Name of the new schedule. Defaults to the name of self. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ if inplace: return self._mutable_insert(start_time, schedule) return self._immutable_insert(start_time, schedule, name=name) def _mutable_insert(self, start_time: int, schedule: "ScheduleComponent") -> "Schedule": """Mutably insert `schedule` into `self` at `start_time`. Args: start_time: Time to insert the second schedule. schedule: Schedule to mutably insert. """ self._add_timeslots(start_time, schedule) self._children.append((start_time, schedule)) self._parameter_manager.update_parameter_table(schedule) return self def _immutable_insert( self, start_time: int, schedule: "ScheduleComponent", name: Optional[str] = None, ) -> "Schedule": """Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``. Args: start_time: Time to insert the schedule. schedule: Schedule to insert. name: Name of the new ``Schedule``. Defaults to name of ``self``. """ new_sched = Schedule.initialize_from(self, name) new_sched._mutable_insert(0, self) new_sched._mutable_insert(start_time, schedule) return new_sched def append( self, schedule: "ScheduleComponent", name: Optional[str] = None, inplace: bool = False ) -> "Schedule": r"""Return a new schedule with ``schedule`` inserted at the maximum time over all channels shared between ``self`` and ``schedule``. .. math:: t = \textrm{max}(\texttt{x.stop_time} |\texttt{x} \in \texttt{self.channels} \cap \texttt{schedule.channels}) Args: schedule: Schedule to be appended. name: Name of the new ``Schedule``. Defaults to name of ``self``. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ common_channels = set(self.channels) & set(schedule.channels) time = self.ch_stop_time(*common_channels) return self.insert(time, schedule, name=name, inplace=inplace) def filter( self, *filter_funcs: Callable, channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, time_ranges: Optional[Iterable[Tuple[int, int]]] = None, intervals: Optional[Iterable[Interval]] = None, check_subroutine: bool = True, ) -> "Schedule": """Return a new ``Schedule`` with only the instructions from this ``Schedule`` which pass though the provided filters; i.e. an instruction will be retained iff every function in ``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in ``channels``, the instruction type is contained in ``instruction_types``, and the period over which the instruction operates is *fully* contained in one specified in ``time_ranges`` or ``intervals``. If no arguments are provided, ``self`` is returned. Args: filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction]) tuple and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types, time_ranges, intervals) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=False, recurse_subroutines=check_subroutine ) def exclude( self, *filter_funcs: Callable, channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, time_ranges: Optional[Iterable[Tuple[int, int]]] = None, intervals: Optional[Iterable[Interval]] = None, check_subroutine: bool = True, ) -> "Schedule": """Return a ``Schedule`` with only the instructions from this Schedule *failing* at least one of the provided filters. This method is the complement of py:meth:`~self.filter`, so that:: self.filter(args) | self.exclude(args) == self Args: filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction]) tuple and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types, time_ranges, intervals) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=True, recurse_subroutines=check_subroutine ) def _add_timeslots(self, time: int, schedule: "ScheduleComponent") -> None: """Update all time tracking within this schedule based on the given schedule. Args: time: The time to insert the schedule into self. schedule: The schedule to insert into self. Raises: PulseError: If timeslots overlap or an invalid start time is provided. """ if not np.issubdtype(type(time), np.integer): raise PulseError("Schedule start time must be an integer.") other_timeslots = _get_timeslots(schedule) self._duration = max(self._duration, time + schedule.duration) for channel in schedule.channels: if channel not in self._timeslots: if time == 0: self._timeslots[channel] = copy.copy(other_timeslots[channel]) else: self._timeslots[channel] = [ (i[0] + time, i[1] + time) for i in other_timeslots[channel] ] continue for idx, interval in enumerate(other_timeslots[channel]): if interval[0] + time >= self._timeslots[channel][-1][1]: # Can append the remaining intervals self._timeslots[channel].extend( [(i[0] + time, i[1] + time) for i in other_timeslots[channel][idx:]] ) break try: interval = (interval[0] + time, interval[1] + time) index = _find_insertion_index(self._timeslots[channel], interval) self._timeslots[channel].insert(index, interval) except PulseError as ex: raise PulseError( "Schedule(name='{new}') cannot be inserted into Schedule(name='{old}') at " "time {time} because its instruction on channel {ch} scheduled from time " "{t0} to {tf} overlaps with an existing instruction." "".format( new=schedule.name or "", old=self.name or "", time=time, ch=channel, t0=interval[0], tf=interval[1], ) ) from ex _check_nonnegative_timeslot(self._timeslots) def _remove_timeslots(self, time: int, schedule: "ScheduleComponent"): """Delete the timeslots if present for the respective schedule component. Args: time: The time to remove the timeslots for the ``schedule`` component. schedule: The schedule to insert into self. Raises: PulseError: If timeslots overlap or an invalid start time is provided. """ if not isinstance(time, int): raise PulseError("Schedule start time must be an integer.") for channel in schedule.channels: if channel not in self._timeslots: raise PulseError(f"The channel {channel} is not present in the schedule") channel_timeslots = self._timeslots[channel] other_timeslots = _get_timeslots(schedule) for interval in other_timeslots[channel]: if channel_timeslots: interval = (interval[0] + time, interval[1] + time) index = _interval_index(channel_timeslots, interval) if channel_timeslots[index] == interval: channel_timeslots.pop(index) continue raise PulseError( "Cannot find interval ({t0}, {tf}) to remove from " "channel {ch} in Schedule(name='{name}').".format( ch=channel, t0=interval[0], tf=interval[1], name=schedule.name ) ) if not channel_timeslots: self._timeslots.pop(channel) def _replace_timeslots(self, time: int, old: "ScheduleComponent", new: "ScheduleComponent"): """Replace the timeslots of ``old`` if present with the timeslots of ``new``. Args: time: The time to remove the timeslots for the ``schedule`` component. old: Instruction to replace. new: Instruction to replace with. """ self._remove_timeslots(time, old) self._add_timeslots(time, new) def _renew_timeslots(self): """Regenerate timeslots based on current instructions.""" self._timeslots.clear() for t0, inst in self.instructions: self._add_timeslots(t0, inst) def replace( self, old: "ScheduleComponent", new: "ScheduleComponent", inplace: bool = False, ) -> "Schedule": """Return a ``Schedule`` with the ``old`` instruction replaced with a ``new`` instruction. The replacement matching is based on an instruction equality check. .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) sched = pulse.Schedule() old = pulse.Play(pulse.Constant(100, 1.0), d0) new = pulse.Play(pulse.Constant(100, 0.1), d0) sched += old sched = sched.replace(old, new) assert sched == pulse.Schedule(new) Only matches at the top-level of the schedule tree. If you wish to perform this replacement over all instructions in the schedule tree. Flatten the schedule prior to running:: .. code-block:: sched = pulse.Schedule() sched += pulse.Schedule(old) sched = sched.flatten() sched = sched.replace(old, new) assert sched == pulse.Schedule(new) Args: old: Instruction to replace. new: Instruction to replace with. inplace: Replace instruction by mutably modifying this ``Schedule``. Returns: The modified schedule with ``old`` replaced by ``new``. Raises: PulseError: If the ``Schedule`` after replacements will has a timing overlap. """ from qiskit.pulse.parameter_manager import ParameterManager new_children = [] new_parameters = ParameterManager() for time, child in self.children: if child == old: new_children.append((time, new)) new_parameters.update_parameter_table(new) else: new_children.append((time, child)) new_parameters.update_parameter_table(child) if inplace: self._children = new_children self._parameter_manager = new_parameters self._renew_timeslots() return self else: try: new_sched = Schedule.initialize_from(self) for time, inst in new_children: new_sched.insert(time, inst, inplace=True) return new_sched except PulseError as err: raise PulseError( f"Replacement of {old} with {new} results in overlapping instructions." ) from err def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return self._parameter_manager.is_parameterized() def assign_parameters( self, value_dict: Dict[ParameterExpression, ParameterValueType], inplace: bool = True ) -> "Schedule": """Assign the parameters in this schedule according to the input. Args: value_dict: A mapping from Parameters to either numeric values or another Parameter expression. inplace: Set ``True`` to override this instance with new parameter. Returns: Schedule with updated parameters. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_parameters(value_dict, inplace=True) return self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict) def get_parameters(self, parameter_name: str) -> List[Parameter]: """Get parameter object bound to this schedule by string name. Because different ``Parameter`` objects can have the same name, this method returns a list of ``Parameter`` s for the provided name. Args: parameter_name: Name of parameter. Returns: Parameter objects that have corresponding name. """ return self._parameter_manager.get_parameters(parameter_name) def __len__(self) -> int: """Return number of instructions in the schedule.""" return len(self.instructions) def __add__(self, other: "ScheduleComponent") -> "Schedule": """Return a new schedule with ``other`` inserted within ``self`` at ``start_time``.""" return self.append(other) def __or__(self, other: "ScheduleComponent") -> "Schedule": """Return a new schedule which is the union of `self` and `other`.""" return self.insert(0, other) def __lshift__(self, time: int) -> "Schedule": """Return a new schedule which is shifted forward by ``time``.""" return self.shift(time) def __eq__(self, other: "ScheduleComponent") -> bool: """Test if two Schedule are equal. Equality is checked by verifying there is an equal instruction at every time in ``other`` for every instruction in this ``Schedule``. .. warning:: This does not check for logical equivalency. Ie., ```python >>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0)) == Delay(20, DriveChannel(0)) False ``` """ # 0. type check, we consider Instruction is a subtype of schedule if not isinstance(other, (type(self), Instruction)): return False # 1. channel check if set(self.channels) != set(other.channels): return False # 2. size check if len(self.instructions) != len(other.instructions): return False # 3. instruction check return all( self_inst == other_inst for self_inst, other_inst in zip(self.instructions, other.instructions) ) def __repr__(self) -> str: name = format(self._name) if self._name else "" instructions = ", ".join([repr(instr) for instr in self.instructions[:50]]) if len(self.instructions) > 25: instructions += ", ..." return f'{self.__class__.__name__}({instructions}, name="{name}")' def _require_schedule_conversion(function: Callable) -> Callable: """A method decorator to convert schedule block to pulse schedule. This conversation is performed for backward compatibility only if all durations are assigned. """ @functools.wraps(function) def wrapper(self, *args, **kwargs): from qiskit.pulse.transforms import block_to_schedule return function(block_to_schedule(self), *args, **kwargs) return wrapper class ScheduleBlock: """Time-ordered sequence of instructions with alignment context. :class:`.ScheduleBlock` supports lazy scheduling of context instructions, i.e. their timeslots is always generated at runtime. This indicates we can parametrize instruction durations as well as other parameters. In contrast to :class:`.Schedule` being somewhat static, :class:`.ScheduleBlock` is a dynamic representation of a pulse program. .. rubric:: Pulse Builder The Qiskit pulse builder is a domain specific language that is developed on top of the schedule block. Use of the builder syntax will improve the workflow of pulse programming. See :ref:`pulse_builder` for a user guide. .. rubric:: Alignment contexts A schedule block is always relatively scheduled. Instead of taking individual instructions with absolute execution time ``t0``, the schedule block defines a context of scheduling and instructions under the same context are scheduled in the same manner (alignment). Several contexts are available in :ref:`pulse_alignments`. A schedule block is instantiated with one of these alignment contexts. The default context is :class:`AlignLeft`, for which all instructions are left-justified, in other words, meaning they use as-soon-as-possible scheduling. If you need an absolute-time interval in between instructions, you can explicitly insert :class:`~qiskit.pulse.instructions.Delay` instructions. .. rubric:: Nested blocks A schedule block can contain other nested blocks with different alignment contexts. This enables advanced scheduling, where a subset of instructions is locally scheduled in a different manner. Note that a :class:`.Schedule` instance cannot be directly added to a schedule block. To add a :class:`.Schedule` instance, wrap it in a :class:`.Call` instruction. This is implicitly performed when a schedule is added through the :ref:`pulse_builder`. .. rubric:: Unsupported operations Because the schedule block representation lacks timeslots, it cannot perform particular :class:`.Schedule` operations such as :meth:`insert` or :meth:`shift` that require instruction start time ``t0``. In addition, :meth:`exclude` and :meth:`filter` methods are not supported because these operations may identify the target instruction with ``t0``. Except for these operations, :class:`.ScheduleBlock` provides full compatibility with :class:`.Schedule`. .. rubric:: Subroutine The timeslots-free representation offers much greater flexibility for writing pulse programs. Because :class:`.ScheduleBlock` only cares about the ordering of the child blocks we can add an undefined pulse sequence as a subroutine of the main program. If your program contains the same sequence multiple times, this representation may reduce the memory footprint required by the program construction. Such a subroutine is realized by the special compiler directive :class:`~qiskit.pulse.instructions.Reference` that is defined by a unique set of reference key strings to the subroutine. The (executable) subroutine is separately stored in the main program. Appended reference directives are resolved when the main program is executed. Subroutines must be assigned through :meth:`assign_references` before execution. .. rubric:: Program Scoping When you call a subroutine from another subroutine, or append a schedule block to another schedule block, the management of references and parameters can be a hard task. Schedule block offers a convenient feature to help with this by automatically scoping the parameters and subroutines. .. code-block:: from qiskit import pulse from qiskit.circuit.parameter import Parameter amp1 = Parameter("amp") with pulse.build() as sched1: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) print(sched1.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp),) The :meth:`~ScheduleBlock.scoped_parameters` method returns all :class:`~.Parameter` objects defined in the schedule block. The parameter name is updated to reflect its scope information, i.e. where it is defined. The outer scope is called "root". Since the "amp" parameter is directly used in the current builder context, it is prefixed with "root". Note that the :class:`Parameter` object returned by :meth:`~ScheduleBlock.scoped_parameters` preserves the hidden `UUID`_ key, and thus the scoped name doesn't break references to the original :class:`Parameter`. You may want to call this program from another program. In this example, the program is called with the reference key "grand_child". You can call a subroutine without specifying a substantial program (like ``sched1`` above which we will assign later). .. code-block:: amp2 = Parameter("amp") with pulse.build() as sched2: with pulse.align_right(): pulse.reference("grand_child") pulse.play(pulse.Constant(200, amp2), pulse.DriveChannel(0)) print(sched2.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp),) This only returns "root::amp" because the "grand_child" reference is unknown. Now you assign the actual pulse program to this reference. .. code-block:: sched2.assign_references({("grand_child", ): sched1}) print(sched2.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp), Parameter(root::grand_child::amp)) Now you get two parameters "root::amp" and "root::grand_child::amp". The second parameter name indicates it is defined within the referred program "grand_child". The program calling the "grand_child" has a reference program description which is accessed through :attr:`ScheduleBlock.references`. .. code-block:: print(sched2.references) .. parsed-literal:: ReferenceManager: - ('grand_child',): ScheduleBlock(Play(Constant(duration=100, amp=amp,... Finally, you may want to call this program from another program. Here we try a different approach to define subroutine. Namely, we call a subroutine from the root program with the actual program ``sched2``. .. code-block:: amp3 = Parameter("amp") with pulse.build() as main: pulse.play(pulse.Constant(300, amp3), pulse.DriveChannel(0)) pulse.call(sched2, name="child") print(main.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp), Parameter(root::child::amp), Parameter(root::child::grand_child::amp)) This implicitly creates a reference named "child" within the root program and assigns ``sched2`` to it. You get three parameters "root::amp", "root::child::amp", and "root::child::grand_child::amp". As you can see, each parameter name reflects the layer of calls from the root program. If you know the scope of a parameter, you can directly get the parameter object using :meth:`ScheduleBlock.search_parameters` as follows. .. code-block:: main.search_parameters("root::child::grand_child::amp") You can use a regular expression to specify the scope. The following returns the parameters defined within the scope of "ground_child" regardless of its parent scope. This is sometimes convenient if you want to extract parameters from a deeply nested program. .. code-block:: main.search_parameters("\\S::grand_child::amp") Note that the root program is only aware of its direct references. .. code-block:: print(main.references) .. parsed-literal:: ReferenceManager: - ('child',): ScheduleBlock(ScheduleBlock(ScheduleBlock(Play(Con... As you can see the main program cannot directly assign a subroutine to the "grand_child" because this subroutine is not called within the root program, i.e. it is indirectly called by "child". However, the returned :class:`.ReferenceManager` is a dict-like object, and you can still reach to "grand_child" via the "child" program with the following chained dict access. .. code-block:: main.references[("child", )].references[("grand_child", )] Note that :attr:`ScheduleBlock.parameters` and :meth:`ScheduleBlock.scoped_parameters()` still collect all parameters also from the subroutine once it's assigned. .. _UUID: https://docs.python.org/3/library/uuid.html#module-uuid """ __slots__ = ( "_parent", "_name", "_reference_manager", "_parameter_manager", "_alignment_context", "_blocks", "_metadata", ) # Prefix to use for auto naming. prefix = "block" # Counter to count instance number. instances_counter = itertools.count() def __init__( self, name: Optional[str] = None, metadata: Optional[dict] = None, alignment_context=None ): """Create an empty schedule block. Args: name: Name of this schedule. Defaults to an autogenerated string if not provided. metadata: Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the :attr:`~qiskit.pulse.ScheduleBlock.metadata` attribute. It will not be directly used in the schedule. alignment_context (AlignmentKind): ``AlignmentKind`` instance that manages scheduling of instructions in this block. Raises: TypeError: if metadata is not a dict. """ from qiskit.pulse.parameter_manager import ParameterManager from qiskit.pulse.transforms import AlignLeft if name is None: name = self.prefix + str(next(self.instances_counter)) if sys.platform != "win32" and not is_main_process(): name += f"-{mp.current_process().pid}" # This points to the parent schedule object in the current scope. # Note that schedule block can be nested without referencing, e.g. .append(child_block), # and parent=None indicates the root program of the current scope. # The nested schedule block objects should not have _reference_manager and # should refer to the one of the root program. # This also means referenced program should be assigned to the root program, not to child. self._parent = None self._name = name self._parameter_manager = ParameterManager() self._reference_manager = ReferenceManager() self._alignment_context = alignment_context or AlignLeft() self._blocks = [] # get parameters from context self._parameter_manager.update_parameter_table(self._alignment_context) if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @classmethod def initialize_from(cls, other_program: Any, name: Optional[str] = None) -> "ScheduleBlock": """Create new schedule object with metadata of another schedule object. Args: other_program: Qiskit program that provides metadata to new object. name: Name of new schedule. Name of ``block`` is used by default. Returns: New block object with name and metadata. Raises: PulseError: When ``other_program`` does not provide necessary information. """ try: name = name or other_program.name if other_program.metadata: metadata = other_program.metadata.copy() else: metadata = None try: alignment_context = other_program.alignment_context except AttributeError: alignment_context = None return cls(name=name, metadata=metadata, alignment_context=alignment_context) except AttributeError as ex: raise PulseError( f"{cls.__name__} cannot be initialized from the program data " f"{other_program.__class__.__name__}." ) from ex @property def name(self) -> str: """Return name of this schedule""" return self._name @property def metadata(self) -> Dict[str, Any]: """The user provided metadata associated with the schedule. User provided ``dict`` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. """ return self._metadata @metadata.setter def metadata(self, metadata): """Update the schedule metadata""" if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @property def alignment_context(self): """Return alignment instance that allocates block component to generate schedule.""" return self._alignment_context def is_schedulable(self) -> bool: """Return ``True`` if all durations are assigned.""" # check context assignment for context_param in self._alignment_context._context_params: if isinstance(context_param, ParameterExpression): return False # check duration assignment for elm in self.blocks: if isinstance(elm, ScheduleBlock): if not elm.is_schedulable(): return False else: try: if not isinstance(elm.duration, int): return False except UnassignedReferenceError: return False return True @property @_require_schedule_conversion def duration(self) -> int: """Duration of this schedule block.""" return self.duration @property def channels(self) -> Tuple[Channel]: """Returns channels that this schedule block uses.""" chans = set() for elm in self.blocks: if isinstance(elm, Reference): raise UnassignedReferenceError( f"This schedule contains unassigned reference {elm.ref_keys} " "and channels are ambiguous. Please assign the subroutine first." ) chans = chans | set(elm.channels) return tuple(chans) @property @_require_schedule_conversion def instructions(self) -> Tuple[Tuple[int, Instruction]]: """Get the time-ordered instructions from self.""" return self.instructions @property def blocks(self) -> Tuple["BlockComponent", ...]: """Get the block elements added to self. .. note:: The sequence of elements is returned in order of addition. Because the first element is schedule first, e.g. FIFO, the returned sequence is roughly time-ordered. However, in the parallel alignment context, especially in the as-late-as-possible scheduling, or :class:`.AlignRight` context, the actual timing of when the instructions are issued is unknown until the :class:`.ScheduleBlock` is scheduled and converted into a :class:`.Schedule`. """ blocks = [] for elm in self._blocks: if isinstance(elm, Reference): elm = self.references.get(elm.ref_keys, None) or elm blocks.append(elm) return tuple(blocks) @property def parameters(self) -> Set[Parameter]: """Return unassigned parameters with raw names.""" # Need new object not to mutate parameter_manager.parameters out_params = set() out_params |= self._parameter_manager.parameters for subroutine in self.references.values(): if subroutine is None: continue out_params |= subroutine.parameters return out_params def scoped_parameters(self) -> Tuple[Parameter]: """Return unassigned parameters with scoped names. .. note:: If a parameter is defined within a nested scope, it is prefixed with all parent-scope names with the delimiter string, which is "::". If a reference key of the scope consists of multiple key strings, it will be represented by a single string joined with ",". For example, "root::xgate,q0::amp" for the parameter "amp" defined in the reference specified by the key strings ("xgate", "q0"). """ return tuple( sorted( _collect_scoped_parameters(self, current_scope="root").values(), key=lambda p: p.name, ) ) @property def references(self) -> ReferenceManager: """Return a reference manager of the current scope.""" if self._parent is not None: return self._parent.references return self._reference_manager @_require_schedule_conversion def ch_duration(self, *channels: Channel) -> int: """Return the time of the end of the last instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ return self.ch_duration(*channels) def append( self, block: "BlockComponent", name: Optional[str] = None, inplace: bool = True ) -> "ScheduleBlock": """Return a new schedule block with ``block`` appended to the context block. The execution time is automatically assigned when the block is converted into schedule. Args: block: ScheduleBlock to be appended. name: Name of the new ``Schedule``. Defaults to name of ``self``. inplace: Perform operation inplace on this schedule. Otherwise, return a new ``Schedule``. Returns: Schedule block with appended schedule. Raises: PulseError: When invalid schedule type is specified. """ if not isinstance(block, (ScheduleBlock, Instruction)): raise PulseError( f"Appended `schedule` {block.__class__.__name__} is invalid type. " "Only `Instruction` and `ScheduleBlock` can be accepted." ) if not inplace: schedule = copy.deepcopy(self) schedule._name = name or self.name schedule.append(block, inplace=True) return schedule if isinstance(block, Reference) and block.ref_keys not in self.references: self.references[block.ref_keys] = None elif isinstance(block, ScheduleBlock): block = copy.deepcopy(block) # Expose subroutines to the current main scope. # Note that this 'block' is not called. # The block is just directly appended to the current scope. if block.is_referenced(): if block._parent is not None: # This is an edge case: # If this is not a parent, block.references points to the parent's reference # where subroutine not referred within the 'block' may exist. # Move only references existing in the 'block'. # See 'test.python.pulse.test_reference.TestReference.test_appending_child_block' for ref in _get_references(block._blocks): self.references[ref.ref_keys] = block.references[ref.ref_keys] else: # Avoid using dict.update and explicitly call __set_item__ for validation. # Reference manager of appended block is cleared because of data reduction. for ref_keys, ref in block._reference_manager.items(): self.references[ref_keys] = ref block._reference_manager.clear() # Now switch the parent because block is appended to self. block._parent = self self._blocks.append(block) self._parameter_manager.update_parameter_table(block) return self def filter( self, *filter_funcs: List[Callable], channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, check_subroutine: bool = True, ): """Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock`` which pass though the provided filters; i.e. an instruction will be retained if every function in ``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in ``channels``, and the instruction type is contained in ``instruction_types``. .. warning:: Because ``ScheduleBlock`` is not aware of the execution time of the context instructions, filtering out some instructions may change the execution time of the remaining instructions. If no arguments are provided, ``self`` is returned. Args: filter_funcs: A list of Callables which take a ``Instruction`` and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. check_subroutine: Set `True` to individually filter instructions inside a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: ``ScheduleBlock`` consisting of instructions that matches with filtering condition. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=False, recurse_subroutines=check_subroutine ) def exclude( self, *filter_funcs: List[Callable], channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, check_subroutine: bool = True, ): """Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock`` *failing* at least one of the provided filters. This method is the complement of py:meth:`~self.filter`, so that:: self.filter(args) + self.exclude(args) == self in terms of instructions included. .. warning:: Because ``ScheduleBlock`` is not aware of the execution time of the context instructions, excluding some instructions may change the execution time of the remaining instructions. Args: filter_funcs: A list of Callables which take a ``Instruction`` and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: ``ScheduleBlock`` consisting of instructions that do not match with at least one of filtering conditions. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=True, recurse_subroutines=check_subroutine ) def replace( self, old: "BlockComponent", new: "BlockComponent", inplace: bool = True, ) -> "ScheduleBlock": """Return a ``ScheduleBlock`` with the ``old`` component replaced with a ``new`` component. Args: old: Schedule block component to replace. new: Schedule block component to replace with. inplace: Replace instruction by mutably modifying this ``ScheduleBlock``. Returns: The modified schedule block with ``old`` replaced by ``new``. """ if not inplace: schedule = copy.deepcopy(self) return schedule.replace(old, new, inplace=True) if old not in self._blocks: # Avoid unnecessary update of reference and parameter manager return self # Temporarily copies references all_references = ReferenceManager() if isinstance(new, ScheduleBlock): new = copy.deepcopy(new) all_references.update(new.references) new._reference_manager.clear() new._parent = self for ref_key, subroutine in self.references.items(): if ref_key in all_references: warnings.warn( f"Reference {ref_key} conflicts with substituted program {new.name}. " "Existing reference has been replaced with new reference.", UserWarning, ) continue all_references[ref_key] = subroutine # Regenerate parameter table by regenerating elements. # Note that removal of parameters in old is not sufficient, # because corresponding parameters might be also used in another block element. self._parameter_manager.clear() self._parameter_manager.update_parameter_table(self._alignment_context) new_elms = [] for elm in self._blocks: if elm == old: elm = new self._parameter_manager.update_parameter_table(elm) new_elms.append(elm) self._blocks = new_elms # Regenerate reference table # Note that reference is attached to the outer schedule if nested. # Thus, this investigates all references within the scope. self.references.clear() root = self while root._parent is not None: root = root._parent for ref in _get_references(root._blocks): self.references[ref.ref_keys] = all_references[ref.ref_keys] return self def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return any(self.parameters) def is_referenced(self) -> bool: """Return True iff the current schedule block contains reference to subroutine.""" return len(self.references) > 0 def assign_parameters( self, value_dict: Dict[ParameterExpression, ParameterValueType], inplace: bool = True, ) -> "ScheduleBlock": """Assign the parameters in this schedule according to the input. Args: value_dict: A mapping from Parameters to either numeric values or another Parameter expression. inplace: Set ``True`` to override this instance with new parameter. Returns: Schedule with updated parameters. Raises: PulseError: When the block is nested into another block. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_parameters(value_dict, inplace=True) # Update parameters in the current scope self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict) for subroutine in self._reference_manager.values(): # Also assigning parameters to the references associated with self. # Note that references are always stored in the root program. # So calling assign_parameters from nested block doesn't update references. if subroutine is None: continue subroutine.assign_parameters(value_dict=value_dict, inplace=True) return self def assign_references( self, subroutine_dict: Dict[Union[str, Tuple[str, ...]], "ScheduleBlock"], inplace: bool = True, ) -> "ScheduleBlock": """Assign schedules to references. It is only capable of assigning a schedule block to immediate references which are directly referred within the current scope. Let's see following example: .. code-block:: python from qiskit import pulse with pulse.build() as subroutine: pulse.delay(10, pulse.DriveChannel(0)) with pulse.build() as sub_prog: pulse.reference("A") with pulse.build() as main_prog: pulse.reference("B") In above example, the ``main_prog`` can refer to the subroutine "root::B" and the reference of "B" to program "A", i.e., "B::A", is not defined in the root namespace. This prevents breaking the reference "root::B::A" by the assignment of "root::B". For example, if a user could indirectly assign "root::B::A" from the root program, one can later assign another program to "root::B" that doesn't contain "A" within it. In this situation, a reference "root::B::A" would still live in the reference manager of the root. However, the subroutine "root::B::A" would no longer be used in the actual pulse program. To assign subroutine "A" to ``nested_prog`` as a nested subprogram of ``main_prog``, you must first assign "A" of the ``sub_prog``, and then assign the ``sub_prog`` to the ``main_prog``. .. code-block:: python sub_prog.assign_references({("A", ): nested_prog}, inplace=True) main_prog.assign_references({("B", ): sub_prog}, inplace=True) Alternatively, you can also write .. code-block:: python main_prog.assign_references({("B", ): sub_prog}, inplace=True) main_prog.references[("B", )].assign_references({"A": nested_prog}, inplace=True) Here :attr:`.references` returns a dict-like object, and you can mutably update the nested reference of the particular subroutine. .. note:: Assigned programs are deep-copied to prevent an unexpected update. Args: subroutine_dict: A mapping from reference key to schedule block of the subroutine. inplace: Set ``True`` to override this instance with new subroutine. Returns: Schedule block with assigned subroutine. Raises: PulseError: When reference key is not defined in the current scope. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_references(subroutine_dict, inplace=True) for key, subroutine in subroutine_dict.items(): if key not in self.references: unassigned_keys = ", ".join(map(repr, self.references.unassigned())) raise PulseError( f"Reference instruction with {key} doesn't exist " f"in the current scope: {unassigned_keys}" ) self.references[key] = copy.deepcopy(subroutine) return self def get_parameters(self, parameter_name: str) -> List[Parameter]: """Get parameter object bound to this schedule by string name. Note that we can define different parameter objects with the same name, because these different objects are identified by their unique uuid. For example, .. code-block:: python from qiskit import pulse, circuit amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") with pulse.build() as sub_prog: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(sub_prog, name="sub") pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0)) main_prog.get_parameters("amp") This returns a list of two parameters ``amp1`` and ``amp2``. Args: parameter_name: Name of parameter. Returns: Parameter objects that have corresponding name. """ matched = [p for p in self.parameters if p.name == parameter_name] return matched def search_parameters(self, parameter_regex: str) -> List[Parameter]: """Search parameter with regular expression. This method looks for the scope-aware parameters. For example, .. code-block:: python from qiskit import pulse, circuit amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") with pulse.build() as sub_prog: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(sub_prog, name="sub") pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0)) main_prog.search_parameters("root::sub::amp") This finds ``amp1`` with scoped name "root::sub::amp". Args: parameter_regex: Regular expression for scoped parameter name. Returns: Parameter objects that have corresponding name. """ pattern = re.compile(parameter_regex) return sorted( _collect_scoped_parameters(self, current_scope="root", filter_regex=pattern).values(), key=lambda p: p.name, ) def __len__(self) -> int: """Return number of instructions in the schedule.""" return len(self.blocks) def __eq__(self, other: "ScheduleBlock") -> bool: """Test if two ScheduleBlocks are equal. Equality is checked by verifying there is an equal instruction at every time in ``other`` for every instruction in this ``ScheduleBlock``. This check is performed by converting the instruction representation into directed acyclic graph, in which execution order of every instruction is evaluated correctly across all channels. Also ``self`` and ``other`` should have the same alignment context. .. warning:: This does not check for logical equivalency. Ie., ```python >>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0)) == Delay(20, DriveChannel(0)) False ``` """ # 0. type check if not isinstance(other, type(self)): return False # 1. transformation check if self.alignment_context != other.alignment_context: return False # 2. size check if len(self) != len(other): return False # 3. instruction check with alignment from qiskit.pulse.transforms.dag import block_to_dag as dag if not rx.is_isomorphic_node_match(dag(self), dag(other), lambda x, y: x == y): return False return True def __repr__(self) -> str: name = format(self._name) if self._name else "" blocks = ", ".join([repr(instr) for instr in self.blocks[:50]]) if len(self.blocks) > 25: blocks += ", ..." return '{}({}, name="{}", transform={})'.format( self.__class__.__name__, blocks, name, repr(self.alignment_context) ) def __add__(self, other: "BlockComponent") -> "ScheduleBlock": """Return a new schedule with ``other`` inserted within ``self`` at ``start_time``.""" return self.append(other) def _common_method(*classes): """A function decorator to attach the function to specified classes as a method. .. note:: For developer: A method attached through this decorator may hurt readability of the codebase, because the method may not be detected by a code editor. Thus, this decorator should be used to a limited extent, i.e. huge helper method. By using this decorator wisely, we can reduce code maintenance overhead without losing readability of the codebase. """ def decorator(method): @functools.wraps(method) def wrapper(*args, **kwargs): return method(*args, **kwargs) for cls in classes: setattr(cls, method.__name__, wrapper) return method return decorator @_common_method(Schedule, ScheduleBlock) def draw( self, style: Optional[Dict[str, Any]] = None, backend=None, # importing backend causes cyclic import time_range: Optional[Tuple[int, int]] = None, time_unit: str = "dt", disable_channels: Optional[List[Channel]] = None, show_snapshot: bool = True, show_framechange: bool = True, show_waveform_info: bool = True, show_barrier: bool = True, plotter: str = "mpl2d", axis: Optional[Any] = None, ): """Plot the schedule. Args: style: Stylesheet options. This can be dictionary or preset stylesheet classes. See :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXStandard`, :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXSimple`, and :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXDebugging` for details of preset stylesheets. backend (Optional[BaseBackend]): Backend object to play the input pulse program. If provided, the plotter may use to make the visualization hardware aware. time_range: Set horizontal axis limit. Tuple `(tmin, tmax)`. time_unit: The unit of specified time range either `dt` or `ns`. The unit of `ns` is available only when `backend` object is provided. disable_channels: A control property to show specific pulse channel. Pulse channel instances provided as a list are not shown in the output image. show_snapshot: Show snapshot instructions. show_framechange: Show frame change instructions. The frame change represents instructions that modulate phase or frequency of pulse channels. show_waveform_info: Show additional information about waveforms such as their name. show_barrier: Show barrier lines. plotter: Name of plotter API to generate an output image. One of following APIs should be specified:: mpl2d: Matplotlib API for 2D image generation. Matplotlib API to generate 2D image. Charts are placed along y axis with vertical offset. This API takes matplotlib.axes.Axes as ``axis`` input. ``axis`` and ``style`` kwargs may depend on the plotter. axis: Arbitrary object passed to the plotter. If this object is provided, the plotters use a given ``axis`` instead of internally initializing a figure object. This object format depends on the plotter. See plotter argument for details. Returns: Visualization output data. The returned data type depends on the ``plotter``. If matplotlib family is specified, this will be a ``matplotlib.pyplot.Figure`` data. """ # pylint: disable=cyclic-import from qiskit.visualization import pulse_drawer return pulse_drawer( program=self, style=style, backend=backend, time_range=time_range, time_unit=time_unit, disable_channels=disable_channels, show_snapshot=show_snapshot, show_framechange=show_framechange, show_waveform_info=show_waveform_info, show_barrier=show_barrier, plotter=plotter, axis=axis, ) def _interval_index(intervals: List[Interval], interval: Interval) -> int: """Find the index of an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. Returns: The index of the interval. Raises: PulseError: If the interval does not exist. """ index = _locate_interval_index(intervals, interval) found_interval = intervals[index] if found_interval != interval: raise PulseError(f"The interval: {interval} does not exist in intervals: {intervals}") return index def _locate_interval_index(intervals: List[Interval], interval: Interval, index: int = 0) -> int: """Using binary search on start times, find an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. index: A running tally of the index, for recursion. The user should not pass a value. Returns: The index into intervals that new_interval would be inserted to maintain a sorted list of intervals. """ if not intervals or len(intervals) == 1: return index mid_idx = len(intervals) // 2 mid = intervals[mid_idx] if interval[1] <= mid[0] and (interval != mid): return _locate_interval_index(intervals[:mid_idx], interval, index=index) else: return _locate_interval_index(intervals[mid_idx:], interval, index=index + mid_idx) def _find_insertion_index(intervals: List[Interval], new_interval: Interval) -> int: """Using binary search on start times, return the index into `intervals` where the new interval belongs, or raise an error if the new interval overlaps with any existing ones. Args: intervals: A sorted list of non-overlapping Intervals. new_interval: The interval for which the index into intervals will be found. Returns: The index into intervals that new_interval should be inserted to maintain a sorted list of intervals. Raises: PulseError: If new_interval overlaps with the given intervals. """ index = _locate_interval_index(intervals, new_interval) if index < len(intervals): if _overlaps(intervals[index], new_interval): raise PulseError("New interval overlaps with existing.") return index if new_interval[1] <= intervals[index][0] else index + 1 return index def _overlaps(first: Interval, second: Interval) -> bool: """Return True iff first and second overlap. Note: first.stop may equal second.start, since Interval stop times are exclusive. """ if first[0] == second[0] == second[1]: # They fail to overlap if one of the intervals has duration 0 return False if first[0] > second[0]: first, second = second, first return second[0] < first[1] def _check_nonnegative_timeslot(timeslots: TimeSlots): """Test that a channel has no negative timeslots. Raises: PulseError: If a channel timeslot is negative. """ for chan, chan_timeslots in timeslots.items(): if chan_timeslots: if chan_timeslots[0][0] < 0: raise PulseError(f"An instruction on {chan} has a negative starting time.") def _get_timeslots(schedule: "ScheduleComponent") -> TimeSlots: """Generate timeslots from given schedule component. Args: schedule: Input schedule component. Raises: PulseError: When invalid schedule type is specified. """ if isinstance(schedule, Instruction): duration = schedule.duration instruction_duration_validation(duration) timeslots = {channel: [(0, duration)] for channel in schedule.channels} elif isinstance(schedule, Schedule): timeslots = schedule.timeslots else: raise PulseError(f"Invalid schedule type {type(schedule)} is specified.") return timeslots def _get_references(block_elms: List["BlockComponent"]) -> Set[Reference]: """Recursively get reference instructions in the current scope. Args: block_elms: List of schedule block elements to investigate. Returns: A set of unique reference instructions. """ references = set() for elm in block_elms: if isinstance(elm, ScheduleBlock): references |= _get_references(elm._blocks) elif isinstance(elm, Reference): references.add(elm) return references def _collect_scoped_parameters( schedule: ScheduleBlock, current_scope: str, filter_regex: Optional[re.Pattern] = None, ) -> Dict[Tuple[str, int], Parameter]: """A helper function to collect parameters from all references in scope-aware fashion. Parameter object is renamed with attached scope information but its UUID is remained. This means object is treated identically on the assignment logic. This function returns a dictionary of all parameters existing in the target program including its reference, which is keyed on the unique identifier consisting of scoped parameter name and parameter object UUID. This logic prevents parameter clash in the different scope. For example, when two parameter objects with the same UUID exist in different references, both of them appear in the output dictionary, even though they are technically the same object. This feature is particularly convenient to search parameter object with associated scope. Args: schedule: Schedule to get parameters. current_scope: Name of scope where schedule exist. filter_regex: Optional. Compiled regex to sort parameter by name. Returns: A dictionary of scoped parameter objects. """ parameters_out = {} for param in schedule._parameter_manager.parameters: new_name = f"{current_scope}{Reference.scope_delimiter}{param.name}" if filter_regex and not re.search(filter_regex, new_name): continue scoped_param = Parameter.__new__(Parameter, new_name, uuid=getattr(param, "_uuid")) scoped_param.__init__(new_name) unique_key = new_name, hash(param) parameters_out[unique_key] = scoped_param for sub_namespace, subroutine in schedule.references.items(): if subroutine is None: continue composite_key = Reference.key_delimiter.join(sub_namespace) full_path = f"{current_scope}{Reference.scope_delimiter}{composite_key}" sub_parameters = _collect_scoped_parameters( subroutine, current_scope=full_path, filter_regex=filter_regex ) parameters_out.update(sub_parameters) return parameters_out # These type aliases are defined at the bottom of the file, because as of 2022-01-18 they are # imported into other parts of Terra. Previously, the aliases were at the top of the file and used # forwards references within themselves. This was fine within the same file, but causes scoping # issues when the aliases are imported into different scopes, in which the `ForwardRef` instances # would no longer resolve. Instead, we only use forward references in the annotations of _this_ # file to reference the aliases, which are guaranteed to resolve in scope, so the aliases can all be # concrete. ScheduleComponent = Union[Schedule, Instruction] """An element that composes a pulse schedule.""" BlockComponent = Union[ScheduleBlock, Instruction] """An element that composes a pulse schedule block."""
https://github.com/JayantiSingh/Quant_co_Qiskit
JayantiSingh
# useful additional packages from qiskit import IBMQ, BasicAer, execute from qiskit import Aer from qiskit.aqua.components.oracles import LogicalExpressionOracle from qiskit.aqua.algorithms import Grover from qiskit.aqua.algorithms import VQE, ExactEigensolver from qiskit.tools.visualization import plot_histogram from qiskit.aqua import Operator, run_algorithm from qiskit.aqua.input import EnergyInput from qiskit.aqua.translators.ising import max_cut, tsp from qiskit.aqua.components.optimizers import SPSA from qiskit.aqua.components.variational_forms import RY from qiskit.aqua import QuantumInstance # useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes %matplotlib inline import numpy as np import networkx as nx # setup aqua logging import logging from qiskit.aqua._logging import set_logging_config, build_logging_config # set_logging_config(build_logging_config(logging.DEBUG)) # choose INFO, DEBUG to see the log # ignoring deprecation errors on matplotlib import warnings import matplotlib.cbook warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation) # Generating a graph of 4 nodes n = 4 num_qubits = n ** 2 ins = tsp.random_tsp(n) G = nx.Graph() G.add_nodes_from(np.arange(0, n, 1)) colors = ['r' for node in G.nodes()] pos = {k: v for k, v in enumerate(ins.coord)} default_axes = plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos) print('distance\n', ins.w) from itertools import permutations def brute_force_tsp(w, N): a=list(permutations(range(1,N))) last_best_distance = 1e10 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[pre_j,0] order = (0,) + i if distance < last_best_distance: best_order = order last_best_distance = distance print('order = ' + str(order) + ' Distance = ' + str(distance)) return last_best_distance, best_order best_distance, best_order = brute_force_tsp(ins.w, ins.dim) print('Best order from brute force = ' + str(best_order) + ' with total distance = ' + str(best_distance)) def draw_tsp_solution(G, order, colors, pos): G2 = G.copy() n = len(order) for i in range(n): j = (i + 1) % n G2.add_edge(order[i], order[j]) default_axes = plt.axes(frameon=True) nx.draw_networkx(G2, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos) draw_tsp_solution(G, best_order, colors, pos) qubitOp, offset = tsp.get_tsp_qubitops(ins) algo_input = EnergyInput(qubitOp) #Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector ee = ExactEigensolver(qubitOp, k=1) result = ee.run() """ algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) """ x = tsp.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) #print('tsp objective:', result['energy'] + offset) print('feasible:', tsp.tsp_feasible(x)) z = tsp.get_tsp_solution(x) print('solution:', z) print('solution objective:', tsp.tsp_value(z, ins.w)) draw_tsp_solution(G, z, colors, pos) seed = 10598 spsa = SPSA(max_trials=300) ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear') vqe = VQE(qubitOp, ry, spsa) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed) result = vqe.run(quantum_instance) """ algorithm_cfg = { 'name': 'VQE' } optimizer_cfg = { 'name': 'SPSA', 'max_trials': 300 } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': seed}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg, 'backend': {'provider': 'qiskit.Aer', 'name': 'statevector_simulator'} } result = run_algorithm(parahms,algo_input) """ print('energy:', result['energy']) print('time:', result['eval_time']) #print('tsp objective:', result['energy'] + offset) x = tsp.sample_most_likely(result['eigvecs'][0]) print('feasible:', tsp.tsp_feasible(x)) z = tsp.get_tsp_solution(x) print('solution:', z) print('solution objective:', tsp.tsp_value(z, ins.w)) draw_tsp_solution(G, z, colors, pos)
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import time from dwave.system import LeapHybridSampler from qiskit.optimization.algorithms import CplexOptimizer from random_lp.lp_random_gen import create_models from utilities.helpers import create_dwave_meo DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y") + "/SPARSE/" DIR # select linear program to solve qps = create_models(DIR) qp = qps['test_38'] # init Optimizers cplex = CplexOptimizer() leap = create_dwave_meo(LeapHybridSampler()) dwave_auto = create_dwave_meo() # solve classically cplex.solve(qp) # solve hybrid leap.min_eigen_solver.sampler.set_label("leap_test_38") res_leap = leap.solve(qp) res_leap # solve quantum dwave_auto.min_eigen_solver.sampler.set_label("dwave_test_38") res_dwave = dwave_auto.solve(qp) res_dwave qp.to_docplex().prettyprint()
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ The Custom Circuit-based Quantum Oracle. """ from qiskit import QuantumCircuit, QuantumRegister from qiskit.aqua import AquaError from .oracle import Oracle class CustomCircuitOracle(Oracle): """ The helper class for creating oracles from user-supplied quantum circuits """ def __init__(self, variable_register=None, output_register=None, ancillary_register=None, circuit=None): """ Constructor. Args: variable_register (QuantumRegister): The register holding variable qubit(s) for the oracle function output_register (QuantumRegister): The register holding output qubit(s) for the oracle function ancillary_register (QuantumRegister): The register holding ancillary qubit(s) circuit (QuantumCircuit): The quantum circuit corresponding to the intended oracle function """ super().__init__() if variable_register is None: raise AquaError('Missing QuantumRegister for variables.') if output_register is None: raise AquaError('Missing QuantumRegister for output.') if circuit is None: raise AquaError('Missing custom QuantumCircuit for the oracle.') self._variable_register = variable_register self._output_register = output_register self._ancillary_register = ancillary_register self._circuit = circuit @property def variable_register(self): return self._variable_register @property def output_register(self): return self._output_register @property def ancillary_register(self): return self._ancillary_register @property def circuit(self): return self._circuit def construct_circuit(self): """Construct the oracle circuit. Returns: A quantum circuit for the oracle. """ raise self._circuit
https://github.com/ncitron/qiskit-hack
ncitron
class QuantComp: def __init__(qboard, classical): qboard.classical = classical def convert(cboard): ret = [] for i in range(len(cboard)): if cboard[i] == 1: hold = str(bin(i)) while(len(hold) < 7): hold = '0' + hold ret.append(hold) return ret def setup(array): tot = len(array) n = 7 s = [] for i in range(n-1): s.append(i) if tot > 8: rep = 2 elif tot > 4: rep = 3 elif tot == 4: rep = 4 elif tot == 3: rep = 5 elif tot == 2: rep = 6 else: rep = 8 return rep, n def build_oracle(circuit, solutions, n): for i in range(tot): temp = solutions[i] for j, yesno in enumerate(reversed(temp)): if yesno == '0': circuit.x(j) circuit.h(n-1) circuit.mct(s, n-1) circuit.h(n-1) for k, noyes in enumerate(reversed(temp)): if noyes == '0': circuit.x(k) def amplify(circuit, n): circuit.h(range(n)) circuit.x(range(n)) circuit.h(n-1) circuit.mct(s, n-1) circuit.h(n-1) circuit.x(range(n)) circuit.h(range(n)) def guess(qboard): sol = convert(qboard.classical) rep, n = setup(sol) qc = QuantumCircuit(n) qc.h(range(n)) for i in range(rep): build_oracle(qc, sol, n) amplify(qc, n) qc.measure_all() simulator = Aer.get_backend('qasm_simulator') return execute(qc, backend = simulator, shots = 1).result().get_counts() q = QuantComp([0,0,0,0,0,1]) q.guess()
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
# 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. # Copyright 2021 Dell (www.dell.com) # # 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 unittest import os import json import logging # from ..dell_runtime.emulation_executor import EmulationExecutor from dell_runtime import EmulationExecutor RUNTIME_PROGRAM = """ import random from qiskit import transpile from qiskit.circuit.random import random_circuit def prepare_circuits(backend): circuit = random_circuit(num_qubits=5, depth=4, measure=True, seed=random.randint(0, 1000)) return transpile(circuit, backend) def main(backend, user_messenger, **kwargs): iterations = kwargs['iterations'] interim_results = kwargs.pop('interim_results', {}) final_result = kwargs.pop("final_result", {}) for it in range(iterations): qc = prepare_circuits(backend) user_messenger.publish({"iteration": it, "interim_results": interim_results}) backend.run(qc).result() user_messenger.publish(final_result, final=True) """ logger = logging.getLogger(__name__) class EmulationExecutorTest(unittest.TestCase): def test_pre_post_run(self): try: executor = EmulationExecutor(program=None, program_data=(RUNTIME_PROGRAM, "STRING")) self.assertIsNotNone(executor) executor._pre_run() self.assertTrue(os.path.isdir(executor.temp_dir())) program_path = os.path.join(executor.temp_dir(), "program.py") self.assertTrue(os.path.isfile(program_path)) with open(program_path, "r") as program_file: program_text = program_file.read() self.assertEqual(RUNTIME_PROGRAM, program_text) executor_path = os.path.join(executor.temp_dir(), "executor.py") self.assertTrue(os.path.isfile(executor_path)) finally: executor._post_run() self.assertFalse(os.path.isdir(executor.temp_dir()))
https://github.com/barankiewicz/Deutsch-Jozsa
barankiewicz
# zaimportuj Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, assemble, transpile # zaimportuj narzędzie Qiskit do wizualizacji from qiskit.visualization import plot_histogram # initialization import numpy as np qn = 4 #Liczba kubitów balanced_function = True #Wybór funkcji stałej lub zbalansowanej def generate_oracle(balanced, n): oracle_qc = QuantumCircuit(n+1) if balanced == True: # Wygeneruj losowy ciąg bitów, żeby określić, na których kubitach użyć bramki X if n <= 10: pot = n else: pot = 16 b = np.random.randint(1,2**pot) b_str = format(b, '0'+str(n)+'b') #Iteracja przez ciąg bitów; jeżeli znak to 0 - nie rób nic, jeżeli 1 - użyj bramki X for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) #Zbalansowanie wyroczni poprzez zastosowanie bramek CNOT for qubit in range(n): oracle_qc.cx(qubit, n) # Powtórzenie bramek X for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) if balanced == False: #Najpierw losowy generujemy 0 lub 1, następnie tworzymy wyrocznię, która zwraca jedynie wygenerowaną liczbę output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Wyrocznia Uf" # To show when we display the circuit return oracle_gate def deutsch_jozsa(oracle): # W wyroczni jest jeden kubit więcej, niż znaków wejściowych funkcji f n = oracle.num_qubits - 1; #Utworzenie obwodu kwantowego final_circuit = QuantumCircuit(n+1, n) # Krok 1: final_circuit.x(n) final_circuit.h(n) for qubit in range(n): final_circuit.h(qubit) # Krok 2: final_circuit.append(oracle, range(n+1)) # Krok 3: for qubit in range(n): final_circuit.h(qubit) # Krok 4: for i in range(n): final_circuit.measure(i, i) return final_circuit oracle_gate = generate_oracle(balanced_function, qn) circuit = deutsch_jozsa(oracle_gate) circuit.draw() aer_sim = Aer.get_backend('aer_simulator') transpiled_circuit = transpile(circuit, aer_sim) qobj = assemble(transpiled_circuit) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) #IBMQ.save_account('') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (qn+1) and not x.configuration().simulator and x.status().operational==True)) print("Najmniej zajęty procesor: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_circuit = transpile(circuit, backend, optimization_level=3) job = backend.run(transpiled_circuit) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer)
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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford, random_clifford qc = QuantumCircuit(3) cliff = random_clifford(2) qc.append(cliff, [0, 1]) qc.ccx(0, 1, 2) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] for _ in range(100): depths.append( transpile( ghz, backend, layout_method='trivial' # Fixed layout mapped in circuit order ).depth() ) plt.figure(figsize=(8, 6)) plt.hist(depths, align='left', color='#AC557C') plt.xlabel('Depth', fontsize=14) plt.ylabel('Counts', fontsize=14);
https://github.com/theflyingrahul/qiskitsummerschool2020
theflyingrahul
!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/BOBO1997/osp_solutions
BOBO1997
# Import general libraries (needed for functions) import numpy as np import time # Import Qiskit classes import qiskit from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer from qiskit.providers.aer import noise from qiskit.tools.visualization import plot_histogram # Import measurement calibration functions from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal, CompleteMeasFitter, TensoredMeasFitter) # Generate the calibration circuits qr = qiskit.QuantumRegister(3) qubit_list = [0,1,2] meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') state_labels # Execute the calibration circuits without noise backend = qiskit.Aer.get_backend('qasm_simulator') job = qiskit.execute(meas_calibs, backend=backend, shots=1000) cal_results = job.result() # The calibration matrix without noise is the identity matrix meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') print(meas_fitter.cal_matrix) # Generate a noise model for the 5 qubits noise_model = noise.NoiseModel() for qi in range(1): read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],[0.25,0.75]]) noise_model.add_readout_error(read_err, [qi]) # Execute the calibration circuits backend = qiskit.Aer.get_backend('qasm_simulator') job = qiskit.execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model) cal_results = job.result() # Calculate the calibration matrix with the noise model meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list, circlabel='mcal') print(meas_fitter.cal_matrix) # Plot the calibration matrix meas_fitter.plot_calibration() # What is the measurement fidelity? print("Average Measurement Fidelity: %f" % meas_fitter.readout_fidelity()) # What is the measurement fidelity of Q0? print("Average Measurement Fidelity of Q0: %f" % meas_fitter.readout_fidelity( label_list = [['000','001','010','011'],['100','101','110','111']])) # Make a 3Q GHZ state cr = ClassicalRegister(3) ghz = QuantumCircuit(qr, cr) ghz.h(qr[0]) ghz.cx(qr[0], qr[1]) ghz.cx(qr[1], qr[2]) ghz.measure(qr[0],cr[0]) ghz.measure(qr[1],cr[1]) ghz.measure(qr[2],cr[2]) job = qiskit.execute([ghz], backend=backend, shots=5000, noise_model=noise_model) results = job.result() # Results without mitigation raw_counts = results.get_counts() # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(results) mitigated_counts = mitigated_results.get_counts(0) from qiskit.tools.visualization import * plot_histogram([raw_counts, mitigated_counts], legend=['raw', 'mitigated']) # Make a 3Q GHZ state cr = ClassicalRegister(3) ghz = QuantumCircuit(qr, cr) ghz.h(qr[0]) ghz.cx(qr[0], qr[1]) ghz.cx(qr[1], qr[2]) # 明示的にbig endianにしてみる ghz.measure(qr[0],cr[2]) ghz.measure(qr[1],cr[1]) ghz.measure(qr[2],cr[0]) job = qiskit.execute([ghz], backend=backend, shots=5000, noise_model=noise_model) results = job.result() # Results without mitigation raw_counts = results.get_counts() # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(results) mitigated_counts = mitigated_results.get_counts(0) from qiskit.tools.visualization import * plot_histogram([raw_counts, mitigated_counts], legend=['raw', 'mitigated'])
https://github.com/thoughtpoet/Toward-high-frequency-trading-on-the-quantm-cloud
thoughtpoet
!python3 -m pip install -q qiskit !python3 -m pip install -q qiskit_ibm_runtime from qiskit import IBMQ from qiskit_ibm_runtime import QiskitRuntimeService, Session, Options, Sampler, Estimator from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.quantum_info.operators import Operator from qiskit.extensions.unitary import UnitaryGate from qiskit.providers.aer import AerSimulator, Aer from qiskit.execute_function import execute import numpy as np from typing import Dict, Optional # ==================================== # pass IBM API Token # ==================================== QiskitRuntimeService.save_account(channel='ibm_quantum', token="", overwrite=True) num_players = 2 # define the payoff matrices. Assume, the 1st matrix is Alice's payoff, the secomd matrix is Bob's payoff payoff_matrix =[[[3, 0], [5, 1]], [[3, 5], [0, 1]]] # players' matrices # |C> strategy # bob = [ # [1, 0], # [0, 1]] # |D> strategy # bob = [ # [0, 1], # [1, 0], # ] def alice_plays_quantum(theta:float, phi:float): """ Set up a quantum game for Alice playing quantum, and Bob playing classically. Arg: theta: the value of the theta parameter. phi: the value of the phi parameter. Returns: qc: the class of 'qiskit.circuit.quantumcircuit.QuantumCircuit', a constructed quantum circuit for the quantum game set up. """ alice = np.array([[np.exp(1.0j*phi)*np.cos(theta/2), np.sin(theta/2)], [-np.sin(theta/2), np.exp(-1.0j*phi)*np.cos(theta/2)]]) bob = np.array([ [1, 0], [0, 1]]).astype(complex) qc = QuantumCircuit(num_players) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() unitary_alice = UnitaryGate(Operator(alice)) unitary_bob = UnitaryGate(Operator(bob)) qc.append(unitary_alice, [0]) qc.append(unitary_bob, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) return qc # test run # define the simulator simulator = Aer.get_backend('statevector_simulator') theta = np.pi phi = 0.0 qc = alice_plays_quantum(theta, phi) results = execute(qc, simulator, shots=1024).result().get_counts() results # calculating payoffs def get_payoff(counts): """ Calculate the reward for the players after the game ends. """ payoff_bob = [] payoff_alice = [] for strategy, prob in counts.items(): strategy_bob = int(strategy[1]) strategy_alice = int(strategy[0]) payoff_bob.append(prob * payoff_matrix[0][strategy_alice][strategy_bob]) payoff_alice.append(prob * payoff_matrix[0][strategy_bob][strategy_alice]) return sum(payoff_alice), sum(payoff_bob) # change the size on the quantum space to explore more quantum strategies space_size = 4 for phi in np.linspace(0, np.pi/2, space_size): for theta in np.linspace(0, np.pi, space_size): qc = alice_plays_quantum(theta, phi) results = execute(qc, simulator, shots=1024).result().get_counts() payoff_alice, payoff_bob = get_payoff(results) print("theta = {}, phi = {}, results = {}, Alice's payoff {}, Bob's payoff {}".format(theta, phi, results, payoff_alice, payoff_bob)) print("Next Game") qc = alice_plays_quantum(theta = np.pi/2, phi = np.pi/4) job = simulator.run(qc, shots=2048) result = job.result() outputstate = result.get_statevector(qc, decimals=3) print(outputstate) from qiskit.visualization import plot_state_city plot_state_city(outputstate) from qiskit.visualization import plot_histogram counts = result.get_counts() plot_histogram(counts) # probabilities of a certain outcome counts num_players = 2 def alice_bob_play_quantum(theta_a:float, phi_a:float, theta_b:float, phi_b:float, measure=False): """ Set up a quantum game. Both players have access to quantum strategies. Args: theta_a: Theta parameter for Alice's unitary. phi_a: Phi parameter for Alice's unitary. theta_b: Theta parameter for Bob's unitary. phi_b: Phi parameter for Bob's unitary. Returns: qc: the class of 'qiskit.circuit.quantumcircuit.QuantumCircuit', a constructed quantum circuit for the quantum game set up. """ alice = np.array([ [np.exp(1.0j*phi_a)*np.cos(theta_a/ 2), np.sin(theta_a / 2)], [-np.sin(theta_a / 2), np.exp(-1.0j*phi_a)*np.cos(theta_a / 2)]]) bob = np.array([ [np.exp(1.0j*phi_b)*np.cos(theta_b / 2), np.sin(theta_b / 2)], [-np.sin(theta_b / 2), np.exp(-1.0j*phi_b)*np.cos(theta_b / 2)]]) qc = QuantumCircuit(num_players) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() unitary_alice = UnitaryGate(Operator(alice)) unitary_bob = UnitaryGate(Operator(bob)) qc.append(unitary_alice, [0]) qc.append(unitary_bob, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) if measure: qc.measure_all() return qc alice_reward = 0 bob_reward = 0 draw = 0 space_size = 2 for phi1 in np.linspace(0, 2*np.pi, space_size): for theta1 in np.linspace(0, np.pi, space_size): for phi2 in np.linspace(0, 2*np.pi, space_size): for theta2 in np.linspace(0, np.pi, space_size): qc = alice_bob_play_quantum(theta1, phi1, theta2, phi2) results = execute(qc, simulator, shots=1024).result().get_counts() payoff_alice, payoff_bob = get_payoff(results) # count winning if payoff_alice > payoff_bob: alice_reward += 1 elif payoff_bob > payoff_alice: bob_reward += 1 else: draw += 1 # print results print("theta_alice = {}, phi_alice = {}, theta_bob = {}, phi_bob = {}".format(theta1, phi1, theta2, phi2 )) print("results = {}, Alice's raward {}, Bob's reward {}".format(results, payoff_alice, payoff_bob)) print("Next Game") print("===================================================") print("In {} games Alice gets a higher reward than Bob.". format(alice_reward)) print("In {} games, Bob gets a higher reward than Alice.".format(bob_reward)) print("In {} games Alice and Bob get equal reward.".format(draw)) matrix = np.array([[1.0j, 0], [0, -1.0j]]) qc = QuantumCircuit(2) gate = UnitaryGate(Operator(matrix)) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() qc.append(gate, [0]) qc.append(gate, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) results = execute(qc, simulator, shots=1024).result().get_counts() alice_payoff, bob_payoff = get_payoff(results) print("Strategy: {}".format(results)) print("Alice's payoff is {}, Bob's payoff is {}".format(alice_payoff, bob_payoff)) import matplotlib.pyplot as plt space_size = 40 def payoff_plot(): """ Plot expected payoff distribution for Alice. """ x = np.linspace(1, -1, space_size) y = np.linspace(-1, 1, space_size) X, Y = np.meshgrid(x, y) Z = np.zeros(X.shape) for i in range(0,space_size): for inner in range(0, space_size): if X[inner][i] < 0 and Y[inner][i] < 0: qc = alice_bob_play_quantum(0, X[inner][i]*np.pi/2, 0, Y[inner][i]*np.pi/2) payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts()) Z[inner][i] = payoff_alice elif X[inner][i] >= 0 and Y[inner][i] >= 0: qc = alice_bob_play_quantum(X[inner][i]*np.pi, 0, Y[inner][i]*np.pi, 0) payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts()) Z[inner][i] = payoff_alice elif X[inner][i] >= 0 and Y[inner][i] < 0: qc = alice_bob_play_quantum(X[inner][i]*np.pi, 0, 0, Y[inner][i]*np.pi/2) payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts()) Z[inner][i] = payoff_alice elif X[inner][i] < 0 and Y[inner][i] >= 0: qc = alice_bob_play_quantum(0, X[inner][i]*np.pi/2, Y[inner][i]*np.pi, 0) payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts()) Z[inner][i] = payoff_alice fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(111, projection='3d') ax.plot_surface(X, Y, Z, cmap=plt.cm.coolwarm, antialiased=True) ax.set(xlim=(-1, 1), ylim=(1, -1), xlabel="Bob strategy", ylabel='Alice strategy', zlabel="Alice's expected payoff") plt.show() payoff_plot() def build_qcir_three_parameters(theta1, phi1, lmbda, theta2, phi2): """ Set up a quantum game. Both players have access to quantum strategies space """ alice = np.array([ [np.exp(1.0j*phi1)*np.cos(theta1/2), 1.0j*np.exp(1.0j * lmbda) * np.sin(theta1/2)], [1.0j*np.exp(-1.0j * lmbda) * np.sin(theta1/2), np.exp(-1.0j*phi1)*np.cos(theta1/2)]]) bob = np.array([ [np.exp(1.0j*phi2)*np.cos(theta2/2), np.sin(theta2/2)], [-np.sin(theta2/2), np.exp(-1.0j*phi2)*np.cos(theta2/2)]]) qc = QuantumCircuit(num_players) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0,1]) qc.barrier() unitary_alice = UnitaryGate(Operator(alice)) unitary_bob = UnitaryGate(Operator(bob)) qc.append(unitary_alice, [0]) qc.append(unitary_bob, [1]) qc.barrier() Jdagger_unitary = UnitaryGate(Operator(J.conj().T)) qc.append(Jdagger_unitary, [0,1]) return qc alice_reward = 0 bob_reward = 0 draw = 0 space_size = 4 for phi1 in np.linspace(-np.pi, np.pi, space_size): for theta1 in np.linspace(0, np.pi, space_size): for phi2 in np.linspace(-np.pi, np.pi, space_size): for theta2 in np.linspace(0, np.pi, space_size): for lmbda in np.linspace(-np.pi, np.pi, 2*space_size): qc = build_qcir_three_parameters(theta1, phi1, lmbda, theta2, phi2) results = execute(qc, simulator, shots=1024).result().get_counts() payoff_alice, payoff_bob = get_payoff(results) # count winning if payoff_alice > payoff_bob: alice_reward += 1 elif payoff_bob > payoff_alice: bob_reward += 1 else: draw += 1 # print results print("theta_alice = {}, phi_alice = {}, theta_bob = {}, phi_bob = {}".format(theta1, phi1, theta2, phi2 )) print("results = {}, Alice's payoff {}, Bob's payoff {}".format(results, payoff_alice, payoff_bob)) print("Next Game") print("===================================================") print("In {} games Alice gets a higher reward than Bob.". format(alice_reward)) print("In {} games, Bob gets a higher reward than Alice.".format(bob_reward)) print("In {} games Alice and Bob get equal reward.".format(draw)) !python3 -m pip install -q qiskit-ibm-provider from qiskit.providers.ibmq import least_busy from qiskit_ibm_provider import IBMProvider provider = IBMProvider() # ==================================== # pass IBM API Token # ==================================== provider.save_account(token=, overwrite=True) small_devices = provider.backends(filters=lambda x: x.configuration().n_qubits == 5 and not x.configuration().simulator) least_busy(small_devices) backend = least_busy(small_devices) qc = alice_bob_play_quantum(theta_a = 0, phi_a = 0, theta_b = np.pi/2, phi_b = 0, measure=True) job = execute(qc, backend, optimization_level=2) result = job.result() counts = result.get_counts() counts plot_histogram(counts) job = execute(qc, backend=Aer.get_backend('statevector_simulator'), shots=1024) result = job.result() counts = result.get_counts() print(counts) plot_histogram(counts) from functools import reduce from operator import add from qiskit import quantum_info as qi def mixed_strategy(alpha_a:float, alpha_b:float): """ Set up a quantum game. Both players have access to quantum strategies. Args: theta_a: Theta parameter for Alice's unitary. phi_a: Phi parameter for Alice's unitary. theta_b: Theta parameter for Bob's unitary. phi_b: Phi parameter for Bob's unitary. Returns: qc: the class of 'qiskit.circuit.quantumcircuit.QuantumCircuit', a constructed quantum circuit for the quantum game set up. """ qc = QuantumCircuit(2) # Alice strategies unitary1_a = np.eye(2).astype(complex) unitary2_a = np.array([[-1.0j, 0], [0, 1.0j]]) # Bob's strategies unitary1_b = np.array([[0, 1], [-1, 0]]).astype(complex) unitary2_b = np.array([[0, -1.0j], [-1.0j, 0]]).astype(complex) # define probabilities for Alice p1_a = np.cos(alpha_a / 2) ** 2 p2_a = np.sin(alpha_a/ 2) ** 2 # define probabilities for Bob p1_b = np.cos(alpha_b / 2) ** 2 p2_b = np.sin(alpha_b/ 2) ** 2 # define the set of actions and their probability distribution. mixed_strategy = [[(p1_a, unitary1_a), (p2_a, unitary2_a)], [(p1_b, unitary1_b), (p2_b, unitary2_b)]] identity = np.eye(2) J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j], [0.0, 1.0, 1.0j, 0.0], [0.0, 1.0j, 1.0, 0.0], [1.0j, 0.0, 0.0, 1.0]]).astype(complex) J_unitary = UnitaryGate(Operator(J)) qc.append(J_unitary, [0, 1]) rho = qi.DensityMatrix.from_instruction(qc) for index, strategy in enumerate(mixed_strategy): rho = reduce(add, (prob * rho.evolve(np.kron(*[strat if index == player else identity for player in range(num_players)])) for prob, strat in strategy)) rho = rho.evolve(Operator(J.conj().T)) return rho.probabilities() payoff_matrix =[[[3, 0], [5, 1]], [[3, 5], [0, 1]]] for alpha_a in np.linspace(0, np.pi, 4): for alpha_b in np.linspace(0, np.pi, 2): print("alpha_a = ", alpha_a) print("alpha_b = ", alpha_b) prob = mixed_strategy(alpha_a, alpha_b) print("prob = ", prob) alice_matrix = np.reshape(payoff_matrix[0], (1,4)) bob_matrix = np.reshape(payoff_matrix[1], (1,4)) print("Alice's Payoff = ", np.round(np.dot(prob, alice_matrix[0]), 3)) print("Bob's Payoff = ", np.round(np.dot(prob, bob_matrix[0]),3)) print("=======================") # probability of 1/2 and 1/2 yeilds the payoffs of 2.5 for each player. prob = mixed_strategy(np.pi/2, np.pi/2) print("prob = ", prob) alice_matrix = np.reshape(payoff_matrix[0], (1,4)) bob_matrix = np.reshape(payoff_matrix[1], (1,4)) print("Alice's Payoff = ", np.round(np.dot(prob, alice_matrix[0]), 3)) print("Bob's Payoff = ", np.round(np.dot(prob, bob_matrix[0]),3))
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/jcylim/QiskitProject
jcylim
import qiskit as qk from qiskit import available_backends, get_backend, execute, register, least_busy import numpy as np from scipy.optimize import curve_fit from qiskit.tools.qcvv.fitters import exp_fit_fun, osc_fit_fun, plot_coherence qx_config = { "APItoken": 'dcdb2d9414a625c1f57373c544add3711c78c3d7faf39397fe2c41887110e8b59caf81bcb2bc32714d936da41a261fea510f96df379afcbdfa9df6cc6bfe3829', "url": 'https://quantumexperience.ng.bluemix.net/api' } #backend = 'local_qasm_simulator' # run on local simulator by default register(qx_config['APItoken'], qx_config['url']) backend = qk.get_backend('ibmqx4') # the device to run on #backend = least_busy(available_backends({'simulator': False, 'local': False})) #print("the best backend is " + backend) # function for padding with QId gates def pad_QId(circuit,N,qr): # circuit to add to, N = number of QId gates to add, qr = qubit reg for ii in range(N): circuit.barrier(qr) circuit.iden(qr) return circuit shots = 1024 # the number of shots in the experiment # Select qubit whose T1 is to be measured qubit=1 # Creating registers qr = qk.QuantumRegister(5) cr = qk.ClassicalRegister(5) # the delay times are all set in terms of single-qubit gates # so we need to calculate the time from these parameters params = backend.parameters['qubits'][qubit] pulse_length=params['gateTime']['value'] # single-qubit gate time buffer_length=params['buffer']['value'] # spacing between pulses unit = params['gateTime']['unit'] steps=10 gates_per_step=120 max_gates=(steps-1)*gates_per_step+1 tot_length=buffer_length+pulse_length time_per_step=gates_per_step*tot_length qc_dict={} for ii in range(steps): step_num='step_%s'%(str(ii)) qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)}) qc_dict[step_num].x(qr[qubit]) qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit]) qc_dict[step_num].barrier(qr[qubit]) qc_dict[step_num].measure(qr[qubit], cr[qubit]) circuits=list(qc_dict.values()) # run the program status = backend.status if status['operational'] == False or status['pending_jobs'] > 10: print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible') t1_job=qk.execute(circuits, backend, shots=shots) # arrange the data from the run result_t1 = t1_job.result() keys_0_1=list(result_t1.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001' data=np.zeros(len(qc_dict.keys())) # numpy array for data sigma_data = np.zeros(len(qc_dict.keys())) # change unit from ns to microseconds plot_factor=1 if unit.find('ns')>-1: plot_factor=1000 punit='$\mu$s' xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps in microseconds for ii,key in enumerate(qc_dict.keys()): # get the data in terms of counts for the excited state normalized to the total number of counts data[ii]=float(result_t1.get_counts(qc_dict[key])[keys_0_1[1]])/shots sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots) # fit the data to an exponential fitT1, fcov = curve_fit(exp_fit_fun, xvals, data, bounds=([-1,2,0], [1., 500, 1])) ferr = np.sqrt(np.diag(fcov)) plot_coherence(xvals, data, sigma_data, fitT1, exp_fit_fun, punit, 'T$_1$ ', qubit) print("a: " + str(round(fitT1[0],2)) + u" \u00B1 " + str(round(ferr[0],2))) print("T1: " + str(round(fitT1[1],2))+ " µs" + u" \u00B1 " + str(round(ferr[1],2)) + ' µs') print("c: " + str(round(fitT1[2],2)) + u" \u00B1 " + str(round(ferr[2],2)))
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- 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/dlyongemallo/qiskit-zx-transpiler
dlyongemallo
# ZX transpiler pass for Qiskit # Copyright (C) 2023 David Yonge-Mallo # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for Qiskit ZX transpiler.""" from typing import Callable, Optional import pyzx as zx import numpy as np from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.quantum_info import Statevector from qiskit.transpiler import PassManager from qiskit.circuit.random import random_circuit import qiskit.converters from zxpass import ZXPass def _run_zxpass(qc: QuantumCircuit, optimize: Optional[Callable[[zx.Circuit], zx.Circuit]] = None) -> bool: zxpass = ZXPass(optimize) pass_manager = PassManager(zxpass) zx_qc = pass_manager.run(qc) return Statevector.from_instruction(qc).equiv(Statevector.from_instruction(zx_qc)) def test_basic_circuit() -> None: """Test a basic circuit. Taken from https://github.com/Quantomatic/pyzx/blob/master/circuits/Fast/mod5_4_before """ qc = QuantumCircuit(5) qc.x(4) qc.h(4) qc.ccz(0, 3, 4) qc.ccz(2, 3, 4) qc.h(4) qc.cx(3, 4) qc.h(4) qc.ccz(1, 2, 4) qc.h(4) qc.cx(2, 4) qc.h(4) qc.ccz(0, 1, 4) qc.h(4) qc.cx(1, 4) qc.cx(0, 4) assert _run_zxpass(qc) def test_custom_optimize() -> None: """Test custom optimize method. """ qc = QuantumCircuit(4) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.cx(0, 1) qc.cx(1, 2) qc.cx(2, 3) qc.cx(3, 0) def optimize(circ: zx.Circuit) -> zx.Circuit: # Any function that takes a zx.Circuit and returns a zx.Circuit will do. return circ.to_basic_gates() assert _run_zxpass(qc, optimize) def test_measurement() -> None: """Test a circuit with a measurement. """ q = QuantumRegister(1, 'q') c = ClassicalRegister(1, 'c') qc = QuantumCircuit(q, c) qc.h(q[0]) qc.measure(q[0], c[0]) qc.h(q[0]) dag = qiskit.converters.circuit_to_dag(qc) zxpass = ZXPass() circuits_and_nodes = zxpass._dag_to_circuits_and_nodes(dag) # pylint: disable=protected-access assert len(circuits_and_nodes) == 3 assert circuits_and_nodes[1] == dag.op_nodes()[1] def test_conditional_gate() -> None: """Test a circuit with a conditional gate. """ q = QuantumRegister(1, 'q') c = ClassicalRegister(1, 'c') qc = QuantumCircuit(q, c) qc.h(q[0]).c_if(c, 0) assert _run_zxpass(qc) def test_unitary() -> None: """Test a circuit with a unitary gate. """ matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]] qc = QuantumCircuit(2) qc.unitary(matrix, [0, 1]) assert _run_zxpass(qc) def test_pyzx_issue_102() -> None: """Regression test for PyZX issue #102. This tests for a bug which prevented an earlier attempt at a Qiskit ZX transpiler pass from working. See: https://github.com/Quantomatic/pyzx/issues/102 """ qc = QuantumCircuit(4) qc.ccx(2, 1, 0) qc.ccz(0, 1, 2) qc.h(1) qc.ccx(1, 2, 3) qc.t(1) qc.ccz(0, 1, 2) qc.h(1) qc.t(0) qc.ccz(2, 1, 0) qc.s(1) qc.ccx(2, 1, 0) qc.crz(0.2*np.pi, 0, 1) qc.rz(0.8*np.pi, 1) qc.cry(0.4*np.pi, 2, 1) qc.crx(0.02*np.pi, 2, 0) assert _run_zxpass(qc) def test_random_circuits() -> None: """Test random circuits. """ for _ in range(20): num_qubits = np.random.randint(4, 9) depth = np.random.randint(10, 21) qc = random_circuit(num_qubits, depth) assert _run_zxpass(qc)
https://github.com/varunpalakodeti20/Grover-Algo
varunpalakodeti20
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/xtophe388/QISKIT
xtophe388
# useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np # useful math functions from math import pi, cos, acos, sqrt import random # importing the QISKit from qiskit import QuantumProgram import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram Q_program = QuantumProgram() Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url N = 4 # Creating registers qr = Q_program.create_quantum_register("qr", N) # for recording the measurement on qr cr = Q_program.create_classical_register("cr", N) circuitName = "sharedEntangled" sharedEntangled = Q_program.create_circuit(circuitName, [qr], [cr]) #Create uniform superposition of all strings of length 2 for i in range(2): sharedEntangled.h(qr[i]) #The amplitude is minus if there are odd number of 1s for i in range(2): sharedEntangled.z(qr[i]) #Copy the content of the fist two qubits to the last two qubits for i in range(2): sharedEntangled.cx(qr[i], qr[i+2]) #Flip the last two qubits for i in range(2,4): sharedEntangled.x(qr[i]) #we first define controlled-u gates required to assign phases from math import pi def ch(qProg, a, b): """ Controlled-Hadamard gate """ qProg.h(b) qProg.sdg(b) qProg.cx(a, b) qProg.h(b) qProg.t(b) qProg.cx(a, b) qProg.t(b) qProg.h(b) qProg.s(b) qProg.x(b) qProg.s(a) return qProg def cu1pi2(qProg, c, t): """ Controlled-u1(phi/2) gate """ qProg.u1(pi/4.0, c) qProg.cx(c, t) qProg.u1(-pi/4.0, t) qProg.cx(c, t) qProg.u1(pi/4.0, t) return qProg def cu3pi2(qProg, c, t): """ Controlled-u3(pi/2, -pi/2, pi/2) gate """ qProg.u1(pi/2.0, t) qProg.cx(c, t) qProg.u3(-pi/4.0, 0, 0, t) qProg.cx(c, t) qProg.u3(pi/4.0, -pi/2.0, 0, t) return qProg # dictionary for Alice's operations/circuits aliceCircuits = {} # Quantum circuits for Alice when receiving idx in 1, 2, 3 for idx in range(1, 4): circuitName = "Alice"+str(idx) aliceCircuits[circuitName] = Q_program.create_circuit(circuitName, [qr], [cr]) theCircuit = aliceCircuits[circuitName] if idx == 1: #the circuit of A_1 theCircuit.x(qr[1]) theCircuit.cx(qr[1], qr[0]) theCircuit = cu1pi2(theCircuit, qr[1], qr[0]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit = cu1pi2(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit = cu1pi2(theCircuit, qr[0], qr[1]) theCircuit = cu3pi2(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit = ch(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit.cx(qr[1], qr[0]) theCircuit.x(qr[1]) elif idx == 2: theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit = cu1pi2(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit = cu1pi2(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit.h(qr[0]) theCircuit.h(qr[1]) elif idx == 3: theCircuit.cz(qr[0], qr[1]) theCircuit.swap(qr[0], qr[1]) theCircuit.h(qr[0]) theCircuit.h(qr[1]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit.cz(qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) #measure the first two qubits in the computational basis theCircuit.measure(qr[0], cr[0]) theCircuit.measure(qr[1], cr[1]) # dictionary for Bob's operations/circuits bobCircuits = {} # Quantum circuits for Bob when receiving idx in 1, 2, 3 for idx in range(1,4): circuitName = "Bob"+str(idx) bobCircuits[circuitName] = Q_program.create_circuit(circuitName, [qr], [cr]) theCircuit = bobCircuits[circuitName] if idx == 1: theCircuit.x(qr[2]) theCircuit.x(qr[3]) theCircuit.cz(qr[2], qr[3]) theCircuit.x(qr[3]) theCircuit.u1(pi/2.0, qr[2]) theCircuit.x(qr[2]) theCircuit.z(qr[2]) theCircuit.cx(qr[2], qr[3]) theCircuit.cx(qr[3], qr[2]) theCircuit.h(qr[2]) theCircuit.h(qr[3]) theCircuit.x(qr[3]) theCircuit = cu1pi2(theCircuit, qr[2], qr[3]) theCircuit.x(qr[2]) theCircuit.cz(qr[2], qr[3]) theCircuit.x(qr[2]) theCircuit.x(qr[3]) elif idx == 2: theCircuit.x(qr[2]) theCircuit.x(qr[3]) theCircuit.cz(qr[2], qr[3]) theCircuit.x(qr[3]) theCircuit.u1(pi/2.0, qr[3]) theCircuit.cx(qr[2], qr[3]) theCircuit.h(qr[2]) theCircuit.h(qr[3]) elif idx == 3: theCircuit.cx(qr[3], qr[2]) theCircuit.x(qr[3]) theCircuit.h(qr[3]) #measure the third and fourth qubits in the computational basis theCircuit.measure(qr[2], cr[2]) theCircuit.measure(qr[3], cr[3]) a, b = random.randint(1,3), random.randint(1,3) #generate random integers print("The values of a and b are, resp.,", a,b) aliceCircuit = aliceCircuits["Alice"+str(a)] bobCircuit = bobCircuits["Bob"+str(b)] circuitName = "Alice"+str(a)+"Bob"+str(b) Q_program.add_circuit(circuitName, sharedEntangled+aliceCircuit+bobCircuit) backend = "local_qasm_simulator" ##backend = "ibmqx2" shots = 1 # We perform a one-shot experiment results = Q_program.execute([circuitName], backend=backend, shots=shots) answer = results.get_counts(circuitName) print(answer) for key in answer.keys(): aliceAnswer = [int(key[-1]), int(key[-2])] bobAnswer = [int(key[-3]), int(key[-4])] if sum(aliceAnswer) % 2 == 0:#the sume of Alice answer must be even aliceAnswer.append(0) else: aliceAnswer.append(1) if sum(bobAnswer) % 2 == 1:#the sum of Bob answer must be odd bobAnswer.append(0) else: bobAnswer.append(1) break print("Alice answer for a = ", a, "is", aliceAnswer) print("Bob answer for b = ", b, "is", bobAnswer) if(aliceAnswer[b-1] != bobAnswer[a-1]): #check if the intersection of their answers is the same print("Alice and Bob lost") else: print("Alice and Bob won") backend = "local_qasm_simulator" #backend = "ibmqx2" shots = 10 # We perform 10 shots of experiments for each round nWins = 0 nLost = 0 for a in range(1,4): for b in range(1,4): print("Asking Alice and Bob with a and b are, resp.,", a,b) rWins = 0 rLost = 0 aliceCircuit = aliceCircuits["Alice"+str(a)] bobCircuit = bobCircuits["Bob"+str(b)] circuitName = "Alice"+str(a)+"Bob"+str(b) Q_program.add_circuit(circuitName, sharedEntangled+aliceCircuit+bobCircuit) if backend == "ibmqx2": ibmqx2_backend = Q_program.get_backend_configuration('ibmqx2') ibmqx2_coupling = ibmqx2_backend['coupling_map'] results = Q_program.execute([circuitName], backend=backend, shots=shots, coupling_map=ibmqx2_coupling, max_credits=3, wait=10, timeout=240) else: results = Q_program.execute([circuitName], backend=backend, shots=shots) answer = results.get_counts(circuitName) for key in answer.keys(): kfreq = answer[key] #frequencies of keys obtained from measurements aliceAnswer = [int(key[-1]), int(key[-2])] bobAnswer = [int(key[-3]), int(key[-4])] if sum(aliceAnswer) % 2 == 0: aliceAnswer.append(0) else: aliceAnswer.append(1) if sum(bobAnswer) % 2 == 1: bobAnswer.append(0) else: bobAnswer.append(1) #print("Alice answer for a = ", a, "is", aliceAnswer) #print("Bob answer for b = ", b, "is", bobAnswer) if(aliceAnswer[b-1] != bobAnswer[a-1]): #print(a, b, "Alice and Bob lost") nLost += kfreq rLost += kfreq else: #print(a, b, "Alice and Bob won") nWins += kfreq rWins += kfreq print("\t#wins = ", rWins, "out of ", shots, "shots") print("Number of Games = ", nWins+nLost) print("Number of Wins = ", nWins) print("Winning probabilities = ", (nWins*100.0)/(nWins+nLost))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qr = QuantumRegister(3) qc = QuantumCircuit(qr) c3h_gate = HGate().control(2) qc.append(c3h_gate, qr) qc.draw('mpl')
https://github.com/nahumsa/volta
nahumsa
# 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 qiskit from qiskit import execute # Observables made by hand, those observables are changed # for the more general function sample_hamiltonian def _measure_zz_circuit(qc: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit: """Construct the circuit to measure""" zz_circuit = qc.copy() zz_circuit.measure_all() return zz_circuit def _clear_counts(count: dict) -> dict: if "00" not in count: count["00"] = 0 if "01" not in count: count["01"] = 0 if "10" not in count: count["10"] = 0 if "11" not in count: count["11"] = 0 return count def measure_zz(qc, backend, shots=10000): """Measure the ZZ expectation value for a given circuit.""" zz_circuit = _measure_zz_circuit(qc) count = execute(zz_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count["00"] + count["11"] + count["01"] + count["10"] # Get counts for expected value zz_meas = count["00"] + count["11"] - count["01"] - count["10"] return zz_meas / total_counts def measure_zi(qc, backend, shots=10000): """Measure the ZI expectation value for a given circuit.""" zi_circuit = _measure_zz_circuit(qc) count = execute(zi_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count["00"] + count["11"] + count["01"] + count["10"] # Get counts for expected value zi_meas = count["00"] - count["11"] + count["01"] - count["10"] return zi_meas / total_counts def measure_iz(qc, backend, shots=10000): """Measure the IZ expectation value for a given circuit.""" iz_circuit = _measure_zz_circuit(qc) count = execute(iz_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count["00"] + count["11"] + count["01"] + count["10"] # Get counts for expected value iz_meas = count["00"] - count["11"] - count["01"] + count["10"] return iz_meas / total_counts def measure_xx(qc, backend, shots=10000): """Measure the XX expectation value for a given circuit.""" def _measure_xx_circuit( qc: qiskit.QuantumCircuit, ) -> qiskit.QuantumCircuit: """Construct the circuit to measure""" xx_circuit = qc.copy() xx_circuit.h(xx_circuit.qregs[0]) xx_circuit.measure_all() return xx_circuit xx_circuit = _measure_xx_circuit(qc) count = execute(xx_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count["00"] + count["11"] + count["01"] + count["10"] # Get counts for expected value xx_meas = count["00"] + count["11"] - count["01"] - count["10"] return xx_meas / total_counts def measure_yy(qc, backend, shots=10000): """Measure the YY expectation value for a given circuit.""" def _measure_yy_circuit( qc: qiskit.QuantumCircuit, ) -> qiskit.QuantumCircuit: """Construct the circuit to measure""" yy_meas = qc.copy() yy_meas.barrier(range(2)) yy_meas.sdg(range(2)) yy_meas.h(range(2)) yy_meas.measure_all() return yy_meas yy_circuit = _measure_yy_circuit(qc) count = execute(yy_circuit, backend=backend, shots=shots).result().get_counts() count = _clear_counts(count) # Get total counts in order to obtain the probability total_counts = count["00"] + count["11"] + count["01"] + count["10"] # Get counts for expected value xx_meas = count["00"] + count["11"] - count["01"] - count["10"] return xx_meas / total_counts
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXSimple from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXSimple())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(2) qc.h(0) qc.x(1) state = Statevector(qc) plot_bloch_multivector(state)
https://github.com/BoltzmannEntropy/QMLDocker
BoltzmannEntropy
%reset -f import matplotlib.font_manager import numpy as np from matplotlib import pyplot as plt font = { 'family':'SimHei', 'weight':'bold', 'size':'16' } matplotlib.rc("font",**font) from IPython.display import display_pretty import warnings warnings.filterwarnings("ignore") from qutip import * q = (1/np.sqrt(7))*Qobj(np.array([[1+ 1j], [1-2j]]).T) q.conj().full() p=(1/np.sqrt(2))*Qobj(np.array([[-1j], [1]])) p.full() q.conj()*p from sympy import Matrix, symbols, sqrt, init_printing from sympy.physics.quantum import TensorProduct from IPython.display import display_pretty init_printing(use_latex=True) a1 = symbols('a_1') b1 = symbols('b_1') a2 = symbols('a_2') b2 = symbols('b_2') # psi1 = Matrix(2,1,[a1,b1]) # psi2 = Matrix(2,1,[a2,b2]) U_I = Matrix([[1,0], [0,1]]) U_H = 1/sqrt(2)*Matrix([[1, 1], [1,-1]]) U_Z=Matrix(2,2,[1,0,0,-1]) Cnot=Matrix([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) psi1 = Matrix(2,1,[1,0]) psi2 = Matrix(2,1,[1,0]) psi12 = TensorProduct(psi1,psi2) U_FINAL= Cnot*(TensorProduct(U_I,U_Z)*TensorProduct(U_H,U_H))*psi12 U_FINAL from sympy import Matrix, symbols, sqrt, init_printing from sympy.physics.quantum import TensorProduct from IPython.display import display_pretty init_printing(use_latex=True) a1 = symbols('a_1') b1 = symbols('b_1') a2 = symbols('a_2') b2 = symbols('b_2') U_I = Matrix([[1,0], [0,1]]) U_H = 1/sqrt(2)*Matrix([[1, 1], [1,-1]]) U_Z=Matrix(2,2,[1,0,0,-1]) U_X=Matrix(2,2,[0,1,1,0]) Cnot=Matrix([[1,0,0,0], [0,1,0,0], [0,0,0,1], [0,0,1,0]]) psi0 = Matrix(2,1,[1,0]) psi1 = Matrix(2,1,[0,1]) psi3 = a1*psi0 + b1*psi1 psi3 # psi1 = Matrix(2,1,[a1,b1]) # psi2 = Matrix(2,1,[a2,b2]) # psi12 = TensorProduct(psi1,psi2) # # psi12 = psi1+ psi2 U_FINAL= TensorProduct(Cnot,U_I)*(TensorProduct(U_X,U_I,U_Z)*TensorProduct(Cnot,U_I))* TensorProduct(U_H,U_Z,U_I) U_FINAL * TensorProduct(psi0, psi1, psi0) from sympy import sqrt, symbols, Rational from sympy import expand, Eq, Symbol, simplify, exp, sin, srepr from sympy.physics.quantum import * from sympy.physics.quantum.qubit import * from sympy.physics.quantum.gate import * from sympy.physics.quantum.grover import * from sympy.physics.quantum.qft import QFT, IQFT, Fourier from sympy.physics.quantum.circuitplot import circuit_plot for gate in [X,Y,Z]: for state in [Qubit('0'),Qubit('1')]: lhs = gate(0)*state rhs = qapply(lhs) display(Eq(lhs,rhs)) %matplotlib inline import numpy as np from warnings import filterwarnings filterwarnings(action='ignore', category=DeprecationWarning) phi_plus = np.array([1, 0, 0, 1])/np.sqrt(2) # | Phi^+ > phi_minus = np.array([1, 0, 0, -1])/np.sqrt(2) # | Phi^- > psi_plus = np.array([0, 1, 1, 0])/np.sqrt(2) # | Psi^+ > psi_minus = np.array([0, 1, -1, 0])/np.sqrt(2) # | Psi^- > import torch initial_state = [1,0] # Define initial_state as |0> # initial_state = [0,1] # Define initial_state as |0> # initial_state = [1/np.sqrt(2), 1/np.sqrt(2)] # Define state |q_0> initial_state_torch = torch.tensor([initial_state]) x_gate_matrix = torch.tensor([[0,1],[1,0]]) out_state_torch = torch.mm(x_gate_matrix,initial_state_torch.t()) print("after X matrix, the state is ",out_state_torch.t()) # Display the output state vector import numpy from numpy import pi as PI import paddle import paddle_quantum from paddle import matmul from paddle_quantum.ansatz import Circuit from paddle_quantum.qinfo import random_pauli_str_generator, pauli_str_to_matrix from paddle_quantum.linalg import dagger N = 1 # Number of qubits SEED = np.random.randint(9999) # Fixed random seed # Generate random Hamiltonian represented by Pauli string numpy.random.seed(SEED) hamiltonian = random_pauli_str_generator(N, terms=1) print("Random Hamiltonian in Pauli string format = \n", hamiltonian) # Generate matrix representation of Hamiltonian complex_dtype = paddle_quantum.get_dtype() H = pauli_str_to_matrix(hamiltonian, N).astype(complex_dtype) H
https://github.com/quantumjim/pewpew_qiskit_workshops
quantumjim
run controller.py
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # CHANGED!!!! print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[4].draw("mpl") from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) dt_now = datetime.datetime.now() print(dt_now) import pickle with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in jobs: mit_results = meas_fitter.filter.apply(job.result()) rho = State fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.visualization.timeline import draw as timeline_draw from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") timeline_draw(circ)
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
from qiskit import QuantumCircuit from qiskit.compiler import transpile DEFAULT_GATES = ["rz", "h", "s", "cx", "cz"] def decompose(circ: QuantumCircuit, basis=None) -> QuantumCircuit: if basis is None: basis = DEFAULT_GATES return transpile(circ, basis_gates=basis)
https://github.com/KMU-quantum-classroom/qiskit-classroom-converter
KMU-quantum-classroom
import numpy as np from qiskit import( QuantumCircuit, execute, Aer) from qiskit.visualization import plot_histogram # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(2, 2) # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Map the quantum measurement to the classical bits circuit.measure([0,1], [0,1]) # Execute the circuit on the qasm simulator job = execute(circuit, simulator, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(circuit) print(counts) # Draw the circuit circuit.draw() print(circuit)
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/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit import math qc = QuantumCircuit(4) qc.rx(math.pi/2, [0,1,2,3]) qc.p(math.pi/8, 1) qc.s(2) qc.t(3) qc.draw("mpl")
https://github.com/tanjinadnanabir/qbosons-qiskit-hackathon
tanjinadnanabir
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() !pip install mlxtend !pip install lightgbm !pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git import pandas as pd import warnings warnings.filterwarnings('ignore') import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.patches import Patch from matplotlib.lines import Line2D from mlxtend.plotting import plot_decision_regions import seaborn as sns import networkx as nx from IPython.display import clear_output import plotly.graph_objects as go from plotly.subplots import make_subplots from sklearn import datasets from sklearn.datasets import make_hastie_10_2 from sklearn.ensemble import GradientBoostingClassifier, AdaBoostClassifier, RandomForestClassifier from sklearn import metrics from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score, classification_report from sklearn.preprocessing import LabelEncoder, StandardScaler, MinMaxScaler from sklearn.decomposition import PCA from sklearn.pipeline import make_pipeline from sklearn import svm from sklearn.svm import SVC from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.neural_network import MLPClassifier import lightgbm as lgbm from qiskit import Aer, execute from qiskit.opflow import Z, I, PauliExpectation, CircuitSampler, StateFn from qiskit.utils import QuantumInstance from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.algorithms.optimizers import GradientDescent, COBYLA, SLSQP, ADAM from qiskit.visualization import plot_state_city from qiskit_machine_learning.kernels import QuantumKernel from qiskit_machine_learning.algorithms import QSVC from qc_grader.utilities.graph_util import display_maxcut_widget, QAOA_widget from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error from qiskit.utils.mitigation import complete_meas_cal, CompleteMeasFitter from qiskit.opflow.gradients import Gradient, NaturalGradient, QFI, Hessian #from qiskit.algorithms.MulticlassExtension import AllPairs iris = datasets.load_iris() print(iris) iris.feature_names iris.target_names iris_df_data = pd.DataFrame(iris.data, columns = iris.feature_names) iris_df_target = pd.DataFrame(iris.target, columns = ['Iris Label']) iris_df_data # printing iris.data iris_df_target # printing iris.target; 0 : Setosa, 1: Versicolour, 2 : Virginica iris_df_data.describe() # standard decription of data iris_df_data.info() # standard info about data iris_df_data.columns # listing out column names of data iris_df_data['sepal length (cm)'].hist() # histogram plotting of data iris_df_data['sepal width (cm)'].hist() iris_df_data['petal length (cm)'].hist() iris_df_data['petal width (cm)'].hist() iris_df_target['Iris Label'].hist() # This means all flowers have equal number of samples # scatterplot of data irisSB = sns.load_dataset('iris') sns.set_style("darkgrid") sns.FacetGrid(irisSB, hue = "species", height = 6).map(plt.scatter, 'sepal_length', 'sepal_width').add_legend() sns.FacetGrid(irisSB, hue = "species", height = 6).map(plt.scatter, 'petal_length', 'petal_width').add_legend() sns.FacetGrid(irisSB, hue = "species", height = 6).map(plt.scatter, 'sepal_length', 'petal_length').add_legend() sns.FacetGrid(irisSB, hue = "species", height = 6).map(plt.scatter, 'sepal_width', 'petal_width').add_legend() # Pair Plot sns.pairplot(irisSB, hue = 'species') # Distplot for data plot = sns.FacetGrid(irisSB, hue = "species") plot.map(sns.distplot, "sepal_length").add_legend() plot = sns.FacetGrid(irisSB, hue = "species") plot.map(sns.distplot, "sepal_width").add_legend() plot = sns.FacetGrid(irisSB, hue = "species") plot.map(sns.distplot, "petal_length").add_legend() plot = sns.FacetGrid(irisSB, hue = "species") plot.map(sns.distplot, "petal_width").add_legend() plt.show() # Boxplot graph of features VS flower types def graph(y): sns.boxplot(x = "species", y = y, data = irisSB) plt.figure(figsize=(10,10)) # Adding the subplot at the specified # grid position plt.subplot(221) graph('sepal_length') plt.subplot(222) graph('sepal_width') plt.subplot(223) graph('petal_length') plt.subplot(224) graph('petal_width') plt.show() # Outliers for the features sns.boxplot(x = 'sepal_length', data = irisSB) sns.boxplot(x = 'sepal_width', data = irisSB) ## To remove Sepal Width Outliers using IQR(Interquartile Range) ## Code is contained in Single Hashes!! ## IQR #Q1 = np.percentile(irisSB['sepal_width'], 25, interpolation = 'midpoint') #Q3 = np.percentile(irisSB['sepal_width'], 75, interpolation = 'midpoint') #IQR = Q3 - Q1 #print("Old Shape: ", irisSB.shape) ## Upper bound #upper = np.where(irisSB['sepal_width'] >= (Q3+1.5*IQR)) ## Lower bound #lower = np.where(irisSB['sepal_width'] <= (Q1-1.5*IQR)) ## Removing the Outliers #irisSB.drop(upper[0], inplace = True) #irisSB.drop(lower[0], inplace = True) #print("New Shape: ", irisSB.shape) #sns.boxplot(x = 'sepal_width', data = irisSB) sns.boxplot(x = 'petal_length', data = irisSB) sns.boxplot(x = 'petal_width', data = irisSB) # Correlation Matrix iris_df_data.corr() # Petal Length and Petal Width have high correlation # Correlation Matrix Heatmap corr = iris_df_data.corr() fig, ax = plt.subplots(figsize=(5,4)) sns.heatmap(corr, annot=True, ax=ax, cmap = 'coolwarm') # cmap = 'darkgrid' for light colours sepal_length = iris['data'][:, 0] sepal_width = iris['data'][:, 1] petal_length = iris['data'][:, 2] petal_width = iris['data'][:, 3] target = iris['target'] #X = np.column_stack((sepal_length, sepal_width, petal_length, petal_width)) X = np.column_stack((sepal_length, sepal_width, petal_length, petal_width)) x = np.column_stack((sepal_length, sepal_width, petal_length)) # correlation of petal width and petal length is high, hence reducing variable Y = target x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 345) # Reduce dimensions n_dim = 4 pca = PCA(n_components = n_dim).fit(x_train) x_train = pca.transform(x_train) x_test = pca.transform(x_test) # Normalise std_scale = StandardScaler().fit(x_train) x_train = std_scale.transform(x_train) x_test = std_scale.transform(x_test) # Scale samples = np.append(x_train, x_test, axis = 0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) x_train = minmax_scale.transform(x_train) x_test = minmax_scale.transform(x_test) C = 1 # Regularlization Parameter clf_CSVC = make_pipeline(SVC(C = C, decision_function_shape = 'ovo')) # default kernel is ' RBF ' model_CSVC = clf_CSVC.fit(x_train, y_train) # CSVC Model Creation model_CSVC.score(x_test, y_test) # CSVC Model score against test data # Plotting Decision regions # The dimension should be 2 for plotting purposes # Also choose 2 features of the dataset #plot_decision_regions(X = x_test, y = y_test, clf = model_CSVC, legend = 1) # Split dataset sample_train, sample_test, label_train, label_test = train_test_split( x, Y, test_size = 0.2, random_state = 345) # Reduce dimensions n_dim = 3 pca = PCA(n_components = n_dim).fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # Normalise std_scale = StandardScaler().fit(sample_train) sample_train = std_scale.transform(sample_train) sample_test = std_scale.transform(sample_test) # Scale samples = np.append(sample_train, sample_test, axis=0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) sample_train = minmax_scale.transform(sample_train) sample_test = minmax_scale.transform(sample_test) # Select train_size = 120 sample_train = sample_train[:train_size] label_train = label_train[:train_size] test_size = 30 sample_test = sample_test[:test_size] label_test = label_test[:test_size] # Backend and Quantum Instance backend = Aer.get_backend('statevector_simulator') q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 345, seed_transpiler = 345) # Feature Map to convert classical data to quantum data, basically a parameterized Quantum Circuit # Can be used to map seemingly unseparable data to separable form, with respect to hyperplanes, in some higher dimension # This is achieved by e.g. rotation gate parameters depend on data features, etc. dim = 3 # Feature Dimension = number of qubits feature_map = ZZFeatureMap(feature_dimension = dim, reps = 1, entanglement = 'linear', insert_barriers = True, parameter_prefix = 'x').decompose() feature_map.draw('mpl', style = 'iqx') # Quantum Kernel q_kernel = QuantumKernel(feature_map = feature_map, quantum_instance = q_instance) q_circuit = q_kernel.construct_circuit(sample_train[0], sample_train[1]) q_circuit.decompose().decompose().draw(output = 'mpl') # Noise Model : Measurement error def get_noise(pm,pg): error_meas = pauli_error([('X',pm), ('I', 1 - pm)]) error_gate1 = depolarizing_error(pg,1) error_gate2 = error_gate1.tensor(error_gate1) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error_meas, "measure") # measurement error is applied to measurements noise_model.add_all_qubit_quantum_error(error_gate1, ["h"]) # single qubit gate error is applied to H gates noise_model.add_all_qubit_quantum_error(error_gate1, ["p"]) # single qubit gate error is applied to P gates noise_model.add_all_qubit_quantum_error(error_gate2, ["cx"]) # two qubit gate error is applied to CX gates return noise_model noise_model = get_noise(0.01,0.01) # Without Noise job = execute(q_circuit, backend = backend, shots = 10000, seed_simulator = 345, seed_transpiler = 345) counts = job.result().get_counts(q_circuit) plot_histogram(counts) # With Noise Noisy_job = execute(q_circuit, backend = backend, shots = 10000, seed_simulator = 345, seed_transpiler = 345, noise_model = noise_model) Noisy_counts = Noisy_job.result().get_counts(q_circuit) plot_histogram(Noisy_counts) # Error mitigation meas_calibs, state_labels = complete_meas_cal(qr = 3, circlabel =' mcal') cal_results = execute(meas_calibs, backend = backend, shots = 10000, seed_simulator = 345, seed_transpiler = 345, noise_model=noise_model).result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') meas_filter = meas_fitter.filter mitigated_results = meas_filter.apply(Noisy_job.result()) mitigated_counts = mitigated_results.get_counts(q_circuit) plot_histogram(mitigated_counts) plot_histogram([counts, Noisy_counts, mitigated_counts], legend = ['Without Noisy','Noisy', 'Mitigated']) # As we can see from the plot, the noise will not affect the score a lot, as the plots are similar in nature # Kernel Matrix Evaluation matrix_train = q_kernel.evaluate(x_vec = sample_train) matrix_test = q_kernel.evaluate(x_vec = sample_test, y_vec = sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation = 'nearest', origin = 'upper', cmap = 'Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_test), interpolation = 'nearest', origin = 'upper', cmap = 'Reds') axs[1].set_title("testing kernel matrix") plt.show() qpc_svc = make_pipeline(SVC(kernel='precomputed', C = 100)) # QSVC precomputed qpc_svc.fit(matrix_train, label_train) qpc_score = qpc_svc.score(matrix_test, label_test) print(f'Precomputed kernel classification test score: {qpc_score}') # best possible score we got after after trying many combinations """ NOTE : On using the multiclass extension function = " AllPairs " on a previous version of Qiskit, we get score of 1! Hope they introduce it back! """ """ This work of ours is a result of 'Qiskit Fall Fest Kolkata Chapter Hackathon', hosted by Mr. Ritajit Majumdar and Ms. Debasmita Bhowmik from Indian Statistical Institute, in collaboration with IBM Quantum""" # Authors # Vismay Joshi, National Institute Of Technology, Agartala # Tanjin Adnan Abir, Jahangirnagar University # Abhishek Rawat, TCG CREST # Suprabhat Sinha, D Y Patil International University # Rajat Lakhera, Sri Dev Suman Uttarakhand University import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/sooodos/Quantum-Computing-Learning-Gate
sooodos
from datetime import datetime import matplotlib.pyplot as plt from qiskit import QuantumCircuit, BasicAer, execute, IBMQ, transpile from qiskit.providers import BaseJob from qiskit.providers.ibmq import least_busy, IBMQJobManager from qiskit.providers.ibmq.managed import ManagedJobSet from qiskit.visualization import plot_histogram import constants from QCLG_lvl3.classical.bernstein_vazirani_classical import BersteinVaziraniClassical from QCLG_lvl3.classical.classical_xor import ClassicalXor from QCLG_lvl3.classical.random_binary import RandomBinary from QCLG_lvl3.quantum_algorithms.bernstein_vazirani import BernsteinVazirani from QCLG_lvl3.quantum_algorithms.deutsch_josza import DeutschJosza from credentials import account_details class Tools: @classmethod def calculate_elapsed_time(cls, first_step: datetime, last_step: datetime): difference = last_step - first_step return difference.total_seconds() @classmethod def run_on_simulator(cls, circuit: QuantumCircuit): # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(circuit, backend=backend, shots=shots).result() answer = results.get_counts() max_value = 0 max_key = "" for key, value in answer.items(): if value > max_value: max_value = value max_key = key return max_key[::-1] @classmethod def run_on_real_device(cls, circuit: QuantumCircuit, least_busy_backend): from qiskit.tools.monitor import job_monitor shots = int(input("Number of shots (distinct executions to run this experiment: )")) job = execute(circuit, backend=least_busy_backend, shots=shots, optimization_level=3) job_monitor(job, interval=2) return job @classmethod def find_least_busy_backend_from_open(cls, n): if account_details.account_token_open is None: account_token = input("Insert your account token: ") else: account_token = account_details.account_token_open if IBMQ.active_account() is None: IBMQ.enable_account(account_token) provider = IBMQ.get_provider(hub='ibm-q') return least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n + 1) and not x.configuration().simulator and x.status().operational == True)) @classmethod def find_least_busy_backend_from_research(cls, n): if account_details.account_token_research is None \ or account_details.hub is None \ or account_details.group is None \ or account_details.project is None: account_token = input("Insert your account token: ") hub = input("Insert your hub: ") group = input("Insert your group: ") project = input("Insert your project: ") else: account_token = account_details.account_token_research hub = account_details.hub group = account_details.group project = account_details.project IBMQ.enable_account(account_token) provider = IBMQ.get_provider(hub=hub, group=group, project=project) print(provider) return least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n + 1) and not x.configuration().simulator and x.status().operational == True)) @classmethod def print_simul(cls, answer_of_simul, algorithm: str): print(constants.algorithms[int(algorithm)]) print("\nMeasurements: ", answer_of_simul) return @classmethod def print_real(cls, job: BaseJob, least_busy_backend, algorithm: str): results = job.result() answer = results.get_counts() print("\nTotal counts are:", answer) elapsed = results.time_taken print(f"The time it took for the experiment to complete after validation was {elapsed} seconds") plot_histogram(data=answer, title=f"{constants.algorithms[int(algorithm)]} on {least_busy_backend}") plt.show() return @classmethod def execute_classically(cls, algorithm): if algorithm == "0": return cls.execute_deutsch_josza_classically() elif algorithm == "1": return cls.execute_bernstein_vazirani_classically() @classmethod def execute_in_simulator(cls, algorithm): dj_circuit = None if algorithm == "0": bits = str(input("Enter a bit sequence for the quantum circuit:")) dj_circuit = DeutschJosza.deutsch_josza(bits, eval_mode=False) elif algorithm == "1": decimals = int(input("Give the upper limit of the random number: ")) random_binary = RandomBinary.generate_random_binary(decimals) dj_circuit = BernsteinVazirani.bernstein_vazirani(random_binary, eval_mode=False) return cls.run_on_simulator(dj_circuit) @classmethod def execute_in_real_device(cls, algorithm): if algorithm == "0": answer = cls.execute_dj_in_real_device() return answer elif algorithm == "1": decimals = int(input("Give the upper limit of the random number: ")) random_binary = RandomBinary.generate_random_binary(decimals) answer = cls.execute_bv_in_real_device(random_binary) return answer @classmethod def execute_dj_in_real_device(cls): bits = str(input("Enter a bit sequence for the quantum circuit:")) least_busy_backend = Tools.choose_from_provider(len(bits) + 1) dj_circuit = DeutschJosza.deutsch_josza(bits, eval_mode=False) answer_of_real = Tools.run_on_real_device(dj_circuit, least_busy_backend) print(f"least busy is {least_busy_backend}") return answer_of_real @classmethod def execute_bv_in_real_device(cls, random_binary: str): dj_circuit = BernsteinVazirani.bernstein_vazirani(random_binary, eval_mode=False) least_busy_backend = Tools.choose_from_provider(dj_circuit.qubits) answer_of_real = Tools.run_on_real_device(dj_circuit, least_busy_backend) print(f"least busy is {least_busy_backend}") return answer_of_real @classmethod def choose_from_provider(cls, size: int): least_busy_backend = None research = input("Do you want to run this experiment on the research backends? (Y/N)") while research != "Y" and research != "N": research = input("Do you want to run this experiment on the research backends? (Y/N)") if research == "N": least_busy_backend = Tools.find_least_busy_backend_from_open(size) elif research == "Y": least_busy_backend = Tools.find_least_busy_backend_from_research(size) return least_busy_backend @classmethod def execute_deutsch_josza_classically(cls): number_of_bits = int(input("Enter number of bits for a the classical solution:")) return ClassicalXor.execute_classical_xor(bits=number_of_bits) @classmethod def execute_bernstein_vazirani_classically(cls): decimals = int(input("Give the upper limit of the random number: ")) random_binary = RandomBinary.generate_random_binary(decimals) return BersteinVaziraniClassical.guess_number(random_binary) @classmethod def print_classical_answer(cls, classical_answer, algorithm): time_to_generate_worst_input = classical_answer[0] execution_time = classical_answer[1] bits = classical_answer[2] function_nature = classical_answer[3] print(f"Results of classical implementation for the {constants.algorithms[int(algorithm)]} Algorithm:") print(f"Function is {function_nature}") print(f"Time to generate worse input for {bits} bits took {time_to_generate_worst_input} seconds.") print(f"Determining if xor is balanced for {bits} bits took {execution_time} seconds.") print(classical_answer) @classmethod def execute_both(cls, algorithm): answer = [] if algorithm == "0": classical = cls.execute_deutsch_josza_classically() real = cls.execute_dj_in_real_device() answer.append(classical) answer.append(real) elif algorithm == " 1": classical = cls.execute_bernstein_vazirani_classically() real = cls.execute_bv_in_real_device(classical) answer.append(classical) answer.append(real) return answer # ################################################################################################################# # Evaluation methods @classmethod def prepare_dj(cls, bits: int): bit_sequence = "0" * bits dj_circuit = DeutschJosza.deutsch_josza(bit_sequence, eval_mode=True) return dj_circuit @classmethod def prepare_bv(cls, random_binary: str): bj_circuit = BernsteinVazirani.bernstein_vazirani(random_binary, eval_mode=True) return bj_circuit @classmethod def deutsch_josza_classical(cls, bits: int): return ClassicalXor.execute_classical_xor(bits=bits) @classmethod def bernstein_vazirani_classical(cls, bits: int): random_binary = RandomBinary.generate_random_binary_v2(bits) return BersteinVaziraniClassical.guess_number(random_binary) @classmethod def run_batch_job(cls, circuits: list, least_busy_backend) -> ManagedJobSet: transpiled_circuits = transpile(circuits, backend=least_busy_backend) # Use Job Manager to break the circuits into multiple jobs. job_manager = IBMQJobManager() job_set_eval = job_manager.run(transpiled_circuits, backend=least_busy_backend, name='eval', max_experiments_per_job=1) # max_experiments_per_job =1 very important to get # individual execution times return job_set_eval
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate, Initialize from qiskit.providers.ibmq.managed import IBMQJobManager import numpy as np from sys import stdout from scipy.stats import unitary_group class global_max_SPEA: """ This is a class which implements the Statistical Phase Estimation algorithm. The global max SPEA looks to update the cost returned at the end of one itertation as compared to the original normal SPEA. This allows an advantage of the bundling up of circuits and thus helps to speed up the quantum execution time. paper1 - https://arxiv.org/pdf/2104.10285.pdf paper2 - https://arxiv.org/pdf/1906.11401.pdf(discussion) Attributes : resolution(int) : the number of intervals the angle range has to be divided into dims(int) : dimensions of the passed unitary matrix c_unitary_gate(Unitary Gate) : the controlled unitary gate in our algorithm error(int) : the number of places after decimal, upto which the cost of the algorithm would be estimated itrations(int) : the maximum iterations after which the algorithm ends the computation basis(list of np.ndarray) : the basis generated at the start of the algorithm unitary_circuit(QuantumCircuit): a pre-transpiled QuantumCircuit which is applied during the algorithm Methods : __get_basis_vectors(randomize) : Get the d dimensional basis for the initializtion of the algorithm __get_unitary_circuit(backend) : Get the pre-transpiled circuit for the unitary matrix __get_alternate_cost(angle,state,backend,shots) : Get the cost through the alternate method specified in the algorithm __get_standard_cost(angle,state,backend,shots) : Get the cost through the standard method specified in the algorithm __get_circuit(state,angle,backend,shots) : Get the completed circuit used inside the algorithm to estimate the phase get_eigen_pair(backend, algo='alternate', theta_left,theta_right,progress, randomize, target_cost, basis, basis_ind,shots) : Get the eigenstate and eigenphase phase pair for the unitary matrix """ def __init__(self, unitary, resolution=100, error=3, max_iters=20): # handle resolution if not isinstance(resolution, int): raise TypeError("Please enter the number of intervals as an integer value") if resolution < 10 or resolution > 1e6: raise ValueError( "Resolution needs to be atleast 0.1 and greater than 0.000001" ) self.resolution = resolution # handle unitary if ( not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit) and not isinstance(unitary, UnitaryGate) ): raise TypeError( "A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix" ) # convert circuit to numpy array for uniformity if isinstance(unitary, UnitaryGate): U = unitary.to_matrix() else: # both QC and ndarray type U = unitary # note - the unitary here is not just a single qubit unitary if isinstance(U, np.ndarray): self.dims = U.shape[0] else: self.dims = 2 ** (U.num_qubits) if isinstance(U, np.ndarray): self.c_unitary_gate = UnitaryGate(data=U).control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) else: self.c_unitary_gate = U.control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) # handle error if not isinstance(error, int): raise TypeError( "The allowable error should be provided as an int. Interpreted as 10**(-error)" ) if error <= 0: raise ValueError("The error threshold must be finite and greater than 0.") self.error = error # handle max_iters if not isinstance(max_iters, int): raise TypeError("Max iterations must be of integer type") if max_iters <= 0 and max_iters > 1e5: raise ValueError("Max iterations should be atleast 1 and less than 1e5") self.iterations = max_iters self.basis = [] def __get_basis_vectors(self, randomize=True): """Get the d dimensional basis for the unitary provided Args : randomize (bool) : whether to pick a random basis or not Returns: a list of np.ndarrays which are used as the basis vectors""" if randomize == True: UR = unitary_group.rvs(self.dims) else: UR = np.identity(self.dims) basis = [] for k in UR: basis.append(np.array(k, dtype=complex)) return basis def __get_unitary_circuit(self, backend): """Return the pretranspiled circuit Args: backend : the IBMQBackend on which we want to transpile. If None, Default : 'qasm_simulator' Returns: QuantumCircuit containing the transpiled circuit for the controlled unitary """ if backend is None: backend = Aer.get_backend("qasm_simulator") qc = QuantumCircuit(1 + int(np.log2(self.dims))) # make the circuit qc.h(0) qc = qc.compose(self.c_unitary_gate, qubits=range(1 + int(np.log2(self.dims)))) qc.barrier() qc = transpile(qc, backend=backend, optimization_level=3) return qc def __get_circuit(self, state, backend, shots, angle=None): """Given an initial state , return the assembled and transpiled circuit that is generated with inverse rotation Args: state(np.ndarray) : The eigenvector guess state for the initialization backend(IBMQBackend) : the backend on which this circuit is going to be executed shots(int) : the number of shots in our experiments angle(float) : whether the returned circuit contains an inverse rotation gate or not. If angle is None, no rotation gate attached Else, cp(angle) is attached on control qubit 0 Returns: QuantumCircuit which is pre-transpiled according to the backend provided """ # all theta values are iterated over for the same state phi = Initialize(state) qc1 = QuantumCircuit(1 + int(np.log2(self.dims)), 1) # initialize the circuit qc1 = qc1.compose(phi, qubits=list(range(1, int(np.log2(self.dims)) + 1))) qc1.barrier() qc1 = transpile(qc1, backend=backend, optimization_level=1) # get the circuit2 qc2 = self.unitary_circuit qc3 = QuantumCircuit(1 + int(np.log2(self.dims)), 1) if angle is not None: # add inverse rotation on the first qubit qc3.p(-2 * np.pi * angle, 0) # add hadamard qc3.h(0) qc3 = transpile(qc3, backend=backend, optimization_level=1) # make final circuit qc = qc1 + qc2 + qc3 # measure qc.measure([0], [0]) # qc = assemble(qc,shots = shots) return qc def __get_standard_cost(self, angles, state, backend, shots): """Given an initial state and a set of angles, return the best cost and the associated angle. Implements the standard method as specified in the paper. Args : angles(np.ndarray) : the set of angles on which we execute the circuits state(np.ndarray) : the initialization state provided backend(IBMQBackend): the backend on which this circuit needs to be executed shots(int) : the number of shots used to execute this circuit Returns : result(dict) : {result : (float), theta : (float)} result - the best cost given this set of angles theta - the best theta value amongst this set of angles""" result = {"cost": -1, "theta": -1} # all theta values are iterated over for the same state circuits = [] for theta in angles: qc = self.__get_circuit(state, backend, shots, theta) circuits.append(qc) # execute only once... counts = backend.run(circuits, shots=shots).result().get_counts() # get the cost for this theta for k, theta in zip(counts, angles): # for all experiments you ran try: C_val = (k["0"]) / shots except: C_val = 0 if C_val > result["cost"]: # means this is a better theta value result["theta"] = theta result["cost"] = C_val return result def __get_alternate_cost(self, angles, state, backend, shots): """Given an initial state and a set of angles, return the best cost and the associated angle. Implements the alternate method as specified in the paper1 and discussion of paper2. Args : angles(np.ndarray) : the set of angles on which we execute the circuits state(np.ndarray) : the initialization state provided backend(IBMQBackend): the backend on which this circuit needs to be executed shots(int) : the number of shots used to execute this circuit Returns : result(dict) : {result : (float), theta : (float)} result - the best cost given this set of angles theta - the best theta value amongst this set of angles""" result = {"cost": -1, "theta": -1} # all theta values are iterated over for the same state # run the circuit once qc = self.__get_circuit(state, backend, shots) # execute only once... counts = backend.run(qc, shots=shots).result().get_counts() # generate experimental probabilities try: p0 = counts["0"] / shots except: p0 = 0 try: p1 = counts["1"] / shots except: p1 = 0 # now, find the best theta as specified by the # alternate method classically min_s = 1e5 for theta in angles: # generate theoretical probabilities c0 = (np.cos(np.pi * theta)) ** 2 c1 = (np.sin(np.pi * theta)) ** 2 # generate s value s = (p0 - c0) ** 2 + (p1 - c1) ** 2 if s < min_s: result["theta"] = theta min_s = s # now , we have the best theta stored in phi # run circuit once again to get the value of C* qc = self.__get_circuit(state, backend, shots, result["theta"]) counts = backend.run(qc, shots=shots).result().get_counts() try: result["cost"] = counts["0"] / shots except: result["cost"] = 0 # no 0 counts present # return the result return result def __validate_params( self, algorithm, progress, randomize, target_cost, bounds ) -> None: # validate algorithm if not isinstance(algorithm, str): raise TypeError( "Algorithm must be mentioned as a string from the values {alternate,standard}" ) elif algorithm not in ["alternate", "standard"]: raise ValueError( "Algorithm must be specified as 'alternate' or 'standard' " ) # validate progress if not isinstance(progress, bool): raise TypeError("Progress must be a boolean variable") if not isinstance(randomize, bool): raise Exception("Randomize must be a boolean variable") # validate target_cost if target_cost is not None: if not isinstance(target_cost, float): raise TypeError("Target cost must be a float") if target_cost <= 0 or target_cost >= 1: raise ValueError("Target cost must be a float value between 0 and 1") # validate bounds theta_left, theta_right = bounds[0], bounds[1] if theta_left > theta_right: raise ValueError( "Left bound for theta should be smaller than the right bound" ) elif (theta_left < 0) or (theta_right > 1): raise ValueError("Bounds of theta are [0,1].") def get_eigen_pair( self, backend, algo="alternate", theta_left=0, theta_right=1, progress=False, basis=None, basis_ind=None, randomize=True, target_cost=None, shots=512, ): """Finding the eigenstate pair for the unitary Args : backend(IBMQBackend) : the backend on which the circuit needs to be executed algo(str) : ['alternate','standard'] the algorithm to use as specified in the paper1 section 3. theta_left(float): the left bound for the search of eigenvalue. Default : 0 theta_right(float): the right bound for the search of eigenvalue. Default : 1 progress(bool) : Whether to show the progress as the algorithm runs randomize(bool): Whether to choose random initialization of basis states or not If False, computational basis is chosen. target_cost(float) : the min cost required to be achieved by the algorithm basis(list of np.ndarray) : The basis to be used in the algorithm. Note, if basis is specified, randomize value is ignored basis_ind(int) : the index of the basis vector to be used as the initial state vector Returns : result(dict) : {cost :(float), theta :(float), state : (np.ndarray) cost - the cost with which the algorithm terminates theta - the eigenvalue estimated by SPEA state - the eigenvector estimated by SPEA Example Usage found in notebook Statistical QPE-Changed Algorithm.ipynb""" self.unitary_circuit = self.__get_unitary_circuit(backend) self.__validate_params( algo, progress, randomize, target_cost, [theta_left, theta_right] ) results = dict() # first initialize the state phi if basis is None: self.basis = self.__get_basis_vectors(randomize) else: # is basis is specified, given as array of vectors... self.basis = basis # choose a random index if basis_ind is None: ind = np.random.choice(self.dims) else: # choose the index given in that basis ind = basis_ind phi = self.basis[ind] # doing the method 1 of our algorithm # define resolution of angles and precision if target_cost == None: precision = 1 / 10 ** self.error else: precision = 1 - target_cost samples = self.resolution # initialization of range left, right = theta_left, theta_right # generate the angles angles = np.linspace(left, right, samples) # iterate once if algo == "alternate": result = self.__get_alternate_cost(angles, phi, backend, shots) else: result = self.__get_standard_cost(angles, phi, backend, shots) # get initial estimates cost = result["cost"] theta_max = result["theta"] best_phi = phi # the range upto which theta extends iin each iteration angle_range = (right - left) / 2 # a parameter a = 1 # start algorithm iters = 0 found = True while 1 - cost >= precision: # get angles, note if theta didn't change, then we need to # again generate the same range again right = min(theta_right, theta_max + angle_range / 2) left = max(theta_left, theta_max - angle_range / 2) if progress: print("Right :", right) print("Left :", left) # generate the angles only if the theta has been updated if found == True: angles = np.linspace(left, right, samples) found = False # for this iteration if progress: print("ITERATION NUMBER", iters + 1, "...") # generate a cost dict for each of the iterations thetas, costs, states = [], [], [] for i in range((2 * self.dims)): # everyone is supplied with the same range of theta in one iteration # define z if i < self.dims: z = 1 else: z = 1j # alter and normalise phi curr_phi = best_phi + z * a * (1 - cost) * self.basis[i % self.dims] curr_phi = curr_phi / np.linalg.norm(curr_phi) # iterate (angles would be same until theta is changed) if algo == "alternate": res = self.__get_alternate_cost(angles, curr_phi, backend, shots) else: res = self.__get_standard_cost(angles, curr_phi, backend, shots) curr_cost = res["cost"] curr_theta = res["theta"] # append these parameters # bundle the circuits together ... if ( curr_cost > cost ): # then only add this cost in the cost and states list thetas.append(float(curr_theta)) costs.append(float(curr_cost)) states.append(curr_phi) found = True # now each iteration would see the same state as the best phi # is updated once at the end of the iteration # also, the cost is also updated only once at the end of the iteration if progress: stdout.write("\r") stdout.write("%f %%completed" % (100 * (i + 1) / (2 * self.dims))) stdout.flush() # 1 iteration completes if found == False: # phi was not updated , change a a = a / 2 if progress: print("\nNo change, updating a...") else: # if found is actually true, then only update # O(n) , would update this though index = np.argmax(costs) # update the parameters of the model cost = costs[index] theta_max = thetas[index] best_phi = states[index] if progress: print("Best Phi is :", best_phi) print("Theta estimate :", theta_max) print("Current cost :", cost) angle_range /= 2 # updated phi and thus theta too -> refine theta range # update the iterations iters += 1 if progress: print("\nCOST :", cost) print("THETA :", theta_max) if iters >= self.iterations: print( "Maximum iterations reached for the estimation.\nTerminating algorithm..." ) break # add cost, eigenvector and theta to the dict results["cost"] = cost results["theta"] = theta_max results["state"] = best_phi return results class bundled_SPEA_alternate: def __init__(self, unitary, resolution=100, error=3, max_iters=20): # handle resolution if not isinstance(resolution, int): raise TypeError("Please enter the number of intervals as an integer value") if resolution < 10 or resolution > 1e6: raise ValueError( "Resolution needs to be atleast 0.1 and greater than 0.000001" ) self.resolution = resolution # handle unitary if ( not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit) and not isinstance(unitary, UnitaryGate) ): raise TypeError( "A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix" ) # convert circuit to numpy array for uniformity if isinstance(unitary, UnitaryGate): U = unitary.to_matrix() else: # both QC and ndarray type U = unitary # note - the unitary here is not just a single qubit unitary if isinstance(U, np.ndarray): self.dims = U.shape[0] else: self.dims = 2 ** (U.num_qubits) if isinstance(U, np.ndarray): self.c_unitary_gate = UnitaryGate(data=U).control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) else: self.c_unitary_gate = U.control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) # handle error if not isinstance(error, int): raise TypeError( "The allowable error should be provided as an int. Interpreted as 10**(-error)" ) if error <= 0: raise ValueError("The error threshold must be finite and greater than 0.") self.error = error # handle max_iters if not isinstance(max_iters, int): raise TypeError("Max iterations must be of integer type") if max_iters <= 0 and max_iters > 1e5: raise ValueError("Max iterations should be atleast 1 and less than 1e5") self.iterations = max_iters self.basis = [] def get_basis_vectors(self, randomize=True): # get the d dimensional basis for the unitary provided if randomize == True: UR = unitary_group.rvs(self.dims) else: UR = np.identity(self.dims) basis = [] for k in UR: basis.append(np.array(k, dtype=complex)) return basis def get_unitary_circuit(self, backend): """Return the pretranspiled circuit""" if backend is None: backend = Aer.get_backend("qasm_simulator") qc = QuantumCircuit(1 + int(np.log2(self.dims))) # make the circuit qc.h(0) qc = qc.compose(self.c_unitary_gate, qubits=range(1 + int(np.log2(self.dims)))) qc.barrier() qc = transpile(qc, backend=backend, optimization_level=3) return qc def get_circuit(self, state, backend, shots, angle=None): """Given an initial state , return the circuit that is generated with inverse rotation as 0.""" # all theta values are iterated over for the same state phi = Initialize(state) shots = 512 qc1 = QuantumCircuit(1 + int(np.log2(self.dims)), 1) # initialize the circuit qc1 = qc1.compose(phi, qubits=list(range(1, int(np.log2(self.dims)) + 1))) qc1 = transpile(qc1, backend=backend) # get the circuit2 qc2 = self.unitary_circuit qc3 = QuantumCircuit(1 + int(np.log2(self.dims)), 1) if angle is not None: # add inverse rotation on the first qubit qc3.p(-2 * np.pi * angle, 0) # add hadamard qc3.h(0) qc3 = transpile(qc3, backend=backend) # make final circuit qc = qc1 + qc2 + qc3 # qc = assemble(qc,shots = shots) # measure qc.measure([0], [0]) return qc def get_optimal_angle(self, p0, p1, angles): """Return the theta value which minimizes the S metric""" min_s = 1e5 best_theta = -1 for theta in angles: c0 = (np.cos(np.pi * theta)) ** 2 c1 = (np.sin(np.pi * theta)) ** 2 # generate the metric ... s = (p0 - c0) ** 2 + (p1 - c1) ** 2 if s < min_s: s = min_s best_theta = theta return best_theta def execute_job(self, progress, iteration, backend, shots, circuits): """Send a job to the backend using IBMQ Job Manager""" # define IBMQManager instance manager = IBMQJobManager() # first run the generated circuits if progress: print("Transpiling circuits...") # get the job runner instance job_set = manager.run( circuits, backend=backend, name="Job_set " + str(iteration), shots=shots ) if progress: print("Transpilation Done!\nJob sent...") # send and get job job_result = job_set.results() if progress: print("Job has returned") # return result return job_result def get_eigen_pair( self, backend, theta_left=0, theta_right=1, progress=False, randomize=True, basis=None, basis_ind=None, target_cost=None, shots=512, ): """Finding the eigenstate pair for the unitary""" self.unitary_circuit = self.get_unitary_circuit(backend) if theta_left > theta_right: raise ValueError( "Left bound for theta should be smaller than the right bound" ) elif (theta_left < 0) or (theta_right > 1): raise ValueError("Bounds of theta are [0,1].") if not isinstance(progress, bool): raise TypeError("Progress must be a boolean variable") if not isinstance(randomize, bool): raise Exception("Randomize must be a boolean variable") results = dict() # first initialize the state phi if basis is None: self.basis = self.get_basis_vectors(randomize) else: self.basis = basis # choose a random index if basis_ind is None: ind = np.random.choice(self.dims) else: ind = basis_ind phi = self.basis[ind] # doing the method 1 of our algorithm # define resolution of angles and precision precision = 1 / 10 ** self.error samples = self.resolution # initialization of range left, right = theta_left, theta_right # generate the angles angles = np.linspace(left, right, samples) # First execution can be done without JobManager also... circ = self.get_circuit(phi, backend=backend, shots=shots) job = execute(circ, backend=backend, shots=shots) counts = job.result().get_counts() if "0" in counts: p0 = counts["0"] else: p0 = 0 if "1" in counts: p1 = counts["1"] else: p1 = 0 # experimental probabilities p0, p1 = p0 / shots, p1 / shots # get initial angle estimate theta_max = self.get_optimal_angle(p0, p1, angles) # get intial cost circ = self.get_circuit(phi, backend=backend, shots=shots, angle=theta_max) job = execute(circ, backend=backend, shots=shots) counts = job.result().get_counts() if "0" in counts: cost = counts["0"] / shots else: cost = 0 # update best phi best_phi = phi # the range upto which theta extends iin each iteration angle_range = (right - left) / 2 # a parameter a = 1 # start algorithm iters = 0 found = True while 1 - cost >= precision: # get angles, note if theta didn't change, then we need to # again generate the same range again right = min(theta_right, theta_max + angle_range / 2) left = max(theta_left, theta_max - angle_range / 2) if progress: print("Right :", right) print("Left :", left) # generate the angles only if the theta has been updated if found == True: angles = np.linspace(left, right, samples) found = False # for this iteration if progress: print("ITERATION NUMBER", iters + 1, "...") # generate a cost dict for each of the iterations # final result lists costs, states = [], [] # circuit list circuits = [] # 1. Circuit generation loop for i in range((2 * self.dims)): # everyone is supplied with the same range of theta in one iteration # define z if i < self.dims: z = 1 else: z = 1j # alter and normalise phi curr_phi = best_phi + z * a * (1 - cost) * self.basis[i % self.dims] curr_phi = curr_phi / np.linalg.norm(curr_phi) states.append(curr_phi) # bundle the circuits together ... circuits.append( self.get_circuit(curr_phi, backend=backend, shots=shots) ) job_result = self.execute_job(progress, iters, backend, shots, circuits) # define lists again thetas, circuits = [], [] # 3. Classical work for i in range((2 * self.dims)): # we have that many circuits only counts = job_result.get_counts(i) # get the experimental counts for this state try: exp_p0 = counts["0"] except: exp_p0 = 0 try: exp_p1 = counts["1"] except: exp_p1 = 0 # normalize exp_p0 = exp_p0 / shots exp_p1 = exp_p1 / shots theta_val = self.get_optimal_angle(exp_p0, exp_p1, angles) # generate the circuit and append circuits.append( self.get_circuit( states[i], backend=backend, shots=shots, angle=theta_val ) ) thetas.append(theta_val) # again execute these circuits job_result = self.execute_job(progress, iters, backend, shots, circuits) # 5. Result generation loop for i in range((2 * self.dims)): # cost generation after execution ... counts = job_result.get_counts(i) if "0" in counts: curr_cost = counts["0"] / (shots) else: curr_cost = 0 if ( curr_cost > cost ): # then only add this cost in the cost and states list cost = curr_cost best_phi = states[i] theta_max = thetas[i] found = True if progress: stdout.write("\r") stdout.write("%f %%completed" % (100 * (i + 1) / (2 * self.dims))) stdout.flush() if found == False: # phi was not updated , change a a = a / 2 if progress: print("\nNo change, updating a...") else: # if found is actually true, then only print if progress: print("Best Phi is :", best_phi) print("Theta estimate :", theta_max) print("Current cost :", cost) angle_range /= 2 # updated phi and thus theta too -> refine theta range # update the iterations iters += 1 if progress: print("\nCOST :", cost) print("THETA :", theta_max) if iters >= self.iterations: print( "Maximum iterations reached for the estimation.\nTerminating algorithm..." ) break # add cost, eigenvector and theta to the dict results["cost"] = cost results["theta"] = theta_max results["state"] = best_phi return results class bundled_changed_SPEA: def __init__(self, unitary, resolution=100, error=3, max_iters=20): # handle resolution if not isinstance(resolution, int): raise TypeError("Please enter the number of intervals as an integer value") if resolution < 10 or resolution > 1e6: raise ValueError( "Resolution needs to be atleast 0.1 and greater than 0.000001" ) self.resolution = resolution # handle unitary if ( not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit) and not isinstance(unitary, UnitaryGate) ): raise TypeError( "A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix" ) # convert circuit to numpy array for uniformity if isinstance(unitary, UnitaryGate): U = unitary.to_matrix() else: # both QC and ndarray type U = unitary # note - the unitary here is not just a single qubit unitary if isinstance(U, np.ndarray): self.dims = U.shape[0] else: self.dims = 2 ** (U.num_qubits) if isinstance(U, np.ndarray): self.c_unitary_gate = UnitaryGate(data=U).control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) else: self.c_unitary_gate = U.control( num_ctrl_qubits=1, label="CU", ctrl_state="1" ) # handle error if not isinstance(error, int): raise TypeError( "The allowable error should be provided as an int. Interpreted as 10**(-error)" ) if error <= 0: raise ValueError("The error threshold must be finite and greater than 0.") self.error = error # handle max_iters if not isinstance(max_iters, int): raise TypeError("Max iterations must be of integer type") if max_iters <= 0 and max_iters > 1e5: raise ValueError("Max iterations should be atleast 1 and less than 1e5") self.iterations = max_iters self.basis = [] def get_basis_vectors(self, randomize=True): # get the d dimensional basis for the unitary provided if randomize == True: UR = unitary_group.rvs(self.dims) else: UR = np.identity(self.dims) basis = [] for k in UR: basis.append(np.array(k, dtype=complex)) return basis def get_circuits(self, angles, state): """Given an initial state and a set of angles, return the circuits that are generated with those angles""" result = {"cost": -1, "theta": -1} # all theta values are iterated over for the same state phi = Initialize(state) shots = 512 circuits = [] for theta in angles: qc = QuantumCircuit(1 + int(np.log2(self.dims)), 1) # initialize the circuit qc = qc.compose(phi, qubits=list(range(1, int(np.log2(self.dims)) + 1))) # add hadamard qc.h(0) # add unitary which produces a phase kickback on control qubit qc = qc.compose( self.c_unitary_gate, qubits=range(1 + int(np.log2(self.dims))) ) # add the inv rotation qc.p(-2 * np.pi * theta, 0) # add hadamard qc.h(0) # measure qc.measure([0], [0]) # generate all the circuits... circuits.append(qc) return circuits def get_cost(self, angles, counts, shots): """Generate the best cost and theta pair for the particular state""" result = {"cost": -1, "theta": -1} # get the cost for this theta for k, theta in zip(counts, angles): # for all experiments you ran try: C_val = (k["0"]) / shots except: C_val = 0 if C_val > result["cost"]: # means this is a better theta value result["theta"] = theta result["cost"] = C_val return result def get_eigen_pair(self, backend, progress=False, randomize=True): """Finding the eigenstate pair for the unitary""" if not isinstance(progress, bool): raise TypeError("Progress must be a boolean variable") if not isinstance(randomize, bool): raise Exception("Randomize must be a boolean variable") results = dict() # first initialize the state phi self.basis = self.get_basis_vectors(randomize) # choose a random index ind = np.random.choice(self.dims) phi = self.basis[ind] # doing the method 1 of our algorithm # define resolution of angles and precision precision = 1 / 10 ** self.error samples = self.resolution # initialization of range left, right = 0, 1 shots = 512 # generate the angles angles = np.linspace(left, right, samples) # First execution can be done without JobManager also... circs = self.get_circuits(angles, phi) job = execute(circs, backend=backend, shots=shots) counts = job.result().get_counts() result = self.get_cost(angles, counts, shots) # get initial estimates cost = result["cost"] theta_max = result["theta"] best_phi = phi # the range upto which theta extends iin each iteration angle_range = 0.5 # a parameter a = 1 # start algorithm iters = 0 found = True plus = (1 / np.sqrt(2)) * np.array([1, 1]) minus = (1 / np.sqrt(2)) * np.array([1, -1]) # define IBMQManager instance manager = IBMQJobManager() while 1 - cost >= precision: # get angles, note if theta didn't change, then we need to # again generate the same range again right = min(1, theta_max + angle_range / 2) left = max(0, theta_max - angle_range / 2) if progress: print("Right :", right) print("Left :", left) # generate the angles only if the theta has been updated if found == True: angles = np.linspace(left, right, samples) found = False # for this iteration if progress: print("ITERATION NUMBER", iters + 1, "...") # generate a cost dict for each of the iterations # final result lists thetas, costs, states = [], [], [] # circuit list circuits = [] # list to store intermediate states phis = [] # 1. Circuit generation loop for i in range((2 * self.dims)): # everyone is supplied with the same range of theta in one iteration # define z # make a list of the circuits if i < self.dims: z = 1 else: z = 1j # alter and normalise phi curr_phi = best_phi + z * a * (1 - cost) * self.basis[i % self.dims] curr_phi = curr_phi / np.linalg.norm(curr_phi) phis.append(curr_phi) # bundle the circuits together ... circs = self.get_circuits(angles, curr_phi) circuits = circuits + circs # now each iteration would see the same state as the best phi # is updated once at the end of the iteration # also, the cost is also updated only once at the end of the iteration # 2. run the generated circuits if progress: print("Transpiling circuits...") circuits = transpile(circuits=circuits, backend=backend) job_set = manager.run( circuits, backend=backend, name="Job_set" + str(iters), shots=shots ) if progress: print("Transpilation Done!\nJob sent...") job_result = job_set.results() # now get the circuits in chunks of resolution each if progress: print("Job has returned") # 3. Result generation loop for i in range((2 * self.dims)): # get the results of this basis state # it will have resolution number of circuits... counts = [] for j in range(i * self.resolution, (i + 1) * self.resolution): # in this you'll get the counts counts.append(job_result.get_counts(j)) result = self.get_cost(counts, angles, shots) # get the estimates for this basis curr_theta = result["theta"] curr_cost = result["cost"] curr_phi = phis[i] # the result was generated pertaining to this phi if ( curr_cost > cost ): # then only add this cost in the cost and states list thetas.append(float(curr_theta)) costs.append(float(curr_cost)) states.append(curr_phi) found = True if progress: stdout.write("\r") stdout.write("%f %%completed" % (100 * (i + 1) / (2 * self.dims))) stdout.flush() if found == False: # phi was not updated , change a a = a / 2 if progress: print("\nNo change, updating a...") else: # if found is actually true, then only update # O(n) , would update this though index = np.argmax(costs) # update the parameters of the model cost = costs[index] theta_max = thetas[index] best_phi = states[index] if progress: print("Best Phi is :", best_phi) print("Theta estimate :", theta_max) print("Current cost :", cost) angle_range /= 2 # updated phi and thus theta too -> refine theta range # update the iterations iters += 1 if progress: print("\nCOST :", cost) print("THETA :", theta_max) if iters >= self.iterations: print( "Maximum iterations reached for the estimation.\nTerminating algorithm..." ) break # add cost, eigenvector and theta to the dict results["cost"] = cost results["theta"] = theta_max results["state"] = best_phi return results
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Tests AQC plugin. """ import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import SLSQP from qiskit.converters import dag_to_circuit, circuit_to_dag from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.transpiler import PassManager from qiskit.transpiler.passes import UnitarySynthesis from qiskit.transpiler.synthesis.aqc.aqc_plugin import AQCSynthesisPlugin class TestAQCSynthesisPlugin(QiskitTestCase): """Basic tests of the AQC synthesis plugin.""" def setUp(self): super().setUp() self._qc = QuantumCircuit(3) self._qc.mcx( [ 0, 1, ], 2, ) self._target_unitary = Operator(self._qc).data self._seed_config = {"seed": 12345} def test_aqc_plugin(self): """Basic test of the plugin.""" plugin = AQCSynthesisPlugin() dag = plugin.run(self._target_unitary, config=self._seed_config) approx_circuit = dag_to_circuit(dag) approx_unitary = Operator(approx_circuit).data np.testing.assert_array_almost_equal(self._target_unitary, approx_unitary, 3) def test_plugin_setup(self): """Tests the plugin via unitary synthesis pass""" transpiler_pass = UnitarySynthesis( basis_gates=["rx", "ry", "rz", "cx"], method="aqc", plugin_config=self._seed_config ) dag = circuit_to_dag(self._qc) dag = transpiler_pass.run(dag) approx_circuit = dag_to_circuit(dag) approx_unitary = Operator(approx_circuit).data np.testing.assert_array_almost_equal(self._target_unitary, approx_unitary, 3) def test_plugin_configuration(self): """Tests plugin with a custom configuration.""" config = { "network_layout": "sequ", "connectivity_type": "full", "depth": 0, "seed": 12345, "optimizer": SLSQP(), } transpiler_pass = UnitarySynthesis( basis_gates=["rx", "ry", "rz", "cx"], method="aqc", plugin_config=config ) dag = circuit_to_dag(self._qc) dag = transpiler_pass.run(dag) approx_circuit = dag_to_circuit(dag) approx_unitary = Operator(approx_circuit).data np.testing.assert_array_almost_equal(self._target_unitary, approx_unitary, 3) def test_with_pass_manager(self): """Tests the plugin via pass manager""" qc = QuantumCircuit(3) qc.unitary(np.eye(8), [0, 1, 2]) aqc = PassManager( [ UnitarySynthesis( basis_gates=["u", "cx"], method="aqc", plugin_config=self._seed_config ) ] ).run(qc) approx_unitary = Operator(aqc).data np.testing.assert_array_almost_equal(np.eye(8), approx_unitary, 3)
https://github.com/JouziP/MQITE
JouziP
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 5 17:10:42 2022 @author: pejmanjouzdani """ import numpy as np import pandas as pd from BasicFunctions.functions import getState def getStateVectorValuesOfAmpl( j_list, circ_uhu, significant_figures, machine_precision): #################### Benchmark circ_state = getState(circ_uhu, machine_precision) ### df_ampl_bm = pd.DataFrame(circ_state[j_list, :].round(significant_figures).T.tolist()[0]) df_ampl_bm.columns=['|c_j|'] df_ampl_bm.index = j_list #### not normalizing ! df_ampl_bm['|c_j|'] = df_ampl_bm['|c_j|'].apply(lambda x: np.sqrt(x*x.conjugate()).real) return df_ampl_bm if __name__=='__main__': from qiskit import QuantumCircuit from BasicFunctions.getQCirc import getQCirc from BasicFunctions.getRandomQ import getRandomQ from BasicFunctions.getRandomU import getRandomU from BasicFunctions.getUQUCirc import getUQUCirc seed = 1211 np.random.seed(seed) ################################################################ ################################################################ nspins = 10 num_layers =4 num_itr =1 machine_precision = 10 significant_figures = 3 eta = 100 shots = 10**(2*significant_figures) Q = getRandomQ(nspins) inputs={} inputs['nspins']=nspins inputs['num_layers']=num_layers inputs['num_itr']=num_itr inputs['machine_precision']=machine_precision inputs['significant_figures']=significant_figures inputs['eta']=eta inputs['shots']=shots inputs['Q-list']=Q circ_U = getRandomU(nspins, num_layers) circ_Q = getQCirc(circ_U, Q) circ_UQU = getUQUCirc(circ_U, circ_Q) print(pd.DataFrame([inputs]).T ) from Amplitude.Amplitude import Amplitude df_count = Amplitude.getIndexsFromExecute(circ_UQU, shots) df_ampl = Amplitude.getAmplitudes(df_count, eta) j_list = df_ampl.index.tolist() state_vec = getStateVectorValuesOfAmpl( j_list, circ_UQU, significant_figures, machine_precision) df_qc_vs_bm = pd.concat((df_ampl, state_vec), axis=1) df_qc_vs_bm.columns = ['QC', 'StVec'] df_qc_vs_bm['diff'] = df_qc_vs_bm['QC'] - df_qc_vs_bm['StVec'] print(df_qc_vs_bm.round(significant_figures)) print('sum diff^2 rounded to significant figures: ' , np.round( np.sqrt(sum(df_qc_vs_bm.round(significant_figures)['diff'].apply(lambda x: x**2))), significant_figures))
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Multiple-Control Toffoli Gate. """ import logging from math import pi, ceil from qiskit import QuantumCircuit, QuantumRegister from qiskit.aqua import AquaError from qiskit.aqua.utils.circuit_utils import is_qubit logger = logging.getLogger(__name__) def _ccx_v_chain(qc, control_qubits, target_qubit, ancillary_qubits, dirty_ancilla=False): """ Create new MCT circuit by chaining ccx gates into a V shape. The dirty_ancilla mode is from https://arxiv.org/abs/quant-ph/9503016 Lemma 7.2 """ if len(ancillary_qubits) < len(control_qubits) - 2: raise AquaError('Insufficient number of ancillary qubits.') if dirty_ancilla: anci_idx = len(control_qubits) - 3 qc.ccx(control_qubits[len(control_qubits) - 1], ancillary_qubits[anci_idx], target_qubit) for idx in reversed(range(2, len(control_qubits) - 1)): qc.ccx(control_qubits[idx], ancillary_qubits[anci_idx - 1], ancillary_qubits[anci_idx]) anci_idx -= 1 anci_idx = 0 qc.ccx(control_qubits[0], control_qubits[1], ancillary_qubits[anci_idx]) for idx in range(2, len(control_qubits) - 1): qc.ccx(control_qubits[idx], ancillary_qubits[anci_idx], ancillary_qubits[anci_idx + 1]) anci_idx += 1 qc.ccx(control_qubits[len(control_qubits) - 1], ancillary_qubits[anci_idx], target_qubit) for idx in reversed(range(2, len(control_qubits) - 1)): qc.ccx(control_qubits[idx], ancillary_qubits[anci_idx - 1], ancillary_qubits[anci_idx]) anci_idx -= 1 qc.ccx(control_qubits[0], control_qubits[1], ancillary_qubits[anci_idx]) if dirty_ancilla: anci_idx = 0 for idx in range(2, len(control_qubits) - 1): qc.ccx(control_qubits[idx], ancillary_qubits[anci_idx], ancillary_qubits[anci_idx + 1]) anci_idx += 1 def _cccx(qc, qrs, angle=pi / 4): """ a 3-qubit controlled-NOT. An implementation based on Page 17 of Barenco et al. Parameters: qrs: list of quantum registers. The last qubit is the target, the rest are controls angle: default pi/4 when x is not gate set to pi/8 for square root of not """ assert len(qrs) == 4, "There must be exactly 4 qubits of quantum registers for cccx" # controlled-V qc.h(qrs[3]) qc.cu1(-angle, qrs[0], qrs[3]) qc.h(qrs[3]) # ------------ qc.cx(qrs[0], qrs[1]) # controlled-Vdag qc.h(qrs[3]) qc.cu1(angle, qrs[1], qrs[3]) qc.h(qrs[3]) # --------------- qc.cx(qrs[0], qrs[1]) # controlled-V qc.h(qrs[3]) qc.cu1(-angle, qrs[1], qrs[3]) qc.h(qrs[3]) # ------------ qc.cx(qrs[1], qrs[2]) # controlled-Vdag qc.h(qrs[3]) qc.cu1(angle, qrs[2], qrs[3]) qc.h(qrs[3]) # --------------- qc.cx(qrs[0], qrs[2]) # controlled-V qc.h(qrs[3]) qc.cu1(-angle, qrs[2], qrs[3]) qc.h(qrs[3]) # ------------ qc.cx(qrs[1], qrs[2]) # controlled-Vdag qc.h(qrs[3]) qc.cu1(angle, qrs[2], qrs[3]) qc.h(qrs[3]) # --------------- qc.cx(qrs[0], qrs[2]) # controlled-V qc.h(qrs[3]) qc.cu1(-angle, qrs[2], qrs[3]) qc.h(qrs[3]) def _ccccx(qc, qrs): """ a 4-qubit controlled-NOT. An implementation based on Page 21 (Lemma 7.5) of Barenco et al. Parameters: qrs: list of quantum registers. The last qubit is the target, the rest are controls """ assert len(qrs) == 5, "There must be exactly 5 qubits for ccccx" # controlled-V qc.h(qrs[4]) qc.cu1(-pi / 2, qrs[3], qrs[4]) qc.h(qrs[4]) # ------------ _cccx(qc, qrs[:4]) # controlled-Vdag qc.h(qrs[4]) qc.cu1(pi / 2, qrs[3], qrs[4]) qc.h(qrs[4]) # ------------ _cccx(qc, qrs[:4]) _cccx(qc, [qrs[0], qrs[1], qrs[2], qrs[4]], angle=pi / 8) def _multicx(qc, qrs, qancilla=None): """ construct a circuit for multi-qubit controlled not Parameters: qc: quantum circuit qrs: list of quantum registers of at least length 1 qancilla: a quantum register. can be None if len(qrs) <= 5 Returns: qc: a circuit appended with multi-qubit cnot """ if len(qrs) <= 0: pass elif len(qrs) == 1: qc.x(qrs[0]) elif len(qrs) == 2: qc.cx(qrs[0], qrs[1]) elif len(qrs) == 3: qc.ccx(qrs[0], qrs[1], qrs[2]) else: _multicx_recursion(qc, qrs, qancilla) def _multicx_recursion(qc, qrs, qancilla=None): if len(qrs) == 4: _cccx(qc, qrs) elif len(qrs) == 5: _ccccx(qc, qrs) else: # qrs[0], qrs[n-2] is the controls, qrs[n-1] is the target, and qancilla as working qubit assert qancilla is not None, "There must be an ancilla qubit not necesseraly initialized to zero" n = len(qrs) m1 = ceil(n / 2) _multicx_recursion(qc, [*qrs[:m1], qancilla], qrs[m1]) _multicx_recursion(qc, [*qrs[m1:n - 1], qancilla, qrs[n - 1]], qrs[m1 - 1]) _multicx_recursion(qc, [*qrs[:m1], qancilla], qrs[m1]) _multicx_recursion(qc, [*qrs[m1:n - 1], qancilla, qrs[n - 1]], qrs[m1 - 1]) def _multicx_noancilla(qc, qrs): """ construct a circuit for multi-qubit controlled not without ancillary qubits Parameters: qc: quantum circuit qrs: list of quantum registers of at least length 1 Returns: qc: a circuit appended with multi-qubit cnot """ if len(qrs) <= 0: pass elif len(qrs) == 1: qc.x(qrs[0]) elif len(qrs) == 2: qc.cx(qrs[0], qrs[1]) else: # qrs[0], qrs[n-2] is the controls, qrs[n-1] is the target ctls = qrs[:-1] tgt = qrs[-1] qc.h(tgt) qc.mcu1(pi, ctls, tgt) qc.h(tgt) def mct(self, q_controls, q_target, q_ancilla, mode='basic'): """ Apply Multiple-Control Toffoli operation Args: q_controls: The list of control qubits q_target: The target qubit q_ancilla: The list of ancillary qubits mode (string): The implementation mode to use """ if len(q_controls) == 1: # cx self.cx(q_controls[0], q_target) elif len(q_controls) == 2: # ccx self.ccx(q_controls[0], q_controls[1], q_target) else: # check controls if isinstance(q_controls, QuantumRegister): control_qubits = [qb for qb in q_controls] elif isinstance(q_controls, list): control_qubits = q_controls else: raise AquaError('MCT needs a list of qubits or a quantum register for controls.') # check target if is_qubit(q_target): target_qubit = q_target else: raise AquaError('MCT needs a single qubit as target.') # check ancilla if q_ancilla is None: ancillary_qubits = [] elif isinstance(q_ancilla, QuantumRegister): ancillary_qubits = [qb for qb in q_ancilla] elif isinstance(q_ancilla, list): ancillary_qubits = q_ancilla else: raise AquaError('MCT needs None or a list of qubits or a quantum register for ancilla.') all_qubits = control_qubits + [target_qubit] + ancillary_qubits self._check_qargs(all_qubits) self._check_dups(all_qubits) if mode == 'basic': _ccx_v_chain(self, control_qubits, target_qubit, ancillary_qubits, dirty_ancilla=False) elif mode == 'basic-dirty-ancilla': _ccx_v_chain(self, control_qubits, target_qubit, ancillary_qubits, dirty_ancilla=True) elif mode == 'advanced': _multicx(self, [*control_qubits, target_qubit], ancillary_qubits[0] if ancillary_qubits else None) elif mode == 'noancilla': _multicx_noancilla(self, [*control_qubits, target_qubit]) else: raise AquaError('Unrecognized mode for building MCT circuit: {}.'.format(mode)) def cnx(self, *args, **kwargs): logger.warning("The gate name 'cnx' will be deprecated. Please use 'mct' (Multiple-Control Toffoli) instead.") return mct(self, *args, **kwargs) QuantumCircuit.mct = mct QuantumCircuit.cnx = cnx
https://github.com/JavaFXpert/quantum-pong
JavaFXpert
#!/usr/bin/env python # # 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 pygame from qiskit import BasicAer, execute from utils.colors import * from utils.fonts import ARIAL_30 from utils.states import comp_basis_states class StatevectorGrid1(pygame.sprite.Sprite): """Displays a statevector grid""" def __init__(self, circuit): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.basis_states = comp_basis_states(circuit.width()) self.set_circuit(circuit) # def update(self): # # Nothing yet # a = 1 def set_circuit(self, circuit): backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circuit, backend_sv_sim) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circuit, decimals=3) self.image = pygame.Surface([(circuit.width() + 1) * 50, 100 + len(quantum_state) * 50]) self.image.convert() self.image.fill(BLACK) self.rect = self.image.get_rect() block_size = 50 x_offset = 50 y_offset = 50 for y in range(len(quantum_state)): #text_surface = ARIAL_30.render(self.basis_states[y], False, (0, 0, 0)) #self.image.blit(text_surface,(x_offset, (y + 1) * block_size + y_offset)) rect = pygame.Rect(80, y * block_size, 10, block_size) if abs(quantum_state[y]) > 0: pygame.draw.rect(self.image, WHITE, rect, 0)
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/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
Keerthiraj-Nagaraj
from IPython.display import Image, display Image("ryoko.png", width="70") from IPython.display import Image, display Image('4lightsout_ex.png') from qiskit import * from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute provider = IBMQ.load_account() address = QuantumRegister(2) data = QuantumRegister(3) c = ClassicalRegister(5) qc = QuantumCircuit(address,data,c) # address preparation qc.h([address[0],address[1]]) qc.barrier() # address 0 -> data = 1 qc.x([address[0],address[1]]) qc.ccx(address[0],address[1],data[2]) qc.x([address[0],address[1]]) qc.barrier() # address 1 -> data = 2 qc.x(address[0]) qc.ccx(address[0],address[1],data[1]) qc.x(address[0]) qc.barrier() # address 2 -> data = 5 qc.x(address[1]) qc.ccx(address[0],address[1],data[2]) qc.ccx(address[0],address[1],data[0]) qc.x(address[1]) qc.barrier() # address 3 -> data = 7 qc.ccx(address[0],address[1],data[2]) qc.ccx(address[0],address[1],data[1]) qc.ccx(address[0],address[1],data[0]) qc.barrier() #Check the qRAM status qc.measure(address[0:2], c[0:2]) qc.measure(data[0:3], c[2:5]) # Reverse the output string. qc = qc.reverse_bits() #backend = provider.get_backend('ibmq_qasm_simulator') backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend=backend, shots=8000, seed_simulator=12345, backend_options={"fusion_enable":True}) #job = execute(qc, backend=backend, shots=8192) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') Image('circuit_ex.png') Image('gatesynthesis_ex.png') Image('4lightsout_pr.png') lightsout4=[[1, 1, 1, 0, 0, 0, 1, 0, 0],[1, 0, 1, 0, 0, 0, 1, 1, 0],[1, 0, 1, 1, 1, 1, 0, 0, 1],[1, 0, 0, 0, 0, 0, 1, 0, 0]] import numpy as np # import qiskit libraries from qiskit import IBMQ, Aer,QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.tools.jupyter import * provider = IBMQ.load_account() #import functions to plot from qiskit.visualization import plot_histogram def week2b_ans_func(lightout4): ##### Build your cirucuit here def qRAM(qc, add, board, lightout4): # Board 1 qc.x(add[0]) qc.x(add[1]) for i, curr_light in enumerate(lightout4[0]): if curr_light == 1: qc.ccx(add[0], add[1], board[i]) #qc.ch(q[0], q[3]) #qc.cz(q[2], q[3]) #qc.ch(q[0], q[3]) qc.x(add[0]) qc.x(add[1]) qc.barrier() # Board 2 qc.x(add[0]) for i, curr_light in enumerate(lightout4[1]): if curr_light == 1: qc.ccx(add[0], add[1], board[i]) qc.x(add[0]) qc.barrier() # Board 3 qc.x(add[1]) for i, curr_light in enumerate(lightout4[2]): if curr_light == 1: qc.ccx(add[0], add[1], board[i]) qc.x(add[1]) qc.barrier() # Board 4 for i, curr_light in enumerate(lightout4[3]): if curr_light == 1: qc.ccx(add[0], add[1], board[i]) qc.barrier() def diffuser(nqubits): qc_diff = QuantumCircuit(nqubits) for qubit in range(nqubits): qc_diff.h(qubit) for qubit in range(nqubits): qc_diff.x(qubit) qc_diff.h(nqubits-1) qc_diff.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc_diff.h(nqubits-1) for qubit in range(nqubits): qc_diff.x(qubit) for qubit in range(nqubits): qc_diff.h(qubit) U_f0 = qc_diff.to_gate() U_f0.name = "V" return U_f0 def lights_oracle(sol, board, anc, orc_out_2a): #board_oracle = QuantumRegister(n, 'board') #sol = QuantumRegister(n, 'solution') #orc_out_2a = QuantumRegister(1, 'oracle_out_2a') #this has to be phase flipped qc_1 = QuantumCircuit(sol, board, anc, orc_out_2a) flip_matrix = [[1,1,0,1,0,0,0,0,0], [1,1,1,0,1,0,0,0,0], [0,1,1,0,0,1,0,0,0], [1,0,0,1,1,0,1,0,0], [0,1,0,1,1,1,0,1,0], [0,0,1,0,1,1,0,0,1], [0,0,0,1,0,0,1,1,0], [0,0,0,0,1,0,1,1,1], [0,0,0,0,0,1,0,1,1]] qc_1.barrier() for sol_bit in range(len(flip_matrix)): for board_bit in range(len(flip_matrix[sol_bit])): if flip_matrix[sol_bit][board_bit] == 1: qc_1.cx(sol[sol_bit], board[board_bit]) qc_1.barrier() for i in range(len(flip_matrix)): qc_1.x(board[i]) qc_1.barrier() qc_1.ccx(board[0], board[1], anc[0]) qc_1.ccx(board[2], board[3], anc[1]) qc_1.ccx(anc[0], anc[1], anc[2]) qc_1.ccx(board[4], board[5], anc[3]) qc_1.ccx(board[6], board[7], anc[4]) qc_1.ccx(anc[3], anc[4], anc[5]) qc_1.mct([board[8], anc[2], anc[5]], orc_out_2a, mode = 'noancilla') qc_1.ccx(anc[3], anc[4], anc[5]) qc_1.ccx(board[6], board[7], anc[4]) qc_1.ccx(board[4], board[5], anc[3]) qc_1.ccx(anc[0], anc[1], anc[2]) qc_1.ccx(board[2], board[3], anc[1]) qc_1.ccx(board[0], board[1], anc[0]) #qc_1.mct([board[0], board[1],board[2],board[3],board[4],board[5],board[6],board[7],board[8]], # orc_out_2a, #[anc[0], anc[1],anc[2],anc[3],anc[4],anc[5],anc[6]], # mode='noancilla') qc_1.barrier() for i in range(len(flip_matrix)): qc_1.x(board[i]) qc_1.barrier() for sol_bit in range(len(flip_matrix)): for board_bit in range(len(flip_matrix[sol_bit])): if flip_matrix[sol_bit][board_bit] == 1: qc_1.cx(sol[sol_bit], board[board_bit]) return qc_1 def new_u2a(qc, sol, board, anc, orc_out_2a): r_2a = 1 flip_matrix = [[1,1,0,1,0,0,0,0,0], [1,1,1,0,1,0,0,0,0], [0,1,1,0,0,1,0,0,0], [1,0,0,1,1,0,1,0,0], [0,1,0,1,1,1,0,1,0], [0,0,1,0,1,1,0,0,1], [0,0,0,1,0,0,1,1,0], [0,0,0,0,1,0,1,1,1], [0,0,0,0,0,1,0,1,1]] n =len(flip_matrix) for i_2a in range(r_2a): qc.extend(lights_oracle(sol, board, anc, orc_out_2a)) qc.barrier() qc.append(diffuser(n), sol) qc.barrier() def new_u2a_dagger(qc, sol, board, anc, orc_out_2a): r_2a = 1 flip_matrix = [[1,1,0,1,0,0,0,0,0], [1,1,1,0,1,0,0,0,0], [0,1,1,0,0,1,0,0,0], [1,0,0,1,1,0,1,0,0], [0,1,0,1,1,1,0,1,0], [0,0,1,0,1,1,0,0,1], [0,0,0,1,0,0,1,1,0], [0,0,0,0,1,0,1,1,1], [0,0,0,0,0,1,0,1,1]] n =len(flip_matrix) for i_2a in range(r_2a): qc.barrier() qc.append(diffuser(n), sol) qc.barrier() orc_org = lights_oracle(sol, board, anc, orc_out_2a) qc.extend(orc_org.inverse()) def bitcounter(qc, sol, anc): for i in range(len(sol)): qc.mct([sol[i], anc[0], anc[1], anc[2]], anc[3], mode = 'noancilla') qc.mct([sol[i], anc[0], anc[1]], anc[2], mode = 'noancilla') qc.ccx(sol[i], anc[0], anc[1]) qc.cx(sol[i], anc[0]) def bitcounter_uncompute(qc, sol, anc): for i in range(len(sol)): qc.cx(sol[i], anc[0]) qc.ccx(sol[i], anc[0], anc[1]) qc.mct([sol[i], anc[0], anc[1]], anc[2], mode = 'noancilla') qc.mct([sol[i], anc[0], anc[1], anc[2]], anc[3], mode = 'noancilla') def oracle_2b(qc, add, board, sol, anc, orc_out_2a, orc_out_2b, lightout4): #apply QRAM qRAM(qc, add, board, lightout4) #apply U_2A new_u2a(qc, sol, board, anc, orc_out_2a) #counter #qc.append(WeightedAdder(9), sol+anc) bitcounter(qc, sol, anc) #verifying that the count is less than 3 qc.x(anc[2]) qc.x(anc[3]) qc.ccx(anc[2], anc[3], orc_out_2b) qc.x(anc[2]) qc.x(anc[3]) bitcounter_uncompute(qc, sol, anc) #apply U_2a_dagger new_u2a_dagger(qc, sol, board, anc, orc_out_2a) #apply qRAM dagger - same as qRAM qRAM(qc, add, board, lightout4) # start building the circuit n = len(lightout4[0]) add = QuantumRegister(2, 'address') board = QuantumRegister(n, 'board') sol = QuantumRegister(n, 'solution') anc = QuantumRegister(6, 'anc') orc_out_2a = QuantumRegister(1, 'oracle_out_2a') orc_out_2b = QuantumRegister(1, 'oracle_out_2b') c_out = ClassicalRegister(2, 'classical_bits') qc = QuantumCircuit(add, board, sol, orc_out_2a, anc, orc_out_2b, c_out) qc.h(add) qc.h(sol) qc.x(orc_out_2a) qc.h(orc_out_2a) qc.x(orc_out_2b) qc.h(orc_out_2b) qc.barrier() r_2b = 2 for i_2b in range(r_2b): oracle_2b(qc, add, board, sol, anc, orc_out_2a, orc_out_2b, lightout4) qc.barrier() qc.append(diffuser(2), add) qc.barrier() qc.measure(add, c_out) qc = qc.reverse_bits() #### In addition, please make sure your function can solve the problem with different inputs (lightout4). We will cross validate with different inputs. return qc # Submission code from qc_grader import prepare_ex2b, grade_ex2b, submit_ex2b # Execute your circuit with following prepare_ex2b() function. # The prepare_ex2b() function works like the execute() function with only QuantumCircuit as an argument. job = prepare_ex2b(week2b_ans_func) result = job.result() count = result.get_counts() original_problem_set_counts = count[0] original_problem_set_counts # The bit string with the highest number of observations is treated as the solution. # Check your answer by executing following code. # The quantum cost of the QuantumCircuit is obtained as the score. The quantum cost is related to rank only in the third week. grade_ex2b(job) # Submit your results by executing following code. You can submit as many times as you like during the period. submit_ex2b(job)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test QASM3 exporter.""" # We can't really help how long the lines output by the exporter are in some cases. # pylint: disable=line-too-long from io import StringIO from math import pi import re import unittest from ddt import ddt, data from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile from qiskit.circuit import Parameter, Qubit, Clbit, Instruction, Gate, Delay, Barrier from qiskit.circuit.classical import expr from qiskit.circuit.controlflow import CASE_DEFAULT from qiskit.test import QiskitTestCase from qiskit.qasm3 import Exporter, dumps, dump, QASM3ExporterError, ExperimentalFeatures from qiskit.qasm3.exporter import QASM3Builder from qiskit.qasm3.printer import BasicPrinter # Tests marked with this decorator should be restored after gate definition with parameters is fixed # properly, and the dummy tests after them should be deleted. See gh-7335. requires_fixed_parameterisation = unittest.expectedFailure class TestQASM3Functions(QiskitTestCase): """QASM3 module - high level functions""" def setUp(self): self.circuit = QuantumCircuit(2) self.circuit.u(2 * pi, 3 * pi, -5 * pi, 0) self.expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit[2] q;", "U(2*pi, 3*pi, -5*pi) q[0];", "", ] ) super().setUp() def test_dumps(self): """Test dumps.""" result = dumps(self.circuit) self.assertEqual(result, self.expected_qasm) def test_dump(self): """Test dump into an IO stream.""" io = StringIO() dump(self.circuit, io) result = io.getvalue() self.assertEqual(result, self.expected_qasm) @ddt class TestCircuitQASM3(QiskitTestCase): """QASM3 exporter.""" maxDiff = 1_000_000 @classmethod def setUpClass(cls): # These regexes are not perfect by any means, but sufficient for simple tests on controlled # input circuits. They can allow false negatives (in which case, update the regex), but to # be useful for the tests must _never_ have false positive matches. We use an explicit # space (`\s`) or semicolon rather than the end-of-word `\b` because we want to ensure that # the exporter isn't putting out invalid characters as part of the identifiers. cls.register_regex = re.compile( r"^\s*(let|(qu)?bit(\[\d+\])?)\s+(?P<name>\w+)[\s;]", re.U | re.M ) scalar_type_names = { "angle", "duration", "float", "int", "stretch", "uint", } cls.scalar_parameter_regex = re.compile( r"^\s*((input|output|const)\s+)?" # Modifier rf"({'|'.join(scalar_type_names)})\s*(\[[^\]]+\])?\s+" # Type name and designator r"(?P<name>\w+)[\s;]", # Parameter name re.U | re.M, ) super().setUpClass() def test_regs_conds_qasm(self): """Test with registers and conditionals.""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr1, qr2, cr) qc.measure(qr1[0], cr[0]) qc.measure(qr2[0], cr[1]) qc.measure(qr2[1], cr[2]) qc.x(qr2[1]).c_if(cr, 0) qc.y(qr1[0]).c_if(cr, 1) qc.z(qr1[0]).c_if(cr, 2) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[3] cr;", "qubit[1] qr1;", "qubit[2] qr2;", "cr[0] = measure qr1[0];", "cr[1] = measure qr2[0];", "cr[2] = measure qr2[1];", "if (cr == 0) {", " x qr2[1];", "}", "if (cr == 1) {", " y qr1[0];", "}", "if (cr == 2) {", " z qr1[0];", "}", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_registers_as_aliases(self): """Test that different types of alias creation and concatenation work.""" qubits = [Qubit() for _ in [None] * 10] first_four = QuantumRegister(name="first_four", bits=qubits[:4]) last_five = QuantumRegister(name="last_five", bits=qubits[5:]) alternate = QuantumRegister(name="alternate", bits=qubits[::2]) sporadic = QuantumRegister(name="sporadic", bits=[qubits[4], qubits[2], qubits[9]]) qc = QuantumCircuit(qubits, first_four, last_five, alternate, sporadic) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit _qubit0;", "qubit _qubit1;", "qubit _qubit2;", "qubit _qubit3;", "qubit _qubit4;", "qubit _qubit5;", "qubit _qubit6;", "qubit _qubit7;", "qubit _qubit8;", "qubit _qubit9;", "let first_four = {_qubit0, _qubit1, _qubit2, _qubit3};", "let last_five = {_qubit5, _qubit6, _qubit7, _qubit8, _qubit9};", "let alternate = {first_four[0], first_four[2], _qubit4, last_five[1], last_five[3]};", "let sporadic = {alternate[2], alternate[1], last_five[4]};", "", ] ) self.assertEqual(Exporter(allow_aliasing=True).dumps(qc), expected_qasm) def test_composite_circuit(self): """Test with a composite circuit instruction and barriers""" composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_gate() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate composite_circ _gate_q_0, _gate_q_1 {", " h _gate_q_0;", " x _gate_q_1;", " cx _gate_q_0, _gate_q_1;", "}", "bit[2] cr;", "qubit[2] qr;", "h qr[0];", "cx qr[0], qr[1];", "barrier qr[0], qr[1];", "composite_circ qr[0], qr[1];", "cr[0] = measure qr[0];", "cr[1] = measure qr[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_custom_gate(self): """Test custom gates (via to_gate).""" composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_gate() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate composite_circ _gate_q_0, _gate_q_1 {", " h _gate_q_0;", " x _gate_q_1;", " cx _gate_q_0, _gate_q_1;", "}", "bit[2] cr;", "qubit[2] qr;", "h qr[0];", "cx qr[0], qr[1];", "barrier qr[0], qr[1];", "composite_circ qr[0], qr[1];", "cr[0] = measure qr[0];", "cr[1] = measure qr[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_same_composite_circuits(self): """Test when a composite circuit is added to the circuit multiple times.""" composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_gate() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate composite_circ _gate_q_0, _gate_q_1 {", " h _gate_q_0;", " x _gate_q_1;", " cx _gate_q_0, _gate_q_1;", "}", "bit[2] cr;", "qubit[2] qr;", "h qr[0];", "cx qr[0], qr[1];", "barrier qr[0], qr[1];", "composite_circ qr[0], qr[1];", "composite_circ qr[0], qr[1];", "cr[0] = measure qr[0];", "cr[1] = measure qr[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_composite_circuits_with_same_name(self): """Test when multiple composite circuit instructions same name and different implementation.""" my_gate = QuantumCircuit(1, name="my_gate") my_gate.h(0) my_gate_inst1 = my_gate.to_gate() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst2 = my_gate.to_gate() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst3 = my_gate.to_gate() qr = QuantumRegister(1, name="qr") circuit = QuantumCircuit(qr, name="circuit") circuit.append(my_gate_inst1, [qr[0]]) circuit.append(my_gate_inst2, [qr[0]]) my_gate_inst2_id = id(circuit.data[-1].operation) circuit.append(my_gate_inst3, [qr[0]]) my_gate_inst3_id = id(circuit.data[-1].operation) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate my_gate _gate_q_0 {", " h _gate_q_0;", "}", f"gate my_gate_{my_gate_inst2_id} _gate_q_0 {{", " x _gate_q_0;", "}", f"gate my_gate_{my_gate_inst3_id} _gate_q_0 {{", " x _gate_q_0;", "}", "qubit[1] qr;", "my_gate qr[0];", f"my_gate_{my_gate_inst2_id} qr[0];", f"my_gate_{my_gate_inst3_id} qr[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_pi_disable_constants_false(self): """Test pi constant (disable_constants=False)""" circuit = QuantumCircuit(2) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit[2] q;", "U(2*pi, 3*pi, -5*pi) q[0];", "", ] ) self.assertEqual(Exporter(disable_constants=False).dumps(circuit), expected_qasm) def test_pi_disable_constants_true(self): """Test pi constant (disable_constants=True)""" circuit = QuantumCircuit(2) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit[2] q;", "U(6.283185307179586, 9.42477796076938, -15.707963267948966) q[0];", "", ] ) self.assertEqual(Exporter(disable_constants=True).dumps(circuit), expected_qasm) def test_custom_gate_with_unbound_parameter(self): """Test custom gate with unbound parameter.""" parameter_a = Parameter("a") custom = QuantumCircuit(1, name="custom") custom.rx(parameter_a, 0) circuit = QuantumCircuit(1) circuit.append(custom.to_gate(), [0]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "input float[64] a;", "gate custom(a) _gate_q_0 {", " rx(a) _gate_q_0;", "}", "qubit[1] q;", "custom(a) q[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_custom_gate_with_bound_parameter(self): """Test custom gate with bound parameter.""" parameter_a = Parameter("a") custom = QuantumCircuit(1) custom.rx(parameter_a, 0) custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate() custom_gate.name = "custom" circuit = QuantumCircuit(1) circuit.append(custom_gate, [0]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate custom _gate_q_0 {", " rx(0.5) _gate_q_0;", "}", "qubit[1] q;", "custom q[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) @requires_fixed_parameterisation def test_custom_gate_with_params_bound_main_call(self): """Custom gate with unbound parameters that are bound in the main circuit""" parameter0 = Parameter("p0") parameter1 = Parameter("p1") custom = QuantumCircuit(2, name="custom") custom.rz(parameter0, 0) custom.rz(parameter1 / 2, 1) qr_all_qubits = QuantumRegister(3, "q") qr_r = QuantumRegister(3, "r") circuit = QuantumCircuit(qr_all_qubits, qr_r) circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]]) circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate custom(_gate_p_0, _gate_p_0) _gate_q_0, _gate_q_1 {", " rz(pi) _gate_q_0;", " rz(pi/4) _gate_q_1;", "}", "qubit[3] q;", "qubit[3] r;", "custom(pi, pi/2) q[0], r[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_reused_custom_parameter(self): """Test reused custom gate with parameter.""" parameter_a = Parameter("a") custom = QuantumCircuit(1) custom.rx(parameter_a, 0) circuit = QuantumCircuit(1) circuit.append(custom.bind_parameters({parameter_a: 0.5}).to_gate(), [0]) circuit.append(custom.bind_parameters({parameter_a: 1}).to_gate(), [0]) circuit_name_0 = circuit.data[0].operation.definition.name circuit_name_1 = circuit.data[1].operation.definition.name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"gate {circuit_name_0} _gate_q_0 {{", " rx(0.5) _gate_q_0;", "}", f"gate {circuit_name_1} _gate_q_0 {{", " rx(1.0) _gate_q_0;", "}", "qubit[1] q;", f"{circuit_name_0} q[0];", f"{circuit_name_1} q[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_unbound_circuit(self): """Test with unbound parameters (turning them into inputs).""" qc = QuantumCircuit(1) theta = Parameter("θ") qc.rz(theta, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "input float[64] θ;", "qubit[1] q;", "rz(θ) q[0];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_unknown_parameterized_gate_called_multiple_times(self): """Test that a parameterised gate is called correctly if the first instance of it is generic.""" x, y = Parameter("x"), Parameter("y") qc = QuantumCircuit(2) qc.rzx(x, 0, 1) qc.rzx(y, 0, 1) qc.rzx(0.5, 0, 1) expected_qasm = "\n".join( [ "OPENQASM 3;", "input float[64] x;", "input float[64] y;", "gate rzx(x) _gate_q_0, _gate_q_1 {", " h _gate_q_1;", " cx _gate_q_0, _gate_q_1;", " rz(x) _gate_q_1;", " cx _gate_q_0, _gate_q_1;", " h _gate_q_1;", "}", "qubit[2] q;", "rzx(x) q[0], q[1];", "rzx(y) q[0], q[1];", "rzx(0.5) q[0], q[1];", "", ] ) # Set the includes and basis gates to ensure that this gate is unknown. exporter = Exporter(includes=[], basis_gates=("rz", "h", "cx")) self.assertEqual(exporter.dumps(qc), expected_qasm) def test_gate_qasm_with_ctrl_state(self): """Test with open controlled gate that has ctrl_state""" qc = QuantumCircuit(2) qc.ch(0, 1, ctrl_state=0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate ch_o0 _gate_q_0, _gate_q_1 {", " x _gate_q_0;", " ch _gate_q_0, _gate_q_1;", " x _gate_q_0;", "}", "qubit[2] q;", "ch_o0 q[0], q[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_custom_gate_collision_with_stdlib(self): """Test a custom gate with name collision with the standard library.""" custom = QuantumCircuit(2, name="cx") custom.cx(0, 1) custom_gate = custom.to_gate() qc = QuantumCircuit(2) qc.append(custom_gate, [0, 1]) custom_gate_id = id(qc.data[-1].operation) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"gate cx_{custom_gate_id} _gate_q_0, _gate_q_1 {{", " cx _gate_q_0, _gate_q_1;", "}", "qubit[2] q;", f"cx_{custom_gate_id} q[0], q[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) @requires_fixed_parameterisation def test_no_include(self): """Test explicit gate declaration (no include)""" q = QuantumRegister(2, "q") circuit = QuantumCircuit(q) circuit.rz(pi / 2, 0) circuit.sx(0) circuit.cx(0, 1) expected_qasm = "\n".join( [ "OPENQASM 3;", "gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {", " U(0, 0, pi/2) _gate_q_0;", "}", "gate u1(_gate_p_0) _gate_q_0 {", " u3(0, 0, pi/2) _gate_q_0;", "}", "gate rz(_gate_p_0) _gate_q_0 {", " u1(pi/2) _gate_q_0;", "}", "gate sdg _gate_q_0 {", " u1(-pi/2) _gate_q_0;", "}", "gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {", " u3(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", " u2(0, pi) _gate_q_0;", "}", "gate sx _gate_q_0 {", " sdg _gate_q_0;", " h _gate_q_0;", " sdg _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", "qubit[2] q;", "rz(pi/2) q[0];", "sx q[0];", "cx q[0], q[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm) @requires_fixed_parameterisation def test_teleportation(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) qc.h(1) qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() qc.x(2).c_if(qc.clbits[1], 1) qc.z(2).c_if(qc.clbits[0], 1) transpiled = transpile(qc, initial_layout=[0, 1, 2]) expected_qasm = "\n".join( [ "OPENQASM 3;", "gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {", " U(pi/2, 0, pi) _gate_q_0;", "}", "gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {", " u3(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", " u2(0, pi) _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", "gate x _gate_q_0 {", " u3(pi, 0, pi) _gate_q_0;", "}", "gate u1(_gate_p_0) _gate_q_0 {", " u3(0, 0, pi) _gate_q_0;", "}", "gate z _gate_q_0 {", " u1(pi) _gate_q_0;", "}", "bit[2] c;", "h $1;", "cx $1, $2;", "barrier $0, $1, $2;", "cx $0, $1;", "h $0;", "barrier $0, $1, $2;", "c[0] = measure $0;", "c[1] = measure $1;", "barrier $0, $1, $2;", "if (c[1]) {", " x $2;", "}", "if (c[0]) {", " z $2;", "}", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm) @requires_fixed_parameterisation def test_basis_gates(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) qc.h(1) qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() qc.x(2).c_if(qc.clbits[1], 1) qc.z(2).c_if(qc.clbits[0], 1) transpiled = transpile(qc, initial_layout=[0, 1, 2]) expected_qasm = "\n".join( [ "OPENQASM 3;", "gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {", " U(pi/2, 0, pi) _gate_q_0;", "}", "gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {", " u3(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", " u2(0, pi) _gate_q_0;", "}", "gate x _gate_q_0 {", " u3(pi, 0, pi) _gate_q_0;", "}", "bit[2] c;", "h $1;", "cx $1, $2;", "barrier $0, $1, $2;", "cx $0, $1;", "h $0;", "barrier $0, $1, $2;", "c[0] = measure $0;", "c[1] = measure $1;", "barrier $0, $1, $2;", "if (c[1]) {", " x $2;", "}", "if (c[0]) {", " z $2;", "}", "", ] ) self.assertEqual( Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(transpiled), expected_qasm, ) def test_opaque_instruction_in_basis_gates(self): """Test that an instruction that is set in the basis gates is output verbatim with no definition.""" qc = QuantumCircuit(1) qc.x(0) qc.append(Gate("my_gate", 1, []), [0], []) basis_gates = ["my_gate", "x"] transpiled = transpile(qc, initial_layout=[0]) expected_qasm = "\n".join( [ "OPENQASM 3;", "x $0;", "my_gate $0;", "", ] ) self.assertEqual( Exporter(includes=[], basis_gates=basis_gates).dumps(transpiled), expected_qasm ) def test_reset_statement(self): """Test that a reset statement gets output into valid QASM 3. This includes tests of reset operations on single qubits and in nested scopes.""" qreg = QuantumRegister(2, "qr") qc = QuantumCircuit(qreg) qc.reset(0) qc.reset([0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", "qubit[2] qr;", "reset qr[0];", "reset qr[0];", "reset qr[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm) def test_delay_statement(self): """Test that delay operations get output into valid QASM 3.""" qreg = QuantumRegister(2, "qr") qc = QuantumCircuit(qreg) qc.delay(100, qreg[0], unit="ms") qc.delay(2, qreg[1], unit="ps") # "ps" is not a valid unit in OQ3, so we need to convert. expected_qasm = "\n".join( [ "OPENQASM 3;", "qubit[2] qr;", "delay[100ms] qr[0];", "delay[2000ns] qr[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm) def test_loose_qubits(self): """Test that qubits that are not in any register can be used without issue.""" bits = [Qubit(), Qubit()] qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(bits, qr, cr) qc.h(0) qc.h(1) qc.h(2) qc.h(3) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit _qubit0;", "qubit _qubit1;", "qubit[2] qr;", "h _qubit0;", "h _qubit1;", "h qr[0];", "h qr[1];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_loose_clbits(self): """Test that clbits that are not in any register can be used without issue.""" qreg = QuantumRegister(1, name="qr") bits = [Clbit() for _ in [None] * 7] cr1 = ClassicalRegister(name="cr1", bits=bits[1:3]) cr2 = ClassicalRegister(name="cr2", bits=bits[4:6]) qc = QuantumCircuit(bits, qreg, cr1, cr2) qc.measure(0, 0) qc.measure(0, 1) qc.measure(0, 2) qc.measure(0, 3) qc.measure(0, 4) qc.measure(0, 5) qc.measure(0, 6) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit _bit0;", "bit _bit3;", "bit _bit6;", "bit[2] cr1;", "bit[2] cr2;", "qubit[1] qr;", "_bit0 = measure qr[0];", "cr1[0] = measure qr[0];", "cr1[1] = measure qr[0];", "_bit3 = measure qr[0];", "cr2[0] = measure qr[0];", "cr2[1] = measure qr[0];", "_bit6 = measure qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_classical_register_aliasing(self): """Test that clbits that are not in any register can be used without issue.""" qreg = QuantumRegister(1, name="qr") bits = [Clbit() for _ in [None] * 7] cr1 = ClassicalRegister(name="cr1", bits=bits[1:3]) cr2 = ClassicalRegister(name="cr2", bits=bits[4:6]) # cr3 overlaps cr2, but this should be allowed in this alias form. cr3 = ClassicalRegister(name="cr3", bits=bits[5:]) qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3) qc.measure(0, 0) qc.measure(0, 1) qc.measure(0, 2) qc.measure(0, 3) qc.measure(0, 4) qc.measure(0, 5) qc.measure(0, 6) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit _bit0;", "bit _bit1;", "bit _bit2;", "bit _bit3;", "bit _bit4;", "bit _bit5;", "bit _bit6;", "let cr1 = {_bit1, _bit2};", "let cr2 = {_bit4, _bit5};", "let cr3 = {cr2[1], _bit6};", "qubit[1] qr;", "_bit0 = measure qr[0];", "cr1[0] = measure qr[0];", "cr1[1] = measure qr[0];", "_bit3 = measure qr[0];", "cr2[0] = measure qr[0];", "cr3[0] = measure qr[0];", "cr3[1] = measure qr[0];", "", ] ) self.assertEqual(dumps(qc, allow_aliasing=True), expected_qasm) def test_old_alias_classical_registers_option(self): """Test that the ``alias_classical_registers`` option still functions during its changeover period.""" qreg = QuantumRegister(1, name="qr") bits = [Clbit() for _ in [None] * 7] cr1 = ClassicalRegister(name="cr1", bits=bits[1:3]) cr2 = ClassicalRegister(name="cr2", bits=bits[4:6]) # cr3 overlaps cr2, but this should be allowed in this alias form. cr3 = ClassicalRegister(name="cr3", bits=bits[5:]) qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3) qc.measure(0, 0) qc.measure(0, 1) qc.measure(0, 2) qc.measure(0, 3) qc.measure(0, 4) qc.measure(0, 5) qc.measure(0, 6) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit _bit0;", "bit _bit1;", "bit _bit2;", "bit _bit3;", "bit _bit4;", "bit _bit5;", "bit _bit6;", "let cr1 = {_bit1, _bit2};", "let cr2 = {_bit4, _bit5};", "let cr3 = {cr2[1], _bit6};", "qubit[1] qr;", "_bit0 = measure qr[0];", "cr1[0] = measure qr[0];", "cr1[1] = measure qr[0];", "_bit3 = measure qr[0];", "cr2[0] = measure qr[0];", "cr3[0] = measure qr[0];", "cr3[1] = measure qr[0];", "", ] ) self.assertEqual(dumps(qc, alias_classical_registers=True), expected_qasm) def test_simple_for_loop(self): """Test that a simple for loop outputs the expected result.""" parameter = Parameter("x") loop_body = QuantumCircuit(1) loop_body.rx(parameter, 0) loop_body.break_loop() loop_body.continue_loop() qc = QuantumCircuit(2) qc.for_loop([0, 3, 4], parameter, loop_body, [1], []) qc.x(0) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"qubit[2] {qr_name};", f"for {parameter.name} in {{0, 3, 4}} {{", f" rx({parameter.name}) {qr_name}[1];", " break;", " continue;", "}", f"x {qr_name}[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_nested_for_loop(self): """Test that a for loop nested inside another outputs the expected result.""" inner_parameter = Parameter("x") outer_parameter = Parameter("y") inner_body = QuantumCircuit(2) inner_body.rz(inner_parameter, 0) inner_body.rz(outer_parameter, 1) inner_body.break_loop() outer_body = QuantumCircuit(2) outer_body.h(0) outer_body.rz(outer_parameter, 1) # Note we reverse the order of the bits here to test that this is traced. outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], []) outer_body.continue_loop() qc = QuantumCircuit(2) qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], []) qc.x(0) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"qubit[2] {qr_name};", f"for {outer_parameter.name} in [0:3] {{", f" h {qr_name}[0];", f" rz({outer_parameter.name}) {qr_name}[1];", f" for {inner_parameter.name} in [1:2:4] {{", # Note the reversed bit order. f" rz({inner_parameter.name}) {qr_name}[1];", f" rz({outer_parameter.name}) {qr_name}[0];", " break;", " }", " continue;", "}", f"x {qr_name}[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_regular_parameter_in_nested_for_loop(self): """Test that a for loop nested inside another outputs the expected result, including defining parameters that are used in nested loop scopes.""" inner_parameter = Parameter("x") outer_parameter = Parameter("y") regular_parameter = Parameter("t") inner_body = QuantumCircuit(2) inner_body.h(0) inner_body.rx(regular_parameter, 1) inner_body.break_loop() outer_body = QuantumCircuit(2) outer_body.h(0) outer_body.h(1) # Note we reverse the order of the bits here to test that this is traced. outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], []) outer_body.continue_loop() qc = QuantumCircuit(2) qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], []) qc.x(0) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', # This next line will be missing until gh-7280 is fixed. f"input float[64] {regular_parameter.name};", f"qubit[2] {qr_name};", f"for {outer_parameter.name} in [0:3] {{", f" h {qr_name}[0];", f" h {qr_name}[1];", f" for {inner_parameter.name} in [1:2:4] {{", # Note the reversed bit order. f" h {qr_name}[1];", f" rx({regular_parameter.name}) {qr_name}[0];", " break;", " }", " continue;", "}", f"x {qr_name}[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_for_loop_with_no_parameter(self): """Test that a for loop with the parameter set to ``None`` outputs the expected result.""" loop_body = QuantumCircuit(1) loop_body.h(0) qc = QuantumCircuit(2) qc.for_loop([0, 3, 4], None, loop_body, [1], []) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"qubit[2] {qr_name};", "for _ in {0, 3, 4} {", f" h {qr_name}[1];", "}", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_simple_while_loop(self): """Test that a simple while loop works correctly.""" loop_body = QuantumCircuit(1) loop_body.h(0) loop_body.break_loop() loop_body.continue_loop() qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.while_loop((cr, 0), loop_body, [1], []) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "while (cr == 0) {", " h qr[1];", " break;", " continue;", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_nested_while_loop(self): """Test that a while loop nested inside another outputs the expected result.""" inner_body = QuantumCircuit(2, 2) inner_body.measure(0, 0) inner_body.measure(1, 1) inner_body.break_loop() outer_body = QuantumCircuit(2, 2) outer_body.measure(0, 0) outer_body.measure(1, 1) # We reverse the order of the bits here to test this works, and test a single-bit condition. outer_body.while_loop((outer_body.clbits[0], 0), inner_body, [1, 0], [1, 0]) outer_body.continue_loop() qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.while_loop((cr, 0), outer_body, [0, 1], [0, 1]) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "while (cr == 0) {", " cr[0] = measure qr[0];", " cr[1] = measure qr[1];", # Note the reversed bits in the body. " while (!cr[0]) {", " cr[1] = measure qr[1];", " cr[0] = measure qr[0];", " break;", " }", " continue;", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_simple_if_statement(self): """Test that a simple if statement with no else works correctly.""" true_body = QuantumCircuit(1) true_body.h(0) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_test((cr, 0), true_body, [1], []) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " h qr[1];", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_simple_if_else_statement(self): """Test that a simple if statement with an else branch works correctly.""" true_body = QuantumCircuit(1) true_body.h(0) false_body = QuantumCircuit(1) false_body.z(0) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), true_body, false_body, [1], []) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " h qr[1];", "} else {", " z qr[1];", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_nested_if_else_statement(self): """Test that a nested if/else statement works correctly.""" inner_true_body = QuantumCircuit(2, 2) inner_true_body.measure(0, 0) inner_false_body = QuantumCircuit(2, 2) inner_false_body.measure(1, 1) outer_true_body = QuantumCircuit(2, 2) outer_true_body.if_else( (outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1] ) outer_false_body = QuantumCircuit(2, 2) # Note the flipped bits here. outer_false_body.if_else( (outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0] ) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " if (!cr[0]) {", " cr[0] = measure qr[0];", " } else {", " cr[1] = measure qr[1];", " }", "} else {", " if (cr[0]) {", " cr[1] = measure qr[1];", " } else {", " cr[0] = measure qr[0];", " }", "}", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_chain_else_if(self): """Test the basic 'else/if' chaining logic for flattening the else scope if its content is a single if/else statement.""" inner_true_body = QuantumCircuit(2, 2) inner_true_body.measure(0, 0) inner_false_body = QuantumCircuit(2, 2) inner_false_body.measure(1, 1) outer_true_body = QuantumCircuit(2, 2) outer_true_body.if_else( (outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1] ) outer_false_body = QuantumCircuit(2, 2) # Note the flipped bits here. outer_false_body.if_else( (outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0] ) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " if (!cr[0]) {", " cr[0] = measure qr[0];", " } else {", " cr[1] = measure qr[1];", " }", "} else if (cr[0]) {", " cr[1] = measure qr[1];", "} else {", " cr[0] = measure qr[0];", "}", "", ] ) # This is not the default behaviour, and it's pretty buried how you'd access it. builder = QASM3Builder( qc, includeslist=("stdgates.inc",), basis_gates=("U",), disable_constants=False, allow_aliasing=False, ) stream = StringIO() BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program()) self.assertEqual(stream.getvalue(), expected_qasm) def test_chain_else_if_does_not_chain_if_extra_instructions(self): """Test the basic 'else/if' chaining logic for flattening the else scope if its content is a single if/else statement does not cause a flattening if the 'else' block is not a single if/else.""" inner_true_body = QuantumCircuit(2, 2) inner_true_body.measure(0, 0) inner_false_body = QuantumCircuit(2, 2) inner_false_body.measure(1, 1) outer_true_body = QuantumCircuit(2, 2) outer_true_body.if_else( (outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1] ) outer_false_body = QuantumCircuit(2, 2) # Note the flipped bits here. outer_false_body.if_else( (outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0] ) outer_false_body.h(0) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " if (!cr[0]) {", " cr[0] = measure qr[0];", " } else {", " cr[1] = measure qr[1];", " }", "} else {", " if (cr[0]) {", " cr[1] = measure qr[1];", " } else {", " cr[0] = measure qr[0];", " }", " h qr[0];", "}", "", ] ) # This is not the default behaviour, and it's pretty buried how you'd access it. builder = QASM3Builder( qc, includeslist=("stdgates.inc",), basis_gates=("U",), disable_constants=False, allow_aliasing=False, ) stream = StringIO() BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program()) self.assertEqual(stream.getvalue(), expected_qasm) def test_custom_gate_used_in_loop_scope(self): """Test that a custom gate only used within a loop scope still gets a definition at the top level.""" parameter_a = Parameter("a") parameter_b = Parameter("b") custom = QuantumCircuit(1) custom.rx(parameter_a, 0) custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate() custom_gate.name = "custom" loop_body = QuantumCircuit(1) loop_body.append(custom_gate, [0]) qc = QuantumCircuit(1) qc.for_loop(range(2), parameter_b, loop_body, [0], []) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate custom _gate_q_0 {", " rx(0.5) _gate_q_0;", "}", "qubit[1] q;", "for b in [0:1] {", " custom q[0];", "}", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_registers_have_escaped_names(self): """Test that both types of register are emitted with safely escaped names if they begin with invalid names. Regression test of gh-9658.""" qc = QuantumCircuit( QuantumRegister(2, name="q_{reg}"), ClassicalRegister(2, name="c_{reg}") ) qc.measure([0, 1], [0, 1]) out_qasm = dumps(qc) matches = {match_["name"] for match_ in self.register_regex.finditer(out_qasm)} self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}") def test_parameters_have_escaped_names(self): """Test that parameters are emitted with safely escaped names if they begin with invalid names. Regression test of gh-9658.""" qc = QuantumCircuit(1) qc.u(Parameter("p_{0}"), 2 * Parameter("p_?0!"), 0, 0) out_qasm = dumps(qc) matches = {match_["name"] for match_ in self.scalar_parameter_regex.finditer(out_qasm)} self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}") def test_parameter_expression_after_naming_escape(self): """Test that :class:`.Parameter` instances are correctly renamed when they are used with :class:`.ParameterExpression` blocks, even if they have names that needed to be escaped.""" param = Parameter("measure") # an invalid name qc = QuantumCircuit(1) qc.u(2 * param, 0, 0, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "input float[64] _measure;", "qubit[1] q;", "U(2*_measure, 0, 0) q[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_parameters_and_registers_cannot_have_naming_clashes(self): """Test that parameters and registers are considered part of the same symbol table for the purposes of avoiding clashes.""" qreg = QuantumRegister(1, "clash") param = Parameter("clash") qc = QuantumCircuit(qreg) qc.u(param, 0, 0, 0) out_qasm = dumps(qc) register_name = self.register_regex.search(out_qasm) parameter_name = self.scalar_parameter_regex.search(out_qasm) self.assertTrue(register_name) self.assertTrue(parameter_name) self.assertIn("clash", register_name["name"]) self.assertIn("clash", parameter_name["name"]) self.assertNotEqual(register_name["name"], parameter_name["name"]) # Not necessarily all the reserved keywords, just a sensibly-sized subset. @data("bit", "const", "def", "defcal", "float", "gate", "include", "int", "let", "measure") def test_reserved_keywords_as_names_are_escaped(self, keyword): """Test that reserved keywords used to name registers and parameters are escaped into another form when output, and the escaping cannot introduce new conflicts.""" with self.subTest("register"): qreg = QuantumRegister(1, keyword) qc = QuantumCircuit(qreg) out_qasm = dumps(qc) register_name = self.register_regex.search(out_qasm) self.assertTrue(register_name, msg=f"Observed OQ3:\n{out_qasm}") self.assertNotEqual(keyword, register_name["name"]) with self.subTest("parameter"): qc = QuantumCircuit(1) param = Parameter(keyword) qc.u(param, 0, 0, 0) out_qasm = dumps(qc) parameter_name = self.scalar_parameter_regex.search(out_qasm) self.assertTrue(parameter_name, msg=f"Observed OQ3:\n{out_qasm}") self.assertNotEqual(keyword, parameter_name["name"]) def test_expr_condition(self): """Simple test that the conditions of `if`s and `while`s can be `Expr` nodes.""" bits = [Qubit(), Clbit()] cr = ClassicalRegister(2, "cr") if_body = QuantumCircuit(1) if_body.x(0) while_body = QuantumCircuit(1) while_body.x(0) qc = QuantumCircuit(bits, cr) qc.if_test(expr.logic_not(qc.clbits[0]), if_body, [0], []) qc.while_loop(expr.equal(cr, 3), while_body, [0], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; bit[2] cr; qubit _qubit0; if (!_bit0) { x _qubit0; } while (cr == 3) { x _qubit0; } """ self.assertEqual(dumps(qc), expected) def test_expr_nested_condition(self): """Simple test that the conditions of `if`s and `while`s can be `Expr` nodes when nested, and the mapping of inner bits to outer bits is correct.""" bits = [Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") inner_if_body = QuantumCircuit(1) inner_if_body.x(0) outer_if_body = QuantumCircuit(1, 1) outer_if_body.if_test(expr.lift(outer_if_body.clbits[0]), inner_if_body, [0], []) inner_while_body = QuantumCircuit(1) inner_while_body.x(0) outer_while_body = QuantumCircuit([Qubit()], cr) outer_while_body.while_loop(expr.equal(expr.bit_and(cr, 3), 3), inner_while_body, [0], []) qc = QuantumCircuit(bits, cr) qc.if_test(expr.logic_not(qc.clbits[0]), outer_if_body, [0], [1]) qc.while_loop(expr.equal(cr, 3), outer_while_body, [0], cr) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; bit _bit1; bit[2] cr; qubit _qubit0; if (!_bit0) { if (_bit1) { x _qubit0; } } while (cr == 3) { while ((cr & 3) == 3) { x _qubit0; } } """ self.assertEqual(dumps(qc), expected) def test_expr_associativity_left(self): """Test that operations that are in the expression tree in a left-associative form are output to OQ3 correctly.""" body = QuantumCircuit() cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") cr3 = ClassicalRegister(3, "cr3") qc = QuantumCircuit(cr1, cr2, cr3) qc.if_test(expr.equal(expr.bit_and(expr.bit_and(cr1, cr2), cr3), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_or(expr.bit_or(cr1, cr2), cr3), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_xor(expr.bit_xor(cr1, cr2), cr3), 7), body.copy(), [], []) qc.if_test(expr.logic_and(expr.logic_and(cr1[0], cr1[1]), cr1[2]), body.copy(), [], []) qc.if_test(expr.logic_or(expr.logic_or(cr1[0], cr1[1]), cr1[2]), body.copy(), [], []) # Note that bitwise operations have lower priority than `==` so there's extra parentheses. # All these operators are left-associative in OQ3. expected = """\ OPENQASM 3; include "stdgates.inc"; bit[3] cr1; bit[3] cr2; bit[3] cr3; if ((cr1 & cr2 & cr3) == 7) { } if ((cr1 | cr2 | cr3) == 7) { } if ((cr1 ^ cr2 ^ cr3) == 7) { } if (cr1[0] && cr1[1] && cr1[2]) { } if (cr1[0] || cr1[1] || cr1[2]) { } """ self.assertEqual(dumps(qc), expected) def test_expr_associativity_right(self): """Test that operations that are in the expression tree in a right-associative form are output to OQ3 correctly.""" body = QuantumCircuit() cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") cr3 = ClassicalRegister(3, "cr3") qc = QuantumCircuit(cr1, cr2, cr3) qc.if_test(expr.equal(expr.bit_and(cr1, expr.bit_and(cr2, cr3)), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_or(cr1, expr.bit_or(cr2, cr3)), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_xor(cr1, expr.bit_xor(cr2, cr3)), 7), body.copy(), [], []) qc.if_test(expr.logic_and(cr1[0], expr.logic_and(cr1[1], cr1[2])), body.copy(), [], []) qc.if_test(expr.logic_or(cr1[0], expr.logic_or(cr1[1], cr1[2])), body.copy(), [], []) # Note that bitwise operations have lower priority than `==` so there's extra parentheses. # All these operators are left-associative in OQ3, so we need parentheses for them to be # parsed correctly. Mathematically, they're all actually associative in general, so the # order doesn't _technically_ matter. expected = """\ OPENQASM 3; include "stdgates.inc"; bit[3] cr1; bit[3] cr2; bit[3] cr3; if ((cr1 & (cr2 & cr3)) == 7) { } if ((cr1 | (cr2 | cr3)) == 7) { } if ((cr1 ^ (cr2 ^ cr3)) == 7) { } if (cr1[0] && (cr1[1] && cr1[2])) { } if (cr1[0] || (cr1[1] || cr1[2])) { } """ self.assertEqual(dumps(qc), expected) def test_expr_binding_unary(self): """Test that nested unary operators don't insert unnecessary brackets.""" body = QuantumCircuit() cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(cr) qc.if_test(expr.equal(expr.bit_not(expr.bit_not(cr)), 3), body.copy(), [], []) qc.if_test(expr.logic_not(expr.logic_not(cr[0])), body.copy(), [], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] cr; if (~~cr == 3) { } if (!!cr[0]) { } """ self.assertEqual(dumps(qc), expected) def test_expr_precedence(self): """Test that the precedence properties of operators are correctly output.""" body = QuantumCircuit() cr = ClassicalRegister(2, "cr") # This tree is _completely_ inside out, so there's brackets needed round every operand. inside_out = expr.logic_not( expr.less( expr.bit_and( expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), ), expr.bit_and( expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), ), ) ) # This one is the other way round - the tightest-binding operations are on the inside, so no # brackets should be needed at all except to put in a comparison to a bitwise binary # operation, since those bind less tightly than anything that can cast them to a bool. outside_in = expr.logic_or( expr.logic_and( expr.equal(expr.bit_or(cr, cr), expr.bit_and(cr, cr)), expr.equal(expr.bit_and(cr, cr), expr.bit_or(cr, cr)), ), expr.logic_and( expr.greater(expr.bit_or(cr, cr), expr.bit_xor(cr, cr)), expr.less_equal(expr.bit_xor(cr, cr), expr.bit_or(cr, cr)), ), ) # And an extra test of the logical operator order. logics = expr.logic_or( expr.logic_and( expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])), expr.logic_not(expr.logic_and(cr[0], cr[0])), ), expr.logic_and( expr.logic_not(expr.logic_and(cr[0], cr[0])), expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])), ), ) qc = QuantumCircuit(cr) qc.if_test(inside_out, body.copy(), [], []) qc.if_test(outside_in, body.copy(), [], []) qc.if_test(logics, body.copy(), [], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] cr; if (!((((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr)))\ < (((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr))))) { } if ((cr | cr) == (cr & cr) && (cr & cr) == (cr | cr)\ || (cr | cr) > (cr ^ cr) && (cr ^ cr) <= (cr | cr)) { } if ((!cr[0] || !cr[0]) && !(cr[0] && cr[0]) || !(cr[0] && cr[0]) && (!cr[0] || !cr[0])) { } """ self.assertEqual(dumps(qc), expected) def test_no_unnecessary_cast(self): """This is a bit of a cross `Expr`-constructor / OQ3-exporter test. It doesn't really matter whether or not the `Expr` constructor functions insert cast nodes into their output for the literals (at the time of writing [commit 2616602], they don't because they do some type inference) but the OQ3 export definitely shouldn't have them.""" cr = ClassicalRegister(8, "cr") qc = QuantumCircuit(cr) # Note that the integer '1' has a minimum bit-width of 1, whereas the register has a width # of 8. We're testing to make sure that there's no spurious cast up from `bit[1]` to # `bit[8]`, or anything like that, _whether or not_ the `Expr` node includes one. qc.if_test(expr.equal(cr, 1), QuantumCircuit(), [], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[8] cr; if (cr == 1) { } """ self.assertEqual(dumps(qc), expected) class TestCircuitQASM3ExporterTemporaryCasesWithBadParameterisation(QiskitTestCase): """Test functionality that is not what we _want_, but is what we need to do while the definition of custom gates with parameterisation does not work correctly. These tests are modified versions of those marked with the `requires_fixed_parameterisation` decorator, and this whole class can be deleted once those are fixed. See gh-7335. """ maxDiff = 1_000_000 def test_basis_gates(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) first_h = qc.h(1)[0].operation qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() first_x = qc.x(2).c_if(qc.clbits[1], 1)[0].operation qc.z(2).c_if(qc.clbits[0], 1) u2 = first_h.definition.data[0].operation u3_1 = u2.definition.data[0].operation u3_2 = first_x.definition.data[0].operation expected_qasm = "\n".join( [ "OPENQASM 3;", f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi/2, 0, pi) _gate_q_0;", "}", f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{", f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", f" u2_{id(u2)}(0, pi) _gate_q_0;", "}", f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi, 0, pi) _gate_q_0;", "}", "gate x _gate_q_0 {", f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;", "}", "bit[2] c;", "qubit[3] q;", "h q[1];", "cx q[1], q[2];", "barrier q[0], q[1], q[2];", "cx q[0], q[1];", "h q[0];", "barrier q[0], q[1], q[2];", "c[0] = measure q[0];", "c[1] = measure q[1];", "barrier q[0], q[1], q[2];", "if (c[1]) {", " x q[2];", "}", "if (c[0]) {", " z q[2];", "}", "", ] ) self.assertEqual( Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(qc), expected_qasm, ) def test_teleportation(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) qc.h(1) qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() qc.x(2).c_if(qc.clbits[1], 1) qc.z(2).c_if(qc.clbits[0], 1) transpiled = transpile(qc, initial_layout=[0, 1, 2]) first_h = transpiled.data[0].operation u2 = first_h.definition.data[0].operation u3_1 = u2.definition.data[0].operation first_x = transpiled.data[-2].operation u3_2 = first_x.definition.data[0].operation first_z = transpiled.data[-1].operation u1 = first_z.definition.data[0].operation u3_3 = u1.definition.data[0].operation expected_qasm = "\n".join( [ "OPENQASM 3;", f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi/2, 0, pi) _gate_q_0;", "}", f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{", f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", f" u2_{id(u2)}(0, pi) _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi, 0, pi) _gate_q_0;", "}", "gate x _gate_q_0 {", f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;", "}", f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(0, 0, pi) _gate_q_0;", "}", f"gate u1_{id(u1)}(_gate_p_0) _gate_q_0 {{", f" u3_{id(u3_3)}(0, 0, pi) _gate_q_0;", "}", "gate z _gate_q_0 {", f" u1_{id(u1)}(pi) _gate_q_0;", "}", "bit[2] c;", "h $1;", "cx $1, $2;", "barrier $0, $1, $2;", "cx $0, $1;", "h $0;", "barrier $0, $1, $2;", "c[0] = measure $0;", "c[1] = measure $1;", "barrier $0, $1, $2;", "if (c[1]) {", " x $2;", "}", "if (c[0]) {", " z $2;", "}", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm) def test_custom_gate_with_params_bound_main_call(self): """Custom gate with unbound parameters that are bound in the main circuit""" parameter0 = Parameter("p0") parameter1 = Parameter("p1") custom = QuantumCircuit(2, name="custom") custom.rz(parameter0, 0) custom.rz(parameter1 / 2, 1) qr_all_qubits = QuantumRegister(3, "q") qr_r = QuantumRegister(3, "r") circuit = QuantumCircuit(qr_all_qubits, qr_r) circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]]) circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True) custom_id = id(circuit.data[0].operation) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"gate custom_{custom_id}(_gate_p_0, _gate_p_1) _gate_q_0, _gate_q_1 {{", " rz(pi) _gate_q_0;", " rz(pi/4) _gate_q_1;", "}", "qubit[3] q;", "qubit[3] r;", f"custom_{custom_id}(pi, pi/2) q[0], r[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_no_include(self): """Test explicit gate declaration (no include)""" q = QuantumRegister(2, "q") circuit = QuantumCircuit(q) circuit.rz(pi / 2, 0) circuit.sx(0) circuit.cx(0, 1) rz = circuit.data[0].operation u1_1 = rz.definition.data[0].operation u3_1 = u1_1.definition.data[0].operation sx = circuit.data[1].operation sdg = sx.definition.data[0].operation u1_2 = sdg.definition.data[0].operation u3_2 = u1_2.definition.data[0].operation h_ = sx.definition.data[1].operation u2_1 = h_.definition.data[0].operation u3_3 = u2_1.definition.data[0].operation expected_qasm = "\n".join( [ "OPENQASM 3;", f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(0, 0, pi/2) _gate_q_0;", "}", f"gate u1_{id(u1_1)}(_gate_p_0) _gate_q_0 {{", f" u3_{id(u3_1)}(0, 0, pi/2) _gate_q_0;", "}", f"gate rz_{id(rz)}(_gate_p_0) _gate_q_0 {{", f" u1_{id(u1_1)}(pi/2) _gate_q_0;", "}", f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(0, 0, -pi/2) _gate_q_0;", "}", f"gate u1_{id(u1_2)}(_gate_p_0) _gate_q_0 {{", f" u3_{id(u3_2)}(0, 0, -pi/2) _gate_q_0;", "}", "gate sdg _gate_q_0 {", f" u1_{id(u1_2)}(-pi/2) _gate_q_0;", "}", f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi/2, 0, pi) _gate_q_0;", "}", f"gate u2_{id(u2_1)}(_gate_p_0, _gate_p_1) _gate_q_0 {{", f" u3_{id(u3_3)}(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", f" u2_{id(u2_1)}(0, pi) _gate_q_0;", "}", "gate sx _gate_q_0 {", " sdg _gate_q_0;", " h _gate_q_0;", " sdg _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", "qubit[2] q;", f"rz_{id(rz)}(pi/2) q[0];", "sx q[0];", "cx q[0], q[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm) def test_unusual_conditions(self): """Test that special QASM constructs such as ``measure`` are correctly handled when the Terra instructions have old-style conditions.""" qc = QuantumCircuit(3, 2) qc.h(0) qc.measure(0, 0) qc.measure(1, 1).c_if(0, True) qc.reset([0, 1]).c_if(0, True) with qc.while_loop((qc.clbits[0], True)): qc.break_loop().c_if(0, True) qc.continue_loop().c_if(0, True) # Terra forbids delay and barrier from being conditioned through `c_if`, but in theory they # should work fine in a dynamic-circuits sense (although what a conditional barrier _means_ # is a whole other kettle of fish). delay = Delay(16, "dt") delay.condition = (qc.clbits[0], True) qc.append(delay, [0], []) barrier = Barrier(2) barrier.condition = (qc.clbits[0], True) qc.append(barrier, [0, 1], []) expected = """ OPENQASM 3; include "stdgates.inc"; bit[2] c; qubit[3] q; h q[0]; c[0] = measure q[0]; if (c[0]) { c[1] = measure q[1]; } if (c[0]) { reset q[0]; } if (c[0]) { reset q[1]; } while (c[0]) { if (c[0]) { break; } if (c[0]) { continue; } } if (c[0]) { delay[16dt] q[0]; } if (c[0]) { barrier q[0], q[1]; }""" self.assertEqual(dumps(qc).strip(), expected.strip()) class TestExperimentalFeatures(QiskitTestCase): """Tests of features that are hidden behind experimental flags.""" maxDiff = None def test_switch_forbidden_without_flag(self): """Omitting the feature flag should raise an error.""" case = QuantumCircuit(1) circuit = QuantumCircuit(1, 1) circuit.switch(circuit.clbits[0], [((True, False), case)], [0], []) with self.assertRaisesRegex(QASM3ExporterError, "'switch' statements are not stabilized"): dumps(circuit) def test_switch_clbit(self): """Test that a switch statement can be constructed with a bit as a condition.""" qubit = Qubit() clbit = Clbit() case1 = QuantumCircuit([qubit, clbit]) case1.x(0) case2 = QuantumCircuit([qubit, clbit]) case2.z(0) circuit = QuantumCircuit([qubit, clbit]) circuit.switch(clbit, [(True, case1), (False, case2)], [0], [0]) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; int switch_dummy; qubit _qubit0; switch_dummy = _bit0; switch (switch_dummy) { case 1: { x _qubit0; } break; case 0: { z _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_register(self): """Test that a switch statement can be constructed with a register as a condition.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) case3 = QuantumCircuit([qubit], creg) case3.z(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), (1, case2), (2, case3)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; qubit _qubit0; switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: { y _qubit0; } break; case 2: { z _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_with_default(self): """Test that a switch statement can be constructed with a default case at the end.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) case3 = QuantumCircuit([qubit], creg) case3.z(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), (1, case2), (CASE_DEFAULT, case3)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; qubit _qubit0; switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: { y _qubit0; } break; default: { z _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_multiple_cases_to_same_block(self): """Test that it is possible to add multiple cases that apply to the same block, if they are given as a compound value. This is an allowed special case of block fall-through.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; qubit _qubit0; switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } """ self.assertEqual(test, expected) def test_multiple_switches_dont_clash_on_dummy(self): """Test that having more than one switch statement in the circuit doesn't cause naming clashes in the dummy integer value used.""" qubit = Qubit() creg = ClassicalRegister(2, "switch_dummy") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits) circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] switch_dummy; int switch_dummy__generated0; int switch_dummy__generated1; qubit _qubit0; switch_dummy__generated0 = switch_dummy; switch (switch_dummy__generated0) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } switch_dummy__generated1 = switch_dummy; switch (switch_dummy__generated1) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_nested_in_if(self): """Test that the switch statement works when in a nested scope, including the dummy classical variable being declared globally. This isn't necessary in the OQ3 language, but it is universally valid and the IBM QSS stack prefers that. They're our primary consumers of OQ3 strings, so it's best to play nicely with them.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) body = QuantumCircuit([qubit], creg) body.switch(creg, [(0, case1), ((1, 2), case2)], [0], body.clbits) circuit = QuantumCircuit([qubit], creg) circuit.if_else((creg, 1), body.copy(), body, [0], body.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; int switch_dummy__generated0; qubit _qubit0; if (c == 1) { switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } } else { switch_dummy__generated0 = c; switch (switch_dummy__generated0) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } } """ self.assertEqual(test, expected) def test_expr_target(self): """Simple test that the target of `switch` can be `Expr` nodes.""" bits = [Qubit(), Clbit()] cr = ClassicalRegister(2, "cr") case0 = QuantumCircuit(1) case0.x(0) case1 = QuantumCircuit(1) case1.x(0) qc = QuantumCircuit(bits, cr) qc.switch(expr.logic_not(bits[1]), [(False, case0)], [0], []) qc.switch(expr.bit_and(cr, 3), [(3, case1)], [0], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; bit[2] cr; int switch_dummy; int switch_dummy__generated0; qubit _qubit0; switch_dummy = !_bit0; switch (switch_dummy) { case 0: { x _qubit0; } break; } switch_dummy__generated0 = cr & 3; switch (switch_dummy__generated0) { case 3: { x _qubit0; } break; } """ test = dumps(qc, experimental=ExperimentalFeatures.SWITCH_CASE_V1) self.assertEqual(test, expected) @ddt class TestQASM3ExporterFailurePaths(QiskitTestCase): """Tests of the failure paths for the exporter.""" def test_disallow_overlapping_classical_registers_if_no_aliasing(self): """Test that the exporter rejects circuits with a classical bit in more than one register if the ``alias_classical_registers`` option is set false.""" qubits = [Qubit() for _ in [None] * 3] clbits = [Clbit() for _ in [None] * 5] registers = [ClassicalRegister(bits=clbits[:4]), ClassicalRegister(bits=clbits[1:])] qc = QuantumCircuit(qubits, *registers) exporter = Exporter(alias_classical_registers=False) with self.assertRaisesRegex(QASM3ExporterError, r"classical registers .* overlap"): exporter.dumps(qc) @data([1, 2, 1.1], [1j, 2]) def test_disallow_for_loops_with_non_integers(self, indices): """Test that the exporter rejects ``for`` loops that include non-integer values in their index sets.""" loop_body = QuantumCircuit() qc = QuantumCircuit(2, 2) qc.for_loop(indices, None, loop_body, [], []) exporter = Exporter() with self.assertRaisesRegex( QASM3ExporterError, r"The values in QASM 3 'for' loops must all be integers.*" ): exporter.dumps(qc) def test_disallow_custom_subroutine_with_parameters(self): """Test that the exporter throws an error instead of trying to export a subroutine with parameters, while this is not supported.""" subroutine = QuantumCircuit(1) subroutine.rx(Parameter("x"), 0) qc = QuantumCircuit(1) qc.append(subroutine.to_instruction(), [0], []) exporter = Exporter() with self.assertRaisesRegex( QASM3ExporterError, "Exporting non-unitary instructions is not yet supported" ): exporter.dumps(qc) def test_disallow_opaque_instruction(self): """Test that the exporter throws an error instead of trying to export something into a ``defcal`` block, while this is not supported.""" qc = QuantumCircuit(1) qc.append(Instruction("opaque", 1, 0, []), [0], []) exporter = Exporter() with self.assertRaisesRegex( QASM3ExporterError, "Exporting opaque instructions .* is not yet supported" ): exporter.dumps(qc)
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/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/acfilok96/Quantum-Computation
acfilok96
from qiskit import * qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) %matplotlib inline circuit.draw(output='mpl') circuit.h(qr[0]) circuit.draw(output = 'mpl') circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') circuit.measure(qr, cr) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') execute(circuit, backend=simulator) result = execute(circuit, backend=simulator).result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) from qiskit import IBMQ MY_API_TOKEN = "b32678329f7f6dd426b8cf18f20bea23c2cd056b0bee2b4bcf49744b612e598f20f7170a8da4bfd99b009b6fa59d596edea7a6926fd388be158843d8e******" IBMQ.save_account(MY_API_TOKEN, overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider.backends() backend = provider.get_backend('ibmq_santiago') job =execute(circuit, backend= backend) from qiskit.tools.monitor import job_monitor job_monitor(job) result = job.result() # plot_histogram plot_histogram(result.get_counts(circuit))
https://github.com/sebasmos/QuantumVE
sebasmos
%reset -f %matplotlib inline import numpy as np import matplotlib.pyplot as plt import numpy as np import pickle import datetime import os name_data = "sample_trajectories.pkl" os.makedirs("data") Fn = os.path.join(os.getcwd(),"data",name_data) # initialize random number generator rng = np.random.default_rng() # Set simulation parameters dt = 1e-5 # timestep for simulation dt_out = 1e-4 # timestep of saved trajectories stride_out = int(np.round(dt_out/dt)) N_sim = 4000 # number of trajectories to be generated # For each trajectory, we use a random number of timesteps. This is to # show that the parameter inference works with trajectory samples of # various lengths. # The number of timesteps for each trajectory is sampled from a uniform # distribution on the interes from N_steps_min to N_steps_max, which are # defined here: N_steps_mean = int(np.round(0.05/dt)) N_steps_min = N_steps_mean*0.5 N_steps_max = N_steps_mean*1.5 # generate an array that contains the number of steps of all trajectories: N_steps = rng.integers(low=N_steps_min, high=N_steps_max, size=N_sim) # For each simulation, the initial condition is drawn from a uniform # distribution on [x_L, x_R], using the following values: x_L = -1.5 x_R = 1.5 # Definition of the parameters of the Langevin equation. # # We simulate the Ito-Langevin equation # dX_t = a(X_t) * dt + sqrt(2*D) * dW_t, # where dX_t is the increment of the reaction coordinate at time t, # a(x) is the drift, D is the diffusivity (which we assume to be a constant # number, meaning we consider additive noise), and dW_t is the increment # of the Wiener process. # # We consider a constant diffusivity D = 1. # and a gradient drift a(x) = -dU/dx that originates from a double-well potential # U(x) = U0 * ( x**2 - 1 )**2, so that a(x) = -4 * U0 * ( x**2 - 1 ) * x. U0 = 2. a = lambda x: -4*U0*(x**2 - 1)*x trajectories = [] print("{time}\tStarting simulation of {total} trajectories...".format( total =N_sim, time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))) for i in range(N_sim): print("{time}\tRunning simulation {cur_int} of {total}...".format(cur_int=i+1, total =N_sim, time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')), end='\r') # # generate array containing current trajectory current_trajectory = np.zeros(N_steps[i]+1,dtype=float) # generate initial condition for current trajectory current_trajectory[0] = rng.random()*(x_R-x_L) + x_L # # generate all random numbers for the current simulation random_numbers_for_current_simulation = rng.normal(size=N_steps[i]) random_numbers_for_current_simulation *= np.sqrt(2*D*dt) # # run simulation using Euler-Maruyama algorithm for j,current_x in enumerate(current_trajectory[:-1]): current_trajectory[j+1] = dt*a(current_x) \ + random_numbers_for_current_simulation[j] \ + current_x # # append current trajectory to list of trajectories trajectories.append(current_trajectory[::stride_out]) print("{time}\tFinished simulation {total} trajectories. ".format( total =N_sim, time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')), end='\n') # save resulting trajectories pickle.dump(trajectories,open(Fn,'wb')) import numpy as np import pickle class inference: ''' This is the base class that contains the shared codebase for both the linear and nonlinear integrators ''' def __init__(self,parameters={}): ''' Set simulation parameters, which are provided as dictionary in the argument parameters ''' # self.trajectories_loaded = False self.index_loaded = False # self.verbose = True # default value for verbose self.index_directory = './' # default value for index directory # # the following parameters need to be set by the user self.trajectories_filename = 'not set' self.xl = -np.inf self.xr = +np.inf self.N_bins = 100 self.dt = 'not set' # the following two parameters are calculated by the program # and cannot be set manually self.dx = 'not set' self.x = 'not set' # self.set_parameters(parameters) def set_parameters(self,parameters={}): ''' Change parameters of an existing instance of this class ''' # try: self.verbose = parameters['verbose'] except KeyError: pass # try: self.trajectories_filename = parameters['trajectories_filename'] except KeyError: pass # try: self.index_directory = parameters['index_directory'] except KeyError: pass # try: self.xl = parameters['xl'] except KeyError: pass # try: self.xr = parameters['xr'] except KeyError: pass # try: self.N_bins = parameters['N_bins'] except KeyError: pass # try: self.dt = parameters['dt'] except KeyError: pass # # update arrays # if self.xl > -np.inf and self.xr < np.inf: self.dx = (self.xr - self.xl)/self.N_bins if self.N_bins != 'not set': self.x = self.xl + (np.arange(self.N_bins) + 0.5)*self.dx def get_parameters(self,print_parameters=False): ''' Return current parameters ''' self.index_parameters = { 'trajectories_filename':self.trajectories_filename, 'index_directory':self.index_directory, 'xl':self.xl, 'xr':self.xr, 'dx':self.dx, 'dt':self.dt, 'N_bins':self.N_bins, 'x':self.x } if print_parameters: print("Parameters set for this instance:") print("trajectories_filename = {0}".format( self.trajectories_filename)) print("index_directory = {0}".format( self.index_directory)) print("xl = {0}".format(self.xl)) print("xr = {0}".format(self.xr)) print("dx = {0}".format(self.dx)) print("dt = {0}".format(self.dt)) print("N_bins = {0}".format(self.N_bins)) return self.index_parameters def save_parameters(self): ''' Save current parameters ''' # pickle.dump( self.get_parameters(print_parameters=False), open( self.index_directory + "/index_parameters.pkl", "wb" ) ) def load_parameters(self): ''' Load saved parameters ''' # index_parameters = pickle.load( open( self.index_directory + "/index_parameters.pkl", "rb" ) ) self.set_parameters(index_parameters) def check_if_all_parameters_are_set(self): ''' Check if all the parameters necessary for inference are set ''' # if self.trajectories_filename == 'not set': raise RuntimeError("Filename for input trajectories not set.") # if self.dt == 'not set': raise RuntimeError("Timestep not set.") def load_trajectories(self): # self.trajectory_lengths = [] # if self.trajectories_filename == 'not set': raise RuntimeError("No filename for trajectories to load "\ + "provided.") # self.trajectories = pickle.load(open(f"./data/{self.trajectories_filename}", "rb")) # for i, current_trajectory in enumerate(self.trajectories): self.trajectory_lengths.append(len(current_trajectory)) if self.verbose: print("Loaded {0} trajectories.".format(len(self.trajectories))) # self.trajectories_loaded = True # self.get_range_of_time_series() self.check_bounds_of_spatial_domain() def import_trajectories(self,trajectories): # self.trajectories = [] self.trajectory_lengths = [] # for i, current_trajectory in enumerate(trajectories): self.trajectories.append(current_trajectory) self.trajectory_lengths.append(len(current_trajectory)) # if self.verbose: print("Imported {0} trajectories.".format(len(self.trajectories))) # self.trajectories_loaded = True # self.get_range_of_time_series() self.check_bounds_of_spatial_domain() def get_range_of_time_series(self): # if self.trajectories_loaded == False: raise RuntimeError("Please load trajectories first.") # max_pos = -np.inf min_pos = np.inf for i, current_trajectory in enumerate(self.trajectories): cur_max = np.max(current_trajectory) cur_min = np.min(current_trajectory) if cur_max > max_pos: max_pos = cur_max if cur_min < min_pos: min_pos = cur_min ''' if self.verbose: print("For currently loaded trajectories, minimal and maximal "\ + "positions are {0:3.5f} and {1:3.5f}".format(min_pos,max_pos)) '''; self.min_pos = min_pos self.max_pos = max_pos def check_bounds_of_spatial_domain(self): # if self.xl < self.min_pos: if self.xl != -np.inf: print("Warning: l0 < (minimal position in dataset), i.e." \ + " {0:3.5f} < {1:3.5f}.".format(self.xl,self.min_pos) \ + "\n\tUsing l0 = {0:3.5f}".format(self.min_pos)) self.xl = self.min_pos # if self.xr > self.max_pos: if self.xr != np.inf: print("Warning: r0 > (maximal position in dataset), i.e." \ + " {0:3.5f} > {1:3.5f}.".format(self.xr,self.max_pos) \ + "\n\tUsing r0 = {0:3.5f}".format(self.max_pos)) self.xr = self.max_pos # update parameters so that dx gets calculated again if # self.xl or self.xr have changed self.set_parameters() def get_histogram(self,N_hist=100): # bin_edges = np.linspace(self.xl,self.xr, endpoint=True, num=N_hist+1, dtype=float) bin_centers = (bin_edges[1:] + bin_edges[:-1])/2. dx_bins = bin_edges[1] - bin_edges[0] hist = np.zeros(N_hist,dtype=float) # for i, current_trajectory in enumerate(self.trajectories): # bin_numbers = (current_trajectory - bin_edges[0]) // dx_bins for j in range(N_hist): hist[j] += np.sum( bin_numbers == j ) # return hist, bin_edges def create_index(self): # # check that trajectories are loaded if self.trajectories_loaded == False: raise RuntimeError("Please load trajectories first.") # # # traj_number: enumerates the trajectories we consider # traj_index: enumerates the timestep within each trajectory # traj_bin_index: contains the bin index of the current position of the current trajectory # self.traj_number = np.array([],dtype=int) self.traj_index = np.array([],dtype=int) self.traj_bin_index = np.array([],dtype=int) # update_frequency = np.max([len(self.trajectories) // 100,1]) # for i,current_trajectory in enumerate(self.trajectories): if self.verbose: if i % update_frequency == 0: print('Creating index. '\ + 'Processing trajectory {0} of {1}..'.format( i+1,len(self.trajectories) ),end='\r') current_indices = np.array((current_trajectory-self.xl)//self.dx, dtype=int) # # number of current trajectory self.traj_number = np.append(self.traj_number, np.ones(len(current_indices))*i) # positions within current trajectory self.traj_index = np.append(self.traj_index, np.arange(len(current_indices))) # index of bins self.traj_bin_index = np.append(self.traj_bin_index, current_indices) # self.traj_bin_indices = [] for i in range(self.N_bins): self.traj_bin_indices.append( np.array(np.where(self.traj_bin_index == i)[0],dtype=int) ) # self.traj_number = self.traj_number.astype(int) self.traj_index = self.traj_index.astype(int) # self.index_loaded = True # if self.verbose: print('Finished creating index. Processed {0} trajectories. '.format( len(self.trajectories) ),end='\n') # #return traj_number ,traj_index, traj_bin_indices def save_index(self): # if self.index_loaded == False: raise RuntimeError("No index loaded, so no index can be saved.") # self.save_parameters() # pickle.dump( self.traj_number, open( self.index_directory + "/index_traj_number.pkl", "wb" ) ) pickle.dump( self.traj_index, open( self.index_directory + "/index.pkl", "wb" ) ) pickle.dump( self.traj_bin_indices, open( self.index_directory + "/index_bin_indices.pkl", "wb" ) ) # def load_index(self): # self.load_parameters() # self.traj_number = pickle.load( open( self.index_directory + "/index_traj_number.pkl", "rb" ) ) self.traj_index = pickle.load( open( self.index_directory + "/index.pkl", "rb" ) ) self.traj_bin_indices = pickle.load( open( self.index_directory + "/index_bin_indices.pkl", "rb" ) ) # def run_inference(self,N_shift=1): # D_array = np.zeros(self.N_bins,dtype=float) a_array = np.zeros(self.N_bins,dtype=float) # for i in range(self.N_bins): if self.verbose: print('Running inference. Processing bin {0} of {1}..'.format( i+1,self.N_bins),end='\r') D_array[i], a_array[i] = self.kramers_moyal_single_bin( bin_index=i, N_shift=N_shift) if self.verbose: print('Finished inference with {0} bins. '.format( self.N_bins),end='\n') # output_dictionary = {'x':self.x, 'D':D_array, 'a':a_array} return output_dictionary def kramers_moyal_single_bin(self, bin_index,N_shift): # get list of trajectories starting in given bin list_of_trajectories_starting_in_bin = self.traj_bin_indices[bin_index] N = len(list_of_trajectories_starting_in_bin) # set up variables for <x>, <x^2>, which we want to estimate from data delta_x = 0. delta_x_squared = 0. # iterate through all trajectories that start in bin for i,cur_index in enumerate(list_of_trajectories_starting_in_bin): # note that traj_index[cur_index] labels the time at which the trajectory # with number traj_number[cur_index] is in the bin of interest. # if (self.traj_index[cur_index]+N_shift) >= \ self.trajectory_lengths[self.traj_number[cur_index]]: # this means that the length of the current trajectory segment # is less than the lagtime we want to use. In that case we # skip the current trajectory segment, but since we now have # one datapoint less we need to subtract 1 from N N -= 1 continue # cur_diff = self.trajectories[self.traj_number[cur_index]] \ [self.traj_index[cur_index]+N_shift] \ - self.trajectories[self.traj_number[cur_index]] \ [self.traj_index[cur_index]] # delta_x += cur_diff delta_x_squared += cur_diff**2 # if N == 0: print('Warning: Encountered a bin with N = 0 datapoints. To avoid '\ + 'this issue, please i) change the interval size [xl,xr], '\ + 'ii) decrease N_shift, or iii) use longer '\ + 'trajectories.') return np.nan, np.nan # D = delta_x_squared /(2*N*self.dt*N_shift) drift = delta_x / (N*self.dt*N_shift) # return D, drift # the pickle file should contain a list of 1D arrays, i.e. trajectories = pickle.load(open(f"./data/{name_data}", "rb")) # must lead to an object "trajectories" such that # trajectories[i] = 1D array # for i = 0, ..., len(trajectories) print("number of elements: ", len(trajectories)) print("one element: ", trajectories[0].shape, "first column:", trajectories[0][0]) # directory where the index we create will be saved: index_directory = './' # timestep of the trajectories dt = 1e-4 # create a dictionary with the parameters parameters = {'index_directory':index_directory, 'trajectories_filename':name_data, 'dt':dt} # create an instance of the kramers_moyal class inference = inference(parameters) # parameters of an existing class can be changed by creating a dictionary # with the new parameters, and by passing that dictionary to the class: N_bins = 120 updated_parameters = {'N_bins':N_bins} inference.set_parameters(updated_parameters) inference.get_parameters() inference inference.get_parameters() # parameters of an existing class can be changed by creating a dictionary # with the new parameters, and by passing that dictionary to the class: N_bins = 120 updated_parameters = {'N_bins':N_bins} inference.set_parameters(updated_parameters) inference.get_parameters() # the trajectories are loaded from the pickle file stored in the class variable "trajectories_filename" inference.load_trajectories() # instead of loading a pickle file, already loaded trajectories can alternatively be imported, via: # # preloaded_trajectories = [ list of 1D arrays with trajectories ] # inference.import_trajectories(preloaded_trajectories) # Note that only one list of trajectories can be loaded at one time. If several datasets are to be used, # they should be merged before passing them to the inference class. # after loading trajectories, the class variables # xl, xr, dx, x # are automatically updated: inference.get_parameters() # to see how many datapoints are available within each bin, we create # a histogram of the loaded data: N_hist = N_bins # we use the same number of bins as for the inference hist, bin_edges = inference.get_histogram(N_hist=N_hist) bin_centers = (bin_edges[1:] + bin_edges[:-1])/2. bar_width = bin_centers[1] - bin_centers[0] fig,ax = plt.subplots(1,1,figsize=(10,6)) ax.bar(bin_centers,hist,width=bar_width, alpha=0.5) ax.set_yscale('log') plt.show() plt.close(fig) inference.create_index() inference.save_index() # delete instance of class del inference # create new instance of the class, which needs to know where we store the index files, # and where we store the trajectories parameters = {'index_directory':index_directory, 'trajectories_filename':name_data} inference = inference(parameters=parameters) inference.load_trajectories() inference.load_index() # upon loading the index, all parameters from the previous instance are recovered: inference.get_parameters() # if the inference is run without an argument, the value N_shift = 1 is used inference_result = inference.run_inference() # = inference.run_inference(N_shift=1) # the call returns a dictionary with the bin centers x, as well as the # inferred diffusivity and drift at those bin centers: x = inference_result['x'] D = inference_result['D'] a = inference_result['a'] # we plot the results, and compare them to the input D and a(x) used for # generating the sample data: fig,axes = plt.subplots(1,2,figsize=(15,6)) fig.subplots_adjust(wspace=0.3) ax = axes[0] ax.set_title('Diffusivity') ax.plot(x,D, label=r'inferred $D(x)$') ax.axhline(1., dashes=[4,4], label='$D$ used to generate sample data', color='black') ax.set_ylim(0.8,1.2) ax.set_xlim(np.min(x),np.max(x)) ax.legend(loc='best') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$D(x)$') ax = axes[1] ax.set_title('Drift') ax.plot(x,a, label=r'inferred $a(x)$') ax.plot(x,-4*2*(x**2-1)*x, dashes=[4,4], label=r'$a(x)$ used to generate sample data', color='black') ax.set_xlim(np.min(x),np.max(x)) ax.legend(loc='best') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$a(x)$') plt.show() plt.close(fig) N_shifts = [1,10,50,100] inference_results = [] for i,N_shift in enumerate(N_shifts): print("Running inference for N_shift = {0}".format(N_shift)) inference_result = inference.run_inference(N_shift=N_shift) inference_results.append(inference_result) fig,axes = plt.subplots(1,2,figsize=(15,6)) fig.subplots_adjust(wspace=0.3) for i, inference_result in enumerate(inference_results): x = inference_result['x'] D = inference_result['D'] a = inference_result['a'] # axes[0].plot(x,D, label=r'inferred $D(x)$, $N_{\mathrm{shift}} = $' + '{0}'.format(N_shifts[i])) axes[1].plot(x,a, label=r'inferred $a(x)$, $N_{\mathrm{shift}} = $' + '{0}'.format(N_shifts[i])) ax = axes[0] ax.set_title('Diffusivity') ax.axhline(1., dashes=[4,4], label='$D$ used to generate sample data', color='black') ax.set_ylim(0.5,1.5) ax.set_xlim(np.min(x),np.max(x)) ax.legend(loc='best') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$D(x)$') ax = axes[1] ax.set_title('Drift') ax.plot(x,-4*2*(x**2-1)*x, dashes=[4,4], label=r'$a(x)$ used to generate sample data', color='black') ax.set_ylim(-30,30) ax.set_xlim(np.min(x),np.max(x)) ax.legend(loc='best') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$a(x)$') plt.show() plt.close(fig)
https://github.com/qiskit-community/Qiskit-Hackathon-at-World-of-QUANTUM
qiskit-community
# Importing all the parts we will need. from typing import List, Optional from qiskit import transpile, QuantumCircuit, QuantumRegister, ClassicalRegister, cAer from qiskit.providers.fake_provider import FakeManilaV2 from qiskit.visualization import plot_histogram import warnings warnings.filterwarnings("ignore") import math pi = math.pi # Your code here: Implementation of the naive solution # Your code here: Implementation of the good solution # Your code here: Use code to show graphs
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw, IQXSimple 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, style=IQXSimple(), backend=FakeBoeblingen())
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import ddt import qiskit.qasm2 from qiskit.test import QiskitTestCase @ddt.ddt class TestLexer(QiskitTestCase): # Most of the lexer is fully exercised in the parser tests. These tests here are really mopping # up some error messages and whatnot that might otherwise be missed. def test_pathological_formatting(self): # This is deliberately _terribly_ formatted, included multiple blanks lines in quick # succession and comments in places you really wouldn't expect to see comments. program = """ OPENQASM // do we really need a comment here? 2.0//and another comment very squished up ; include // this line introduces a file import "qelib1.inc" // this is the file imported ; // this is a semicolon gate // we're making a gate bell( // void, with loose parenthesis in comment ) ) a,// b{h a;cx a //,,,, ,b;} qreg // a quantum register q [ // a square bracket 2];bell q[0],// q[1];creg c[2];measure q->c;""" parsed = qiskit.qasm2.loads(program) expected_unrolled = qiskit.QuantumCircuit( qiskit.QuantumRegister(2, "q"), qiskit.ClassicalRegister(2, "c") ) expected_unrolled.h(0) expected_unrolled.cx(0, 1) expected_unrolled.measure([0, 1], [0, 1]) self.assertEqual(parsed.decompose(), expected_unrolled) @ddt.data("0.25", "00.25", "2.5e-1", "2.5e-01", "0.025E+1", ".25", ".025e1", "25e-2") def test_float_lexes(self, number): program = f"qreg q[1]; U({number}, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [0.25, 0, 0]) def test_no_decimal_float_rejected_in_strict_mode(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] all floats must include a decimal point", ): qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(25e-2, 0, 0) q[0];", strict=True) @ddt.data("", "qre", "cre", ".") def test_non_ascii_bytes_error(self, prefix): token = f"{prefix}\xff" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "encountered a non-ASCII byte"): qiskit.qasm2.loads(token) def test_integers_cannot_start_with_zero(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "integers cannot have leading zeroes" ): qiskit.qasm2.loads("0123") @ddt.data("", "+", "-") def test_float_exponents_must_have_a_digit(self, sign): token = f"12.34e{sign}" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "needed to see an integer exponent" ): qiskit.qasm2.loads(token) def test_non_builtins_cannot_be_capitalised(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "identifiers cannot start with capital" ): qiskit.qasm2.loads("Qubit") def test_unterminated_filename_is_invalid(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "unexpected end-of-file while lexing string literal" ): qiskit.qasm2.loads('include "qelib1.inc') def test_filename_with_linebreak_is_invalid(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "unexpected line break while lexing string literal" ): qiskit.qasm2.loads('include "qe\nlib1.inc";') def test_strict_single_quoted_path_rejected(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] paths must be in double quotes" ): qiskit.qasm2.loads("OPENQASM 2.0; include 'qelib1.inc';", strict=True) def test_version_must_have_word_boundary_after(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version" ): qiskit.qasm2.loads("OPENQASM 2a;") with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version" ): qiskit.qasm2.loads("OPENQASM 2.0a;") def test_no_boundary_float_in_version_position(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float" ): qiskit.qasm2.loads("OPENQASM .5a;") with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float" ): qiskit.qasm2.loads("OPENQASM 0.2e1a;") def test_integers_must_have_word_boundaries_after(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after an integer" ): qiskit.qasm2.loads("OPENQASM 2.0; qreg q[2a];") def test_floats_must_have_word_boundaries_after(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float" ): qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(2.0a, 0, 0) q[0];") def test_single_equals_is_rejected(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"single equals '=' is never valid" ): qiskit.qasm2.loads("if (a = 2) U(0, 0, 0) q[0];") def test_bare_dot_is_not_valid_float(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a numeric fractional part" ): qiskit.qasm2.loads("qreg q[0]; U(2 + ., 0, 0) q[0];") def test_invalid_token(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"encountered '!', which doesn't match" ): qiskit.qasm2.loads("!")
https://github.com/yaleqc/vqe-error-mitigation
yaleqc
# Imports needed for basic no noise VQE simulation import numpy as np import pylab import copy from qiskit import BasicAer from qiskit.aqua import aqua_globals, QuantumInstance from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE from qiskit.aqua.components.optimizers import SLSQP, SPSA from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.drivers import PySCFDriver from qiskit.chemistry.core import Hamiltonian, QubitMappingType # Some deprecated package issue; one warning is enough. import warnings warnings.filterwarnings(action='once') molecule = 'H .0 .0 -{0}; Li .0 .0 {0}' # Define molecule; could be H2 or LiH, etc. distances = np.arange(0.5, 3.75, 0.25) # Distances in Angstrom vqe_energies = [] hf_energies = [] # Hartree-Fock energies exact_energies = [] # Exact energies from numerical diagonalization for i, d in enumerate(distances): print('step', i) # initialize driver driver = PySCFDriver(molecule.format(d/2), basis='sto3g') qmolecule = driver.run() operator = Hamiltonian(qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[-3, -2]) # Approxns needed to make this # problem tractable. qubit_op, aux_ops = operator.run(qmolecule) # exact diagonalization exact_result = NumPyMinimumEigensolver(qubit_op, aux_operators=aux_ops).run() exact_result = operator.process_algorithm_result(exact_result) # VQE optimizer = SLSQP(maxiter=1000) initial_state = HartreeFock(operator.molecule_info['num_orbitals'], operator.molecule_info['num_particles'], qubit_mapping=operator._qubit_mapping, two_qubit_reduction=operator._two_qubit_reduction) var_form = UCCSD(num_orbitals=operator.molecule_info['num_orbitals'], num_particles=operator.molecule_info['num_particles'], initial_state=initial_state, qubit_mapping=operator._qubit_mapping, two_qubit_reduction=operator._two_qubit_reduction) algo = VQE(qubit_op, var_form, optimizer, aux_operators=aux_ops) vqe_result = algo.run(QuantumInstance(BasicAer.get_backend('statevector_simulator'))) vqe_result = operator.process_algorithm_result(vqe_result) exact_energies.append(exact_result.energy) vqe_energies.append(vqe_result.energy) hf_energies.append(vqe_result.hartree_fock_energy) pylab.plot(distances, hf_energies, label='Hartree Fock') pylab.plot(distances, vqe_energies, 'o', label='VQE') pylab.plot(distances, exact_energies, 'x', label='Exact') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('LiH Ground State Energy') pylab.legend(loc='upper right') # Uncomment to save plot! #pylab.savefig('vqe.png', dpi=300)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.wrapper import available_backends, get_backend from qiskit.wrapper import execute as q_execute q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(q,c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) z = 0.995004165 + 1j * 0.099833417 z = z / abs(z) u_error = np.array([[1, 0], [0, z]]) noise_params = {'U': {'gate_time': 1, 'p_depol': 0.001, 'p_pauli': [0, 0, 0.01], 'U_error': u_error } } config = {"noise_params": noise_params} ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config) ret = ret.result() print(ret.get_counts())