repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
import numpy as np import pytest from qiskit import Aer from qiskit.algorithms.gradients import ReverseEstimatorGradient from qiskit.circuit.library import TwoLocal from qiskit.primitives import Estimator from qiskit.quantum_info import SparsePauliOp np.random.seed(0) max_parallel_threads = 12 gpu = False method = "statevector_gpu" def generate_circuit(nqubits): ansatz = TwoLocal( nqubits, ["rx", "ry", "rz"], ["cx"], "linear", reps=3, flatten=True, ).decompose() params = np.random.rand(ansatz.num_parameters) return ansatz, params def execute_statevector(benchmark, circuit, params): backend_options = { "method": method, "precision": "double", "max_parallel_threads": max_parallel_threads, "fusion_enable": True, "fusion_threshold": 14, "fusion_max_qubit": 5, } circuit = circuit.bind_parameters(params) backend = Aer.get_backend("statevector_simulator") backend.set_options(**backend_options) def evalfunc(backend, circuit): backend.run(circuit).result() benchmark(evalfunc, backend, circuit) def execute_estimator(benchmark, circuit, obs, params): estimator = Estimator() def evalfunc(estimator, circuit, obs, params): estimator.run([circuit], [obs], [params]).result() benchmark(evalfunc, estimator, circuit, obs, params) def execute_gradient(benchmark, circuit, obs, params): estimator_grad = ReverseEstimatorGradient() def evalfunc(estimator_grad, circuit, obs, params): estimator_grad.run([circuit], [obs], [params]).result() benchmark(evalfunc, estimator_grad, circuit, obs, params) nqubits_list = range(4, 21) @pytest.mark.parametrize("nqubits", nqubits_list) def test_statevector(benchmark, nqubits): benchmark.group = "qiskit_statevector" circuit, params = generate_circuit(nqubits) execute_statevector(benchmark, circuit, params) # @pytest.mark.parametrize("nqubits", nqubits_list) # def test_estimator(benchmark, nqubits): # benchmark.group = "qiskit_estimator" # circuit, params = generate_circuit(nqubits) # obs = SparsePauliOp.from_list([("Z" * nqubits, 1)]) # execute_estimator(benchmark, circuit, obs, params) # @pytest.mark.parametrize("nqubits", nqubits_list) # def test_gradient(benchmark, nqubits): # benchmark.group = "qiskit_gradient" # circuit, params = generate_circuit(nqubits) # obs = SparsePauliOp.from_list([("Z" * nqubits, 1)]) # execute_gradient(benchmark, circuit, obs, params)
https://github.com/lockwo/Paper-Review
lockwo
from qiskit import IBMQ, Aer, transpile, schedule as build_schedule from qiskit.transpiler import PassManager from qiskit.transpiler.passes.calibration import RZXCalibrationBuilderNoEcho from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import ElectronicStructureDriverType, ElectronicStructureMoleculeDriver from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer from qiskit_nature.operators.second_quantization import FermionicOp from qiskit_nature.mappers.second_quantization import ParityMapper from qiskit_nature.algorithms import GroundStateEigensolver from qiskit.algorithms import NumPyMinimumEigensolver, VQE from qiskit.algorithms.optimizers import SPSA from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.utils import QuantumInstance import matplotlib.pyplot as plt import numpy as np IBMQ.load_account() provider = IBMQ.get_provider() lagos = provider.get_backend('ibm_lagos') def HEA_naive(num_q, depth): circuit = QuantumCircuit(num_q) params = ParameterVector("theta", length=num_q * (3 * depth + 2)) counter = 0 for q in range(num_q): circuit.rx(params[counter], q) counter += 1 circuit.rz(params[counter], q) counter += 1 for d in range(depth): for q in range(num_q - 1): circuit.cx(q, q + 1) for q in range(num_q): circuit.rz(params[counter], q) counter += 1 circuit.rx(params[counter], q) counter += 1 circuit.rz(params[counter], q) counter += 1 return circuit, params def HEA_aware(num_q, depth, hardware): circuit = QuantumCircuit(num_q) params = ParameterVector("theta", length=num_q * (3 * depth + 2)) counter = 0 for q in range(num_q): circuit.rx(params[counter], q) counter += 1 circuit.rz(params[counter], q) counter += 1 for d in range(depth): for q in range(num_q - 1): gate = QuantumCircuit(num_q) gate.rzx(np.pi/2, q, q + 1) pass_ = RZXCalibrationBuilderNoEcho(hardware) qc_cr = PassManager(pass_).run(gate) circuit.compose(qc_cr, inplace=True) for q in range(num_q): circuit.rz(params[counter], q) counter += 1 circuit.rx(params[counter], q) counter += 1 circuit.rz(params[counter], q) counter += 1 return circuit, params depth = 1 qubits = 2 back = lagos circuit, _ = HEA_naive(qubits, depth) t = transpile(circuit, back) schedule = build_schedule(t, back) schedule.draw() circuit, _ = HEA_aware(qubits, depth, back) t = transpile(circuit, back) schedule = build_schedule(t, back) schedule.draw() qubit_converter = QubitConverter(ParityMapper(), two_qubit_reduction=True) numpy_solver = NumPyMinimumEigensolver() spsa = SPSA(100) qi = QuantumInstance(Aer.get_backend('aer_simulator')) vqe_circuit = VQE(ansatz=circuit, quantum_instance=qi, optimizer=spsa) # H2 simulation total_dist = 4 dist = 0.1 incr_early = 0.1 incr_late = 0.3 real_energies = [] vqe_energies = [] dists = [] while dist < total_dist: print(dist, total_dist) molecule = Molecule(geometry=[['H', [0., 0., 0.]], ['H', [0., 0., dist]]]) driver = ElectronicStructureMoleculeDriver(molecule, basis='sto3g', \ driver_type=ElectronicStructureDriverType.PYSCF) es_problem = ElectronicStructureProblem(driver) second_q_ops = es_problem.second_q_ops() if dist == 0.1: FermionicOp.set_truncation(0) print(second_q_ops[0]) FermionicOp.set_truncation(1) print(qubit_converter.convert(second_q_ops[0], num_particles=es_problem.num_particles)) print(es_problem.grouped_property) calc = GroundStateEigensolver(qubit_converter, numpy_solver) res = calc.solve(es_problem) real_energies.append(np.real(res.total_energies[0])) calc = GroundStateEigensolver(qubit_converter, vqe_circuit) res = calc.solve(es_problem) vqe_energies.append(np.real(res.total_energies[0])) dists.append(dist) if dist > total_dist / 2: dist += incr_late else: dist += incr_early plt.plot(dists, real_energies, label='Real', color='red') plt.scatter(dists, vqe_energies, label='VQE', color='black') plt.title("H2") plt.ylim(-1.2, 0.4) plt.xlim(0, 4) plt.xlabel('Angstroms') plt.ylabel('Hartree') plt.legend() plt.show() depth = 2 qubits = 4 circuit, _ = HEA_naive(qubits, depth) spsa = SPSA(100) qi = QuantumInstance(Aer.get_backend('aer_simulator')) vqe_circuit = VQE(ansatz=circuit, quantum_instance=qi, optimizer=spsa) #print(circuit) total_dist = 5 dist = 0.3 incr_early = 0.1 incr_late = 0.3 real_energies = [] vqe_energies = [] dists = [] while dist < total_dist: print(dist, total_dist) molecule = Molecule(geometry=[['Li', [0., 0., 0.]], ['H', [0., 0., dist]]]) driver = ElectronicStructureMoleculeDriver(molecule, basis='sto3g', \ driver_type=ElectronicStructureDriverType.PYSCF) transformer = FreezeCoreTransformer(freeze_core=True, remove_orbitals=[3, 4]) es_problem = ElectronicStructureProblem(driver, transformers=[transformer]) second_q_ops = es_problem.second_q_ops() if dist == 0.3: print(second_q_ops[0]) print(qubit_converter.convert(second_q_ops[0], num_particles=es_problem.num_particles)) print(es_problem.grouped_property) print(es_problem.grouped_property_transformed) calc = GroundStateEigensolver(qubit_converter, numpy_solver) res = calc.solve(es_problem) real_energies.append(np.real(res.total_energies[0])) calc = GroundStateEigensolver(qubit_converter, vqe_circuit) #VQEClient() res = calc.solve(es_problem) vqe_energies.append(np.real(res.total_energies[0])) dists.append(dist) if dist > total_dist / 2: dist += incr_late else: dist += incr_early plt.plot(dists, real_energies, label='Real', color='green') plt.scatter(dists, vqe_energies, label='VQE', color='black') plt.title("LiH") plt.ylim(-8, -6.6) plt.xlim(0.3, 5) plt.xlabel('Angstroms') plt.ylabel('Hartree') plt.legend() plt.show() depth = 2 qubits = 6 circuit, _ = HEA_naive(qubits, depth) spsa = SPSA(100) qi = QuantumInstance(Aer.get_backend('aer_simulator')) vqe_circuit = VQE(ansatz=circuit, quantum_instance=qi, optimizer=spsa) #print(circuit) total_dist = 5 dist = 0.4 incr_early = 0.2 incr_late = 0.4 real_energies = [] vqe_energies = [] dists = [] while dist < total_dist: print(dist, total_dist) molecule = Molecule(geometry=[['H', [0., 0., -dist]], ['Be', [0., 0., 0.]], ['H', [0., 0., dist]]]) driver = ElectronicStructureMoleculeDriver(molecule, basis='sto3g', \ driver_type=ElectronicStructureDriverType.PYSCF) transformer = FreezeCoreTransformer(freeze_core=True, remove_orbitals=[4, 5]) es_problem = ElectronicStructureProblem(driver, transformers=[transformer]) second_q_ops = es_problem.second_q_ops() if dist == 0.4: print(second_q_ops[0]) print(qubit_converter.convert(second_q_ops[0], num_particles=es_problem.num_particles)) print(es_problem.grouped_property) print(es_problem.grouped_property_transformed) calc = GroundStateEigensolver(qubit_converter, numpy_solver) res = calc.solve(es_problem) real_energies.append(np.real(res.total_energies[0])) calc = GroundStateEigensolver(qubit_converter, vqe_circuit) res = calc.solve(es_problem) vqe_energies.append(np.real(res.total_energies[0])) dists.append(dist) if dist > total_dist / 2: dist += incr_late else: dist += incr_early plt.plot(dists, real_energies, label='Real', color='blue') plt.scatter(dists, vqe_energies, label='VQE', color='black') plt.title("BeH2") plt.ylim(-15.7, -12.0) plt.xlim(0.48, 5) plt.xlabel('Angstroms') plt.ylabel('Hartree') plt.legend() plt.show() from qiskit.tools.jupyter import * %qiskit_version_table
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.quantum_info import SparsePauliOp H2_op = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) from qiskit.primitives import Estimator estimator = Estimator() import numpy as np from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SLSQP from qiskit.circuit.library import TwoLocal from qiskit.utils import algorithm_globals # we will iterate over these different optimizers optimizers = [COBYLA(maxiter=80), L_BFGS_B(maxiter=60), SLSQP(maxiter=60)] converge_counts = np.empty([len(optimizers)], dtype=object) converge_vals = np.empty([len(optimizers)], dtype=object) for i, optimizer in enumerate(optimizers): print("\rOptimizer: {} ".format(type(optimizer).__name__), end="") algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE(estimator, ansatz, optimizer, callback=store_intermediate_result) result = vqe.compute_minimum_eigenvalue(operator=H2_op) converge_counts[i] = np.asarray(counts) converge_vals[i] = np.asarray(values) print("\rOptimization complete "); import pylab pylab.rcParams["figure.figsize"] = (12, 8) for i, optimizer in enumerate(optimizers): pylab.plot(converge_counts[i], converge_vals[i], label=type(optimizer).__name__) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence for various optimizers") pylab.legend(loc="upper right"); from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit.opflow import PauliSumOp numpy_solver = NumPyMinimumEigensolver() result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op)) ref_value = result.eigenvalue.real print(f"Reference value: {ref_value:.5f}") pylab.rcParams["figure.figsize"] = (12, 8) for i, optimizer in enumerate(optimizers): pylab.plot( converge_counts[i], abs(ref_value - converge_vals[i]), label=type(optimizer).__name__, ) pylab.xlabel("Eval count") pylab.ylabel("Energy difference from solution reference value") pylab.title("Energy convergence for various optimizers") pylab.yscale("log") pylab.legend(loc="upper right"); from qiskit.algorithms.gradients import FiniteDiffEstimatorGradient estimator = Estimator() gradient = FiniteDiffEstimatorGradient(estimator, epsilon=0.01) algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") optimizer = SLSQP(maxiter=100) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE( estimator, ansatz, optimizer, callback=store_intermediate_result, gradient=gradient ) result = vqe.compute_minimum_eigenvalue(operator=H2_op) print(f"Value using Gradient: {result.eigenvalue.real:.5f}") pylab.rcParams["figure.figsize"] = (12, 8) pylab.plot(counts, values, label=type(optimizer).__name__) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence using Gradient") pylab.legend(loc="upper right"); print(result) cost_function_evals = result.cost_function_evals initial_pt = result.optimal_point estimator1 = Estimator() gradient1 = FiniteDiffEstimatorGradient(estimator, epsilon=0.01) ansatz1 = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") optimizer1 = SLSQP(maxiter=1000) vqe1 = VQE( estimator1, ansatz1, optimizer1, gradient=gradient1, initial_point=initial_pt ) result1 = vqe1.compute_minimum_eigenvalue(operator=H2_op) print(result1) cost_function_evals1 = result1.cost_function_evals print() print( f"cost_function_evals is {cost_function_evals1} with initial point versus {cost_function_evals} without it." ) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/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/ho0-kim/Hamiltonian_Cycle_Problem_with_QC
ho0-kim
import qiskit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute from qiskit.extensions import UnitaryGate from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt import numpy as np # Graph g = np.array([[0,1,1,0,1,1], [1,0,1,0,0,0], [1,1,0,1,0,1], [0,0,1,0,1,1], [1,0,0,1,0,1], [1,0,1,1,1,0]]) # g = np.array([[0, 1, 1, 1, 1], # [1, 0, 1, 1, 1], # [1, 1, 0, 1, 1], # [1, 1, 1, 0, 1], # [1, 1, 1, 1, 0]]) n_vertices = g.shape[0] n_edges = 0 for i in range(n_vertices): n_edges += sum(g[i, i:]) print('number of vertices:', n_vertices) print('number of edges:', n_edges) print('required qubit number:', n_vertices + n_edges + 1) iter = int(np.pi/(4*np.arcsin(1/np.sqrt(2**n_edges))) - 1/2) # iter = np.pi/4 * np.sqrt(2**n_edges) print('Grover iteration:', iter) g_dict = {} # {edge: [vertex1, vertex2]} edge_idx = 0 for i in range(n_vertices): for j in range(i, n_vertices): if g[i,j] == 1: g_dict[edge_idx] = [i, j] edge_idx += 1 g_dict def oracle(qc, qr_v, qr_e, qr_f, n_vertices): # encode for i in g_dict: qc.cry(np.pi/2, qr_e[i], g_dict[i][0]) qc.cry(np.pi/2, qr_e[i], g_dict[i][1]) qc.barrier() # set flag qc.mcx(v, flag) qc.barrier() # inverse for i in g_dict: qc.cry(-np.pi/2, qr_e[i], g_dict[i][0]) qc.cry(-np.pi/2, qr_e[i], g_dict[i][1]) qc.barrier() def diffuser(qc, qr_e, ancilla): qc.h(qr_e) qc.x(qr_e) qc.h(qr_e[-1]) qc.mct(qr_e[:-1], qr_e[-1])#, ancilla_qubits=ancilla) qc.h(qr_e[-1]) qc.x(qr_e) qc.h(qr_e) v = QuantumRegister(n_vertices, name='v') e = QuantumRegister(n_edges, name='e') flag = QuantumRegister(1, name='flag') n_anc = 32-n_vertices-n_edges-1 anc = QuantumRegister(n_anc, name='anc') c = ClassicalRegister(n_edges) qc = QuantumCircuit(v, e, flag, anc, c) qc.h(e) qc.x(flag) qc.h(flag) qc.barrier() iter = 1 for _ in range(iter): oracle(qc, v, e, flag, n_vertices) qc.barrier() diffuser(qc, e, anc) qc.barrier() qc.measure(e, c) qc.draw('mpl') shots = 5012 backend = Aer.get_backend('qasm_simulator') count = execute(qc, backend=backend, shots=shots).result().get_counts() plot_histogram(count) from collections import defaultdict class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited visited = [False] * (max(self.graph) + 1) # Create a queue for BFS queue = [] count = 0 # Mark the source node as # visited and enqueue it queue.append(s) visited[s] = True count += 1 while queue: # Dequeue a vertex from # queue and print it s = queue.pop(0) # Get all adjacent vertices of the # dequeued vertex s. If a adjacent # has not been visited, then mark it # visited and enqueue it for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True count += 1 return count def postprocess(count, g_dict, n_vertices): sorted_count = {k: t for k, t in sorted(count.items(), key=lambda item: item[1], reverse=True)} m = max(sorted_count.values()) filtered_count = {} for k in sorted_count: if sorted_count[k] > m/2+1: filtered_count[k] = sorted_count[k] else: break answer = [] for k in filtered_count.keys(): g = Graph() for i, v in enumerate(k[::-1]): if v == '1': g.addEdge(g_dict[i][0], g_dict[i][1]) if g.BFS(0) == n_vertices: answer.append(k) return answer postprocess(count, g_dict, n_vertices)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # We copy and paste the previous code # # initial case # We assume that the probability of getting head is 1 at the beginning, # becasue Asja will start with one euro. prob_head = 1 prob_tail = 0 number_of_iteration = 10 for i in range(number_of_iteration): # if the last result was head new_prob_head_from_head = prob_head * 0.6 new_prob_tail_from_head = prob_head * 0.4 # if the last result was tail # we know that prob_tail is 0 at the begining # but we still keep these two lines to have the same code for each iteration new_prob_head_from_tail = prob_tail * 0.3 new_prob_tail_from_tail = prob_tail * 0.7 # update the probabilities at the end of coin toss prob_head = new_prob_head_from_head + new_prob_head_from_tail prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail # print prob_head and prob_tail print("the probability of getting head",prob_head) print("the probability of getting tail",prob_tail)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from IPython.display import HTML HTML('<div align="center"><iframe width="560" height="315" align="centre" src="https://www.youtube.com/embed/hOlOY7NyMfs?start=75&end=126" frameborder="0" allowfullscreen></iframe></div>') # Brute force period finding algorithm def find_period_classical(x, N): n = 1 t = x while t != 1: t *= x t %= N n += 1 return n import random, itertools # Sieve of Eratosthenes algorithm def sieve( ): D = { } yield 2 for q in itertools.islice(itertools.count(3), 0, None, 2): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: x = p + q while x in D or not (x&1): x += p D[x] = p # Creates a list of prime numbers up to the given argument def get_primes_sieve(n): return list(itertools.takewhile(lambda p: p<n, sieve())) def get_semiprime(n): primes = get_primes_sieve(n) l = len(primes) p = primes[random.randrange(l)] q = primes[random.randrange(l)] return p*q N = get_semiprime(1000) print("semiprime N =",N) import math def shors_algorithm_classical(N): x = random.randint(0,N) # step one if(math.gcd(x,N) != 1): # step two return x,0,math.gcd(x,N),N/math.gcd(x,N) r = find_period_classical(x,N) # step three while(r % 2 != 0): r = find_period_classical(x,N) p = math.gcd(x**int(r/2)+1,N) # step four, ignoring the case where (x^(r/2) +/- 1) is a multiple of N q = math.gcd(x**int(r/2)-1,N) return x,r,p,q x,r,p,q = shors_algorithm_classical(N) print("semiprime N = ",N,", coprime x = ",x,", period r = ",r,", prime factors = ",p," and ",q,sep="") from qiskit import Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, register, get_backend, compile from qiskit.tools.visualization import plot_histogram, circuit_drawer # qc = quantum circuit, qr = quantum register, cr = classical register, a = 2, 7, 8, 11 or 13 def circuit_amod15(qc,qr,cr,a): if a == 2: qc.cswap(qr[4],qr[3],qr[2]) qc.cswap(qr[4],qr[2],qr[1]) qc.cswap(qr[4],qr[1],qr[0]) elif a == 7: qc.cswap(qr[4],qr[1],qr[0]) qc.cswap(qr[4],qr[2],qr[1]) qc.cswap(qr[4],qr[3],qr[2]) qc.cx(qr[4],qr[3]) qc.cx(qr[4],qr[2]) qc.cx(qr[4],qr[1]) qc.cx(qr[4],qr[0]) elif a == 8: qc.cswap(qr[4],qr[1],qr[0]) qc.cswap(qr[4],qr[2],qr[1]) qc.cswap(qr[4],qr[3],qr[2]) elif a == 11: # this is included for completeness qc.cswap(qr[4],qr[2],qr[0]) qc.cswap(qr[4],qr[3],qr[1]) qc.cx(qr[4],qr[3]) qc.cx(qr[4],qr[2]) qc.cx(qr[4],qr[1]) qc.cx(qr[4],qr[0]) elif a == 13: qc.cswap(qr[4],qr[3],qr[2]) qc.cswap(qr[4],qr[2],qr[1]) qc.cswap(qr[4],qr[1],qr[0]) qc.cx(qr[4],qr[3]) qc.cx(qr[4],qr[2]) qc.cx(qr[4],qr[1]) qc.cx(qr[4],qr[0]) # qc = quantum circuit, qr = quantum register, cr = classical register, a = 2, 7, 8, 11 or 13 def circuit_aperiod15(qc,qr,cr,a): if a == 11: circuit_11period15(qc,qr,cr) return # Initialize q[0] to |1> qc.x(qr[0]) # Apply a**4 mod 15 qc.h(qr[4]) # controlled identity on the remaining 4 qubits, which is equivalent to doing nothing qc.h(qr[4]) # measure qc.measure(qr[4],cr[0]) # reinitialise q[4] to |0> qc.reset(qr[4]) # Apply a**2 mod 15 qc.h(qr[4]) # controlled unitary qc.cx(qr[4],qr[2]) qc.cx(qr[4],qr[0]) # feed forward if cr[0] == 1: qc.u1(math.pi/2.,qr[4]) qc.h(qr[4]) # measure qc.measure(qr[4],cr[1]) # reinitialise q[4] to |0> qc.reset(qr[4]) # Apply a mod 15 qc.h(qr[4]) # controlled unitary. circuit_amod15(qc,qr,cr,a) # feed forward if cr[1] == 1: qc.u1(math.pi/2.,qr[4]) if cr[0] == 1: qc.u1(math.pi/4.,qr[4]) qc.h(qr[4]) # measure qc.measure(qr[4],cr[2]) def circuit_11period15(qc,qr,cr): # Initialize q[0] to |1> qc.x(qr[0]) # Apply a**4 mod 15 qc.h(qr[4]) # controlled identity on the remaining 4 qubits, which is equivalent to doing nothing qc.h(qr[4]) # measure qc.measure(qr[4],cr[0]) # reinitialise q[4] to |0> qc.reset(qr[4]) # Apply a**2 mod 15 qc.h(qr[4]) # controlled identity on the remaining 4 qubits, which is equivalent to doing nothing # feed forward if cr[0] == 1: qc.u1(math.pi/2.,qr[4]) qc.h(qr[4]) # measure qc.measure(qr[4],cr[1]) # reinitialise q[4] to |0> qc.reset(qr[4]) # Apply 11 mod 15 qc.h(qr[4]) # controlled unitary. qc.cx(qr[4],qr[3]) qc.cx(qr[4],qr[1]) # feed forward if cr[1] == 1: qc.u1(math.pi/2.,qr[4]) if cr[0] == 1: qc.u1(math.pi/4.,qr[4]) qc.h(qr[4]) # measure qc.measure(qr[4],cr[2]) q = QuantumRegister(5, 'q') c = ClassicalRegister(5, 'c') shor = QuantumCircuit(q, c) circuit_aperiod15(shor,q,c,7) backend = Aer.get_backend('qasm_simulator') sim_job = execute([shor], backend) sim_result = sim_job.result() sim_data = sim_result.get_counts(shor) plot_histogram(sim_data)
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
# 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/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Checking the version of PYTHON; we only support 3 at the moment import sys if sys.version_info < (3,0): raise Exception('Please use Python version 3 or greater.') # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np import time from pprint import pprint # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram #import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram QPS_SPECS = { 'circuits': [{ 'name': 'W_states', 'quantum_registers': [{ 'name':'q', 'size':5 }], 'classical_registers': [{ 'name':'c', 'size':5 }]}], } Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) "Choice of the backend" # The flag_qx2 must be "True" for using the ibmqx2. # "True" is also better when using the simulator (shorter circuit) #backend = 'ibmqx2' #backend = 'ibmqx4' backend = 'local_qasm_simulator' #backend = 'ibmqx_hpc_qasm_simulator' flag_qx2 = True if backend == 'ibmqx4': flag_qx2 = False print("Your choice for the backend is: ", backend, "flag_qx2 is: ", flag_qx2) # Here, two useful routine # Define a F_gate def F_gate(circ,q,i,j,n,k) : theta = np.arccos(np.sqrt(1/(n-k+1))) circ.ry(-theta,q[j]) circ.cz(q[i],q[j]) circ.ry(theta,q[j]) circ.barrier(q[i]) # Define the cxrv gate which uses reverse CNOT instead of CNOT def cxrv(circ,q,i,j) : circ.h(q[i]) circ.h(q[j]) circ.cx(q[j],q[i]) circ.h(q[i]) circ.h(q[j]) circ.barrier(q[i],q[j]) # 3-qubit W state Step 1 Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 for i in range(3) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 3-qubit (step 1) on', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 3-qubit (step 1) on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states')) # 3-qubit W state, first and second steps Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 F_gate(W_states,q,1,0,3,2) # Applying F23 for i in range(3) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 3-qubit (steps 1 + 2) on', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 3-qubit (steps 1 + 2) on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states')) # 3-qubit W state Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 F_gate(W_states,q,1,0,3,2) # Applying F23 if flag_qx2 : # option ibmqx2 W_states.cx(q[1],q[2]) # cNOT 21 W_states.cx(q[0],q[1]) # cNOT 32 else : # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) for i in range(3) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 3-qubit on', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 3-qubit on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states')) # 4-qubit W state Q_program = QuantumProgram(specs=QPS_SPECS) # Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[3]) #start is |1000> F_gate(W_states,q,3,2,4,1) # Applying F12 F_gate(W_states,q,2,1,4,2) # Applying F23 F_gate(W_states,q,1,0,4,3) # Applying F34 cxrv(W_states,q,2,3) # cNOT 21 if flag_qx2 : # option ibmqx2 W_states.cx(q[1],q[2]) # cNOT 32 W_states.cx(q[0],q[1]) # cNOT 43 else : # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) for i in range(4) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 4-qubit ', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 4-qubit on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states')) # 5-qubit W state Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[4]) #start is |10000> F_gate(W_states,q,4,3,5,1) # Applying F12 F_gate(W_states,q,3,2,5,2) # Applying F23 F_gate(W_states,q,2,1,5,3) # Applying F34 F_gate(W_states,q,1,0,5,4) # Applying F45 W_states.cx(q[3],q[4]) # cNOT 21 cxrv(W_states,q,2,3) # cNOT 32 if flag_qx2 : # option ibmqx2 W_states.cx(q[1],q[2]) # cNOT 43 W_states.cx(q[0],q[1]) # cNOT 54 else : # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) for i in range(5) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 5-qubit on', backend, "N=", shots,time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=1200) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 5-qubit on', backend, "N=", shots,time_exp) plot_histogram(result.get_counts('W_states'))
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())
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
# -*- coding: utf-8 -*- """ Created on Mon May 31 22:57:39 2021 @author: nbaldelli """ import time import itertools import numpy as np from scipy.optimize import minimize, basinhopping from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP from qiskit.algorithms import VQE from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.opflow import CircuitSampler from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.utils import QuantumInstance from qiskit.ignis.mitigation.measurement import CompleteMeasFitter,complete_meas_cal from modules.utils import * import qiskit from qiskit import IBMQ #%% IBMQ.load_account() # Load account from disk IBMQ.providers() # List all available providers provider = IBMQ.get_provider(hub='ibm-q') print(provider.backends) real_backend = provider.backends(simulator=False, operational=True)[6] L=5 mag = QMag(L,-1) #magnetization operator (Qiskit) ~StateFn(mag) gx_vals = np.logspace(-2,2,10)[::-1] opt_params_noiseless=[] opt_params_noisy=[] Qmags=np.zeros(len(gx_vals)) load=False ############################################################################## #NOISY SIMULATION backend = qiskit.providers.aer.AerSimulator.from_backend(real_backend) coupling_map = backend.configuration().coupling_map noise_model = NoiseModel.from_backend(backend) optimizer = SPSA(maxiter=1000) reps=1 ansatz = qiskit.circuit.library.EfficientSU2(L, reps=reps) # ansatz = qiskit.circuit.library.TwoLocal(L,rotation_blocks="ry", entanglement_blocks=entanglement_blocks, entanglement=entanglement, reps=reps) ansatz.draw("mpl") q_instance = QuantumInstance(backend, coupling_map=coupling_map, noise_model=noise_model, measurement_error_mitigation_cls=CompleteMeasFitter, cals_matrix_refresh_period=30 ) gz=1e-3 filename = f'data/params_VQE_Ising_L{L:.0f}_anti_N_reps{reps}_gz{gz}.npz' ##%% if load==False: for i,gx in enumerate(gx_vals): print('gx: %.2f' %(gx)) if i != 0: vqe = VQE(ansatz=ansatz, initial_point = opt_params_noisy[-1], optimizer=optimizer, quantum_instance=q_instance) else: vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=q_instance) H = QHIsing(L,-1,np.float32(gx),np.float32(gz)) result = vqe.compute_minimum_eigenvalue(H) #ED with Qiskit VQE opt_params_noisy.append(sort_params(result.optimal_parameters)) np.savez(filename, opt_params=opt_params_noisy)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit import Measure from qiskit.circuit.library import HGate, CXGate qr = QuantumRegister(2) cr = ClassicalRegister(2) instructions = [ CircuitInstruction(HGate(), [qr[0]], []), CircuitInstruction(CXGate(), [qr[0], qr[1]], []), CircuitInstruction(Measure(), [qr[0]], [cr[0]]), CircuitInstruction(Measure(), [qr[1]], [cr[1]]), ] circuit = QuantumCircuit.from_instructions(instructions) circuit.draw("mpl")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # A quantum circuit is composed by quantum and classical bits. # # here are the objects that we use to create a quantum circuit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # we use a quantum register to keep our quantum bits. qreg = QuantumRegister(1) # in this example we will use a single quantum bit # To get an information from a quantum bit, it must be measured. (More details will appear.) # The measurement result is stored classically. # Therefore, we also use a classical regiser with classical bits creg = ClassicalRegister(1) # in this example we will use a single classical bit # now we can define our quantum circuit # it is composed by a quantum and a classical register mycircuit = QuantumCircuit(qreg,creg) # we apply operators on quantum bits # operators are also called as gates # we apply NOT operator represented as "x" # operator is a part of the circuit, and we should specify the quantum bit as the parameter mycircuit.x(qreg[0]) # (quantum) bits are enumerated starting from 0 # NOT operator or x-gate is applied to the first qubit of the quantum register # let's run our codes until now, and then draw our circuit print("Everything looks fine, let's continue ...") # we use matplotlib_circuit_drawer # we shortly refer it as "drawer" in our codes from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # let's draw our circuit now drawer(mycircuit) # re-execute me if you DO NOT see the circuit diagram # measurement is defined by associating a quantum bit to a classical bit mycircuit.measure(qreg[0],creg[0]) # the result will be stored in the classical bit print("Everything looks fine, let's continue ...") # let's draw the circuit again to see how the measurement is defined drawer(mycircuit) # reexecute me if you DO NOT see the circuit diagram # we are done with design of our circuit # now we can execute it # we execute quantum circuits many times (WHY?) # we use method "execute" and object "Aer" from qiskit library from qiskit import execute, Aer # we create a job object for execution of the circuit # there are three parameters # 1. mycircuit # 2. beckend on which it will be executed: we will use local simulator # 3. how_many_times will it be executed, let's pick it as 1024 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1024) # we can get the result of the outcome as follows counts = job.result().get_counts(mycircuit) print(counts) # usually quantum programs produce probabilistic outcomes # # My second quantum circuit # # we import all at once from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # we will use 4 quantum bits and 4 classical bits qreg2 = QuantumRegister(4) creg2 = ClassicalRegister(4) mycircuit2 = QuantumCircuit(qreg2,creg2) # I will apply x-gate to the first quantum bit twice mycircuit2.x(qreg2[0]) mycircuit2.x(qreg2[0]) # I will apply x-gate to the fourth quantum bit once mycircuit2.x(qreg2[3]) # I will apply x-gate to the third quantum bit three times mycircuit2.x(qreg2[2]) mycircuit2.x(qreg2[2]) mycircuit2.x(qreg2[2]) # I will apply x-gate to the second quantum bit four times mycircuit2.x(qreg2[1]) mycircuit2.x(qreg2[1]) mycircuit2.x(qreg2[1]) mycircuit2.x(qreg2[1]) # if the size of quantum and classical registers are the same, we can define measurements with a single line code mycircuit2.measure(qreg2,creg2) # then each quantum bit and classical bit is associated with respect to their indices # let's run our codes until now, and then draw our circuit print("Everything looks fine, let's continue ...") drawer(mycircuit2) # re-execute me if you DO NOT see the circuit diagram job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=500) counts = job.result().get_counts(mycircuit2) print(counts) def print_outcomes(counts): # takes a dictionary variable for outcome in counts: # for each key-value in dictionary reverse_outcome = '' for i in outcome: # each string can be considered as a list of characters reverse_outcome = i + reverse_outcome # each new symbol comes before the old symbol(s) print(reverse_outcome,"is observed",counts[outcome],"times") job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=1024) counts = job.result().get_counts(mycircuit2) # counts is a dictionary object in python print_outcomes(counts) from random import randrange n = 20 r=randrange(n) # pick a number from the list {0,1,...,n-1} print(r) # test this method by using a loop for i in range(10): print(randrange(n)) # # your solution is here #
https://github.com/abbarreto/qiskit4
abbarreto
from qiskit import * import numpy as np import math import qiskit nshots = 8192 IBMQ.load_account() #provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_belem') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter dth = math.pi/10 th = np.arange(0,math.pi+dth,dth) ph = 0; lb = 0 N = len(th) F_the = np.zeros(N); F_sim = np.zeros(N); F_exp = np.zeros(N) for j in range(0,N): F_the[j] = math.cos(th[j]/2)**2 qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.u(th[j],ph,lb,qr[2]) qc.h(qr[0]) qc.cswap(qr[0],qr[1],qr[2]) qc.h(qr[0]) qc.measure(qr[0],cr[0]) job_sim = execute(qc, backend=simulator, shots=nshots) counts = job_sim.result().get_counts(qc) if '0' in counts: F_sim[j] = 2*counts['0']/nshots - 1 job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts = job_exp.result().get_counts(qc) if '0' in counts: F_exp[j] = 2*counts['0']/nshots - 1 qc.draw('mpl') qc.decompose().decompose().draw('mpl') # o circuito é "profundo" por causa da swap controlada F_the, F_sim, F_exp from matplotlib import pyplot as plt plt.plot(th, F_the, label=r'$F_{the}$') plt.plot(th, F_sim, '*', label=r'$F_{sim}$') plt.plot(th, F_exp, 'o', label=r'$F_{exp}$') plt.xlabel(r'$\theta$') plt.legend() plt.show()
https://github.com/jlapeyre/Qurt.jl
jlapeyre
# This "activates" the project environment of the package `Qurt`. Normally you would use `Qurt` # from an environment external to the package. import Pkg Pkg.activate("."); # Now `Qurt` should be visible. # `import` imports the package, but no other symbols. import Qurt # Names of objects that are not imported are printed fully qualified, which is verbose. # So import more only so names are not printed fully qualified. import Graphs.SimpleGraphs.SimpleDiGraph import Qurt.NodeStructs.Node using BenchmarkTools # This provides tools like Python %timeit # `using` is similar to `import`. But this invocation imports all of the symbols on the export list of # `Qurt.Circuits` using Qurt.Circuits using Qurt.Interface # many symbols go here as a catch all. They may live elsewhere in the future. qc = Circuit(2, 2) using Qurt.IOQDAGs print_edges(qc) propertynames(qc) typeof(qc.graph) # digraph from `Graphs.jl` qc.nodes using Qurt.Builders import .Qurt.Elements: H, CX, X, Y, RX (nH, nCX) = @build qc H(1) CX(1,2); print_edges(qc) qc[nCX] qc.nodes.element Integer(qc.nodes.element[1]) import .Interface.getelement getelement(qc, 1) # This is currently a way to access the element @btime getelement($qc, 1) # Dollar sign is a detail of how @btime works @btime $qc.nodes.element[1] # This is no more or less efficient qc = Circuit(2) @build qc X(1) Y(2) @build qc begin X(1) Y(2) CX(1,2) RX{1.5}(1) end; g1 = @gate RX g2 = @gate RX{1.5} # circuit element identity and parameters g3 = @gate RX{1.5}(2) # Include wires add_node!(qc, (g1, 1.5), (2,)) add_node!(qc, g2, (2,)) add_node!(qc, g3) (qc[11:13])
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
total1 = 0 total2 = 0 for i in range(3,52,3): total1 = total1 + i total2 += i # shorter form print("The summation is",total1) print("The summation is",total2) T = 0 current_number = 1 for i in range(9): T = T + current_number print("3 to",i,"is",current_number) current_number = 3 * current_number print("summation is",T) # Python has also exponent operator: ** # we can also directly use it T = 0 for i in range(9): print("3 to",i,"is",3**i) T = T + 3 ** i print("summation is",T) T = 0 n = 2 # this value iteratively will be first halved and then added to the summation T how_many_terms = 0 while T<=1.99: n = n/2 # half the value of n print("n = ",n) T = T + n # update the value of T how_many_terms = how_many_terms + 1 print("T = ",T) print("how many terms in the summation:",how_many_terms) # our result says that there should be 8 terms in our summation # let's calculate the summations of the first seven and eight terms, and verify our results T7 = 0 n = 2 # this value iteratively will be first halved and then added to the summation for i in range(7): n = n/2 print("n =",n) T7 = T7 + n print("the summation of the first seven terms is",T7) T8 = 0 n = 2 # this value iteratively will be first halved and then added to the summation for i in range(8): n = n/2 print("n =",n) T8 = T8 + n print("the summation of the first eight terms is",T8) print("(the summation of the first seven terms is",T7,")") from random import randrange r = 0 attempt = 0 while r != 3: # the loop iterates as long as r is not equal to 3 r = randrange(10) # randomly pick a number attempt = attempt + 1 # increase the number of attempts by 1 print (attempt,"->",r) # print the number of attempt and the randomly picked number print("total number of attempt(s) is",attempt) # be aware of single and double indentions number_of_execution = 2000 # change this with 200, 2000, 20000, 200000 and reexecute this cell total_attempts = 0 from random import randrange for i in range(number_of_execution): # the outer loop iterates number_of_execution times r = 0 attempt = 0 while r != 3: # the while-loop iterates as long as r is not equal to 3 r = randrange(10) # randomly pick a number attempt = attempt + 1 # increase the number of attempts by 1 # I am out of scope of while-loop total_attempts = total_attempts + attempt # update the total number of attempts # I am out of scope of for-loop print(number_of_execution,"->",total_attempts/number_of_execution) # let's use triple nested loops for number_of_execution in [20,200,2000,20000,200000]: # we will use the same code by indenting all lines by one more level total_attempts = 0 for i in range(number_of_execution): # the middle loop iterates number_of_execution times r = 0 attempt = 0 while r != 3: # the while-loop iterates as long as r is not equal to 3 r = randrange(10) # randomly pick a number attempt = attempt + 1 # increase the number of attempts by 1 # I am out of scope of while-loop total_attempts = total_attempts + attempt # update the total number of attempts # I am out of scope of for-loop print(number_of_execution,"->",total_attempts/number_of_execution) # you can include 2 million to the list, but you should WAIT for a while to see the result # can your computer compete with exponential growth? # if you think "yes", please try 20 million, 200 million, and so on
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### added y gate ### qc.y(0) qc.h(1) return qc
https://github.com/JayantiSingh/Quant_co_Qiskit
JayantiSingh
import pennylane as qml from pennylane import numpy as np from pennylane.optimize import NesterovMomentumOptimizer import qiskit import matplotlib.pyplot as plt from qiskit.tools.visualization import matplotlib_circuit_drawer as draw dev = qml.device("default.qubit", wires=2) def get_angles(x): beta0 = 2 * np.arcsin(np.sqrt(x[1] ** 2) / np.sqrt(x[0] ** 2 + x[1] ** 2 + 1e-12)) beta1 = 2 * np.arcsin(np.sqrt(x[3] ** 2) / np.sqrt(x[2] ** 2 + x[3] ** 2 + 1e-12)) beta2 = 2 * np.arcsin( np.sqrt(x[2] ** 2 + x[3] ** 2) / np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2 + x[3] ** 2) ) return np.array([beta2, -beta1 / 2, beta1 / 2, -beta0 / 2, beta0 / 2]) def statepreparation(a): qml.RY(a[0], wires=0) qml.CNOT(wires=[0, 1]) qml.RY(a[1], wires=1) qml.CNOT(wires=[0, 1]) qml.RY(a[2], wires=1) qml.PauliX(wires=0) qml.CNOT(wires=[0, 1]) qml.RY(a[3], wires=1) qml.CNOT(wires=[0, 1]) qml.RY(a[4], wires=1) qml.PauliX(wires=0) def layer(W): qml.Rot(W[0, 0], W[0, 1], W[0, 2], wires=0) qml.Rot(W[1, 0], W[1, 1], W[1, 2], wires=1) qml.CNOT(wires=[0, 1]) @qml.qnode(dev) def circuit(weights, angles=None): statepreparation(angles) for W in weights: layer(W) return qml.expval(qml.PauliZ(0)) def variational_classifier(var, angles=None): weights = var[0] bias = var[1] return circuit(weights, angles=angles) + bias def square_loss(labels, predictions): loss = 0 for l, p in zip(labels, predictions): loss = loss + (l - p) ** 2 loss = loss / len(labels) return loss def cost(weights, features, labels): predictions = [variational_classifier(weights, angles=f) for f in features] return square_loss(labels, predictions) def accuracy(labels, predictions): loss = 0 for l, p in zip(labels, predictions): if abs(l - p) < 1e-5: loss = loss + 1 loss = loss / len(labels) return loss data = np.loadtxt('iris_classes1and2_scaled.txt') X = data[:, 0:2] print("First X sample (original) :", X[0]) padding = 0.3 * np.ones((len(X), 1)) X_pad = np.c_[np.c_[X, padding], np.zeros((len(X), 1))] print("First X sample (padded) :", X_pad[0]) normalization = np.sqrt(np.sum(X_pad ** 2, -1)) X_norm = (X_pad.T / normalization).T print("First X sample (normalized):", X_norm[0]) features = np.array([get_angles(x) for x in X_norm]) print("First features sample :", features[0]) Y = data[:, -1] import matplotlib.pyplot as plt plt.figure() plt.scatter(X[:, 0][Y == 1], X[:, 1][Y == 1], c="r", marker="o", edgecolors="k") plt.scatter(X[:, 0][Y == -1], X[:, 1][Y == -1], c="b", marker="o", edgecolors="k") plt.title("Original data") plt.show() plt.figure() dim1 = 0 dim2 = 1 plt.scatter(X_norm[:, dim1][Y == 1], X_norm[:, dim2][Y == 1], c="r", marker="o", edgecolors="k") plt.scatter(X_norm[:, dim1][Y == -1], X_norm[:, dim2][Y == -1], c="b", marker="o", edgecolors="k") plt.title("Padded and normalised data (dims {} and {})".format(dim1, dim2)) plt.show() plt.figure() dim1 = 0 dim2 = 3 plt.scatter(features[:, dim1][Y == 1], features[:, dim2][Y == 1], c="r", marker="o", edgecolors="k") plt.scatter( features[:, dim1][Y == -1], features[:, dim2][Y == -1], c="b", marker="o", edgecolors="k" ) plt.title("Feature vectors (dims {} and {})".format(dim1, dim2)) plt.show() np.random.seed(0) num_data = len(Y) num_train = int(0.75 * num_data) index = np.random.permutation(range(num_data)) feats_train = features[index[:num_train]] Y_train = Y[index[:num_train]] feats_val = features[index[num_train:]] Y_val = Y[index[num_train:]] X_train = X[index[:num_train]] X_val = X[index[num_train:]] num_qubits = 2 num_layers = 6 var_init = (0.01 * np.random.randn(num_layers, num_qubits, 3), 0.0) opt = NesterovMomentumOptimizer(0.01) batch_size = 5 var = var_init for it in range(60): batch_index = np.random.randint(0, num_train, (batch_size,)) feats_train_batch = feats_train[batch_index] Y_train_batch = Y_train[batch_index] var = opt.step(lambda v: cost(v, feats_train_batch, Y_train_batch), var) predictions_train = [np.sign(variational_classifier(var, angles=f)) for f in feats_train] predictions_val = [np.sign(variational_classifier(var, angles=f)) for f in feats_val] acc_train = accuracy(Y_train, predictions_train) acc_val = accuracy(Y_val, predictions_val) print( "Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} " "".format(it + 1, cost(var, features, Y), acc_train, acc_val) ) plt.figure() cm = plt.cm.RdBu xx, yy = np.meshgrid(np.linspace(0.0, 1.5, 20), np.linspace(0.0, 1.5, 20)) X_grid = [np.array([x, y]) for x, y in zip(xx.flatten(), yy.flatten())] padding = 0.3 * np.ones((len(X_grid), 1)) X_grid = np.c_[np.c_[X_grid, padding], np.zeros((len(X_grid), 1))] normalization = np.sqrt(np.sum(X_grid ** 2, -1)) X_grid = (X_grid.T / normalization).T features_grid = np.array( [get_angles(x) for x in X_grid] ) predictions_grid = [variational_classifier(var, angles=f) for f in features_grid] Z = np.reshape(predictions_grid, xx.shape) cnt = plt.contourf(xx, yy, Z, levels=np.arange(-1, 1.1, 0.1), cmap=cm, alpha=0.8, extend="both") plt.contour(xx, yy, Z, levels=[0.0], colors=("black",), linestyles=("--",), linewidths=(0.8,)) plt.colorbar(cnt, ticks=[-1, 0, 1]) plt.scatter( X_train[:, 0][Y_train == 1], X_train[:, 1][Y_train == 1], c="b", marker="o", edgecolors="k", label="class 1 train", ) plt.scatter( X_val[:, 0][Y_val == 1], X_val[:, 1][Y_val == 1], c="b", marker="^", edgecolors="k", label="class 1 validation", ) plt.scatter( X_train[:, 0][Y_train == -1], X_train[:, 1][Y_train == -1], c="r", marker="o", edgecolors="k", label="class -1 train", ) plt.scatter( X_val[:, 0][Y_val == -1], X_val[:, 1][Y_val == -1], c="r", marker="^", edgecolors="k", label="class -1 validation", ) plt.legend() plt.show()
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram # Create a quantum circuit with 2 qubits # The default initial state of qubits will be |0> or [1,0] qc = QuantumCircuit(2) #Applying the hadarmad gate to target qc.h(1) #apply the cx gate to both qubits qc.cx(0,1) #Applying the hadarmad gate to target qc.h(1) #Draw the circuit qc.draw('mpl') #Get the backend for the circuit to display unitary matrix backend = Aer.get_backend('unitary_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_unitary() #import qiskit_textbook and display the combined unitary matrix from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ") #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_statevector() #import qiskit_textbook and display the statevector #from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{Statevector} = ") #execute the circuit and get the plain result out = execute(qc,backend).result() #getting the count of the result counts = out.get_counts() #plotting the histogram plot_histogram(counts)
https://github.com/IceKhan13/QiskitFlow
IceKhan13
import qiskit import numpy as np from math import sqrt,pi from qiskit import * from qiskit.visualization import * from qiskit.extensions import Initialize from qiskit.quantum_info import * import time from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import * import math import datetime # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qc = QuantumCircuit(1) # Create a quantum circuit with one qubit psi = [1/sqrt(2),1/sqrt(2)] # Define initial_state in a superposition state initial_state =Initialize(psi) qc.append(initial_state, [0]) # Apply initialisation operation to the 0th qubit result = execute(qc,Aer.get_backend('statevector_simulator')).result() # Do the simulation, returning the result exp_state = result.get_statevector(qc) print(exp_state) # Display the output state vector qr = QuantumRegister(3) cr = ClassicalRegister(1) circuit = QuantumCircuit(qr,cr) circuit.append(initial_state,[0]) circuit.barrier() circuit.h(qr[1]) circuit.cx(qr[1],qr[2]) circuit.barrier() circuit.cx(qr[0],qr[1]) circuit.h(qr[0]) circuit.barrier() circuit.cz(qr[0],qr[2]) circuit.cx(qr[1],qr[2]) #inverse_init_gate = initial_state.gates_to_uncompute() #circuit.append(inverse_init_gate,[2]) circuit.measure(qr[2],cr) circuit.draw() t =time.time() backend = Aer.get_backend('qasm_simulator') job_circuit= execute(circuit,backend=backend,shots=1) device_counts = job_circuit.result().get_counts(circuit) job_monitor(job_circuit) print(job_circuit.job_id()) print('Time taken:', time.time()-t) qc = QuantumRegister(3) #cr = ClassicalRegister(1) circuit = QuantumCircuit(qc) circuit.append(initial_state,[0]) circuit.barrier() circuit.h(qc[1]) circuit.cx(qc[1],qc[2]) circuit.barrier() circuit.cx(qc[0],qc[1]) circuit.h(qc[0]) circuit.barrier() circuit.cz(qc[0],qc[2]) circuit.cx(qc[1],qc[2]) #inverse_init_gate = initial_state.gates_to_uncompute() #circuit.append(inverse_init_gate,[2]) #circuit.measure(qr[2],cr) circuit.draw() t = time.time() qst_circuit = state_tomography_circuits(circuit,qc[2]) job_circuit = execute(qst_circuit,backend=backend,shots=8192) job_monitor(job_circuit) print(job_circuit.job_id()) print('Time taken:', time.time()-t) tomo_circuit = StateTomographyFitter(job_circuit.result(),qst_circuit) tomo_circuit.data rho_circuit = tomo_circuit.fit() print(rho_circuit) F_state = state_fidelity(exp_state,rho_circuit) print('Fit_fidelity_state:',F_state) plot_state_city(rho_circuit) pur = purity(rho_circuit) print(pur)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import ( ElectronicStructureDriverType, ElectronicStructureMoleculeDriver, PySCFDriver, ) from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer from qiskit_nature.settings import settings settings.dict_aux_operators = True molecule = Molecule( geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1 ) driver = ElectronicStructureMoleculeDriver( molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF ) # or equivalently: driver = PySCFDriver.from_molecule(molecule, basis="sto3g") transformer = FreezeCoreTransformer() problem = ElectronicStructureProblem(driver, transformers=[transformer]) # Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so: second_q_ops = problem.second_q_ops() hamiltonian = second_q_ops["ElectronicEnergy"] print(hamiltonian) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo from qiskit_nature.second_q.transformers import FreezeCoreTransformer molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1) driver = PySCFDriver.from_molecule(molecule, basis="sto3g") # this is now done explicitly problem = driver.run() transformer = FreezeCoreTransformer() # and you also apply transformers explicitly problem = transformer.transform(problem) hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver molecule = Molecule( geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1 ) driver = PySCFDriver.from_molecule(molecule) result = driver.run() print(type(result)) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1) driver = PySCFDriver.from_molecule(molecule, basis="sto3g") result = driver.run() print(type(result)) from qiskit_nature.drivers.second_quantization import FCIDumpDriver path_to_fcidump = "aux_files/h2.fcidump" driver = FCIDumpDriver(path_to_fcidump) result = driver.run() print(type(result)) from qiskit_nature.second_q.formats.fcidump import FCIDump path_to_fcidump = "aux_files/h2.fcidump" fcidump = FCIDump.from_file(path_to_fcidump) print(type(fcidump)) from qiskit_nature.second_q.formats.fcidump_translator import fcidump_to_problem problem = fcidump_to_problem(fcidump) print(type(problem)) from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer transformer = FreezeCoreTransformer() driver = PySCFDriver() transformed_result = transformer.transform(driver.run()) print(type(transformed_result)) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.transformers import FreezeCoreTransformer transformer = FreezeCoreTransformer() driver = PySCFDriver() transformed_result = transformer.transform(driver.run()) print(type(transformed_result)) from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer driver = PySCFDriver() transformer = FreezeCoreTransformer() problem = ElectronicStructureProblem(driver, transformers=[transformer]) # we trigger driver.run() implicitly like so: second_q_ops = problem.second_q_ops() hamiltonian_op = second_q_ops.pop("ElectronicEnergy") aux_ops = second_q_ops from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.transformers import FreezeCoreTransformer driver = PySCFDriver() problem = driver.run() transformer = FreezeCoreTransformer() problem = transformer.transform(problem) hamiltonian_op, aux_ops = problem.second_q_ops() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Checking the version of PYTHON; we only support > 3.5 import sys if sys.version_info < (3,5): raise Exception('Please use Python version 3.5 or greater.') from qiskit import QuantumProgram import math #import Qconfig #Define a QuantumProgram object Q_program = QuantumProgram() #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) pi = math.pi def solve_linear_sys(): #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # create Quantum Register called "qr" with 4 qubits qr = Q_program.create_quantum_register("qr", 4) # create Quantum Register called "cr" with 4 qubits cr = Q_program.create_classical_register("cr", 4) # Creating Quantum Circuit called "qc" involving your Quantum Register "qr" # and your Classical Register "cr" qc = Q_program.create_circuit("solve_linear_sys", [qr], [cr]) # Initialize times that we get the result vector n0 = 0 n1 = 0 for i in range(10): #Set the input|b> state" qc.x(qr[2]) #Set the phase estimation circuit qc.h(qr[0]) qc.h(qr[1]) qc.u1(pi, qr[0]) qc.u1(pi/2, qr[1]) qc.cx(qr[1], qr[2]) #The quantum inverse Fourier transform qc.h(qr[0]) qc.cu1(-pi/2, qr[0], qr[1]) qc.h(qr[1]) #R(lamda^-1) Rotation qc.x(qr[1]) qc.cu3(pi/16, 0, 0, qr[0], qr[3]) qc.cu3(pi/8, 0, 0, qr[1], qr[3]) #Uncomputation qc.x(qr[1]) qc.h(qr[1]) qc.cu1(pi/2, qr[0], qr[1]) qc.h(qr[0]) qc.cx(qr[1], qr[2]) qc.u1(-pi/2, qr[1]) qc.u1(-pi, qr[0]) qc.h(qr[1]) qc.h(qr[0]) # To measure the whole quantum register qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) qc.measure(qr[3], cr[3]) result = Q_program.execute("solve_linear_sys", shots=8192, backend='local_qasm_simulator') # Get the sum og all results n0 = n0 + result.get_data("solve_linear_sys")['counts']['1000'] n1 = n1 + result.get_data("solve_linear_sys")['counts']['1100'] # print the result print(result) print(result.get_data("solve_linear_sys")) # Reset the circuit qc.reset(qr) # calculate the scale of the elements in result vectot and print it. p = n0/n1 print(n0) print(n1) print(p) # The test function if __name__ == "__main__": solve_linear_sys() %run "../version.ipynb"
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) # You can reverse the order of the qubits. from qiskit.quantum_info import DensityMatrix qc = QuantumCircuit(2) qc.h([0, 1]) qc.t(1) qc.s(0) qc.cx(0,1) matrix = DensityMatrix(qc) plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# I am a comment in python print("Hello From Quantum World :-)") # please run me from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from random import randrange # Create my circuit and register objects qreg = QuantumRegister(2) # my quantum register creg = ClassicalRegister(2) # my classical register circuit = QuantumCircuit(qreg,creg) # my quantum circuit # let's apply a Hadamard gate to the first qubit circuit.h(qreg[0]) # let's set the second qubit to |1> circuit.x(qreg[1]) # let's apply CNOT(first_qubit,second_qubit) circuit.cx(qreg[0],qreg[1]) # let's measure the both qubits circuit.measure(qreg,creg) print("The execution was completed, and the circuit was created :)") ## execute the circuit 100 times job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=1024) # get the result counts = job.result().get_counts(circuit) print(counts) from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # draw the overall circuit drawer(circuit) # re-execute me if you DO NOT see the circuit diagram from qiskit import IBMQ IBMQ.save_account('write YOUR IBM API TOKEN here') # Then, execute this cell IBMQ.stored_accounts() IBMQ.load_accounts() IBMQ.active_accounts() IBMQ.backends() IBMQ.backends(operational=True, simulator=False) from qiskit.backends.ibmq import least_busy least_busy(IBMQ.backends(simulator=False)) backend = least_busy(IBMQ.backends(simulator=True)) backend.name() from qiskit import compile qobj = compile(circuit, backend=backend, shots=1024) job = backend.run(qobj) result = job.result() counts = result.get_counts() print(counts) backend_real = least_busy(IBMQ.backends(simulator=False)) backend_real.name() backend_real.status() qobj_real = compile(circuit, backend=backend_real, shots=1024) job_real = backend_real.run(qobj_real) job_real.queue_position() result_real = job_real.result() counts_real = result_real.get_counts() print(counts_real)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Pauli Transfer Matrix (PTM) representation of a Quantum Channel. """ from __future__ import annotations import copy as _copy import math import numpy as np from qiskit import _numpy_compat from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel from qiskit.quantum_info.operators.channel.superop import SuperOp from qiskit.quantum_info.operators.channel.transformations import _to_ptm from qiskit.quantum_info.operators.mixins import generate_apidocs from qiskit.quantum_info.operators.base_operator import BaseOperator class PTM(QuantumChannel): r"""Pauli Transfer Matrix (PTM) representation of a Quantum Channel. The PTM representation of an :math:`n`-qubit quantum channel :math:`\mathcal{E}` is an :math:`n`-qubit :class:`SuperOp` :math:`R` defined with respect to vectorization in the Pauli basis instead of column-vectorization. The elements of the PTM :math:`R` are given by .. math:: R_{i,j} = \frac{1}{2^n} \mbox{Tr}\left[P_i \mathcal{E}(P_j) \right] where :math:`[P_0, P_1, ..., P_{4^{n}-1}]` is the :math:`n`-qubit Pauli basis in lexicographic order. Evolution of a :class:`~qiskit.quantum_info.DensityMatrix` :math:`\rho` with respect to the PTM is given by .. math:: |\mathcal{E}(\rho)\rangle\!\rangle_P = S_P |\rho\rangle\!\rangle_P where :math:`|A\rangle\!\rangle_P` denotes vectorization in the Pauli basis :math:`\langle i | A\rangle\!\rangle_P = \sqrt{\frac{1}{2^n}} \mbox{Tr}[P_i A]`. See reference [1] for further details. References: 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). `arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_ """ def __init__( self, data: QuantumCircuit | Instruction | BaseOperator | np.ndarray, input_dims: int | tuple | None = None, output_dims: int | tuple | None = None, ): """Initialize a PTM quantum channel operator. Args: data (QuantumCircuit or Instruction or BaseOperator or matrix): data to initialize superoperator. input_dims (tuple): the input subsystem dimensions. [Default: None] output_dims (tuple): the output subsystem dimensions. [Default: None] Raises: QiskitError: if input data is not an N-qubit channel or cannot be initialized as a PTM. Additional Information: If the input or output dimensions are None, they will be automatically determined from the input data. The PTM representation is only valid for N-qubit channels. """ # If the input is a raw list or matrix we assume that it is # already a Chi matrix. if isinstance(data, (list, np.ndarray)): # Should we force this to be real? ptm = np.asarray(data, dtype=complex) # Determine input and output dimensions dout, din = ptm.shape if input_dims: input_dim = np.prod(input_dims) else: input_dim = int(math.sqrt(din)) if output_dims: output_dim = np.prod(input_dims) else: output_dim = int(math.sqrt(dout)) if output_dim**2 != dout or input_dim**2 != din or input_dim != output_dim: raise QiskitError("Invalid shape for PTM matrix.") else: # Otherwise we initialize by conversion from another Qiskit # object into the QuantumChannel. if isinstance(data, (QuantumCircuit, Instruction)): # If the input is a Terra QuantumCircuit or Instruction we # convert it to a SuperOp data = SuperOp._init_instruction(data) else: # We use the QuantumChannel init transform to initialize # other objects into a QuantumChannel or Operator object. data = self._init_transformer(data) input_dim, output_dim = data.dim # Now that the input is an operator we convert it to a PTM object rep = getattr(data, "_channel_rep", "Operator") ptm = _to_ptm(rep, data._data, input_dim, output_dim) if input_dims is None: input_dims = data.input_dims() if output_dims is None: output_dims = data.output_dims() # Check input is N-qubit channel num_qubits = int(math.log2(input_dim)) if 2**num_qubits != input_dim or input_dim != output_dim: raise QiskitError("Input is not an n-qubit Pauli transfer matrix.") super().__init__(ptm, num_qubits=num_qubits) def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): dtype = self.data.dtype if dtype is None else dtype return np.array(self.data, dtype=dtype, copy=copy) @property def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._output_dim, self._output_dim, self._input_dim, self._input_dim) def _evolve(self, state, qargs=None): return SuperOp(self)._evolve(state, qargs) # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def conjugate(self): # Since conjugation is basis dependent we transform # to the SuperOp representation to compute the # conjugate channel return PTM(SuperOp(self).conjugate()) def transpose(self): return PTM(SuperOp(self).transpose()) def adjoint(self): return PTM(SuperOp(self).adjoint()) def compose(self, other: PTM, qargs: list | None = None, front: bool = False) -> PTM: if qargs is None: qargs = getattr(other, "qargs", None) if qargs is not None: return PTM(SuperOp(self).compose(other, qargs=qargs, front=front)) # Convert other to PTM if not isinstance(other, PTM): other = PTM(other) new_shape = self._op_shape.compose(other._op_shape, qargs, front) input_dims = new_shape.dims_r() output_dims = new_shape.dims_l() if front: data = np.dot(self._data, other.data) else: data = np.dot(other.data, self._data) ret = PTM(data, input_dims, output_dims) ret._op_shape = new_shape return ret def tensor(self, other: PTM) -> PTM: if not isinstance(other, PTM): other = PTM(other) return self._tensor(self, other) def expand(self, other: PTM) -> PTM: if not isinstance(other, PTM): other = PTM(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): ret = _copy.copy(a) ret._op_shape = a._op_shape.tensor(b._op_shape) ret._data = np.kron(a._data, b.data) return ret # Update docstrings for API docs generate_apidocs(PTM)
https://github.com/quantum-melbourne/qiskit-challenge-22
quantum-melbourne
from qiskit_optimization import QuadraticProgram # Define QuadraticProgram qp = QuadraticProgram() # Add variables qp.binary_var('x') qp.binary_var('y') qp.integer_var(lowerbound=0, upperbound=7, name='z') # Add an objective function qp.maximize(linear={'x': 2, 'y': 1, 'z': 1}) # Add a constraint qp.linear_constraint(linear={'x': 1, 'y': 1, 'z': 1}, sense='LE', rhs=2, name='xyz_leq') print(qp.export_as_lp_string()) import networkx as nx # Make a graph with degree=2 and #node=5 graph = nx.random_regular_graph(d=2, n=5, seed=111) pos = nx.spring_layout(graph, seed=111) # Application class for a Max-cut problem # Make a Max-cut problem from the graph from qiskit_optimization.applications import Maxcut maxcut = Maxcut(graph) maxcut.draw(pos=pos) # Make a QuadraticProgram by calling to_quadratic_program() qp = maxcut.to_quadratic_program() print(qp) from qiskit import Aer from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit.algorithms import QAOA, NumPyMinimumEigensolver qins = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), shots=1000, seed_simulator=123) # Define QAOA solver meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, quantum_instance=qins)) result = meo.solve(qp) print('result:\n', result) print('\nsolution:\n', maxcut.interpret(result)) print('\ntime:', result.min_eigen_solver_result.optimizer_time) maxcut.draw(result, pos=pos) # Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) print('result:\n', result) print('\nsolution:\n', maxcut.interpret(result)) maxcut.draw(result, pos=pos)
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 = [] gate_counts = [] non_local_gate_counts = [] levels = [str(x) for x in range(4)] for level in range(4): circ = transpile(ghz, backend, optimization_level=level) depths.append(circ.depth()) gate_counts.append(sum(circ.count_ops().values())) non_local_gate_counts.append(circ.num_nonlocal_gates()) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.bar(levels, depths, label='Depth') ax1.set_xlabel("Optimization Level") ax1.set_ylabel("Depth") ax1.set_title("Output Circuit Depth") ax2.bar(levels, gate_counts, label='Number of Circuit Operations') ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates') ax2.set_xlabel("Optimization Level") ax2.set_ylabel("Number of gates") ax2.legend() ax2.set_title("Number of output circuit gates") fig.tight_layout() plt.show()
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,BasicAer,Aer,transpile,execute from qiskit.visualization import * qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.measure_all() qc.draw(output="mpl") backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) # For the statevector ,no measurements qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) plot_state_city(sv) qc=QuantumCircuit(2) qc.x(0) qc.h(0) qc.cx(0,1) qc.measure_all() qc.draw(output="mpl") backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) # For the statevector ,no measurements qc=QuantumCircuit(2) qc.x(0) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) plot_state_city(sv) qc=QuantumCircuit(2) qc.h(0) qc.x(1) qc.cx(0,1) qc.measure_all() qc.draw(output="mpl") backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) # For the statevector ,no measurements qc=QuantumCircuit(2) qc.h(0) qc.x(1) qc.cx(0,1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) plot_state_city(sv) qc=QuantumCircuit(2) qc.x(0) qc.h(0) qc.x(1) qc.cx(0,1) qc.measure_all() qc.draw(output="mpl") backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) # For the statevector ,no measurements qc=QuantumCircuit(2) qc.x(0) qc.h(0) qc.x(1) qc.cx(0,1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) plot_state_city(sv) qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) qc=QuantumCircuit(1) qc.x(0) qc.h(0) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) qc=QuantumCircuit(1) qc.h(0) qc.sdg(0) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv, show_state_phases=True) qc=QuantumCircuit(3) qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv, show_state_phases=True)
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/JavierPerez21/QiskitPractice
JavierPerez21
%%capture !pip install qiskit %matplotlib inline from qiskit import * import numpy as np from math import pi from qiskit.visualization import plot_histogram, plot_bloch_multivector, plot_state_qsphere, plot_state_city from qiskit.quantum_info import Statevector from qiskit.quantum_info import state_fidelity import matplotlib.pyplot as plt class RandomCircuitGenerator: def __init__(self, qubits=1, max_depth=3): self.qubits = np.arange(0,qubits).tolist() self.max_depth = max_depth self.qc = QuantumCircuit(qubits, qubits) self.single_qubit_gates = ['x', 'z', 'y', 'h', 's', 't', 'rx', 'rz', 'ry', ''] self.multi_qubit_gates = ['cx', 'cz', 'cy', 'ch', 'cs', 'ct', 'crx', 'crz', 'cry', ''] self.angles = [0, pi / 8, pi / 4, 3 * pi / 8, pi / 2, 5 * pi / 8, 3 * pi / 4, 7 * pi / 8, pi, 9 * pi / 8, 5 * pi / 4, 11 * pi / 8, 3 * pi / 2, 13 * pi / 8, 7 * pi / 4, 15 * pi / 8, 2 * pi] if len(self.qubits) > 1: self.available_gates = self.single_qubit_gates + self.multi_qubit_gates else: self.available_gates = self.single_qubit_gates def generate_random_circuit(self): for i in range(0, self.max_depth): gate = self.available_gates[np.random.randint(0, len(self.available_gates))] self.add_gate(gate) def add_gate(self, gate): if gate == 'x': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.x(qubit) elif gate == 'z': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.z(qubit) elif gate == 'y': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.y(qubit) elif gate == 'h': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.h(qubit) elif gate == 's': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.s(qubit) elif gate == 't': qubit = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.t(qubit) elif gate == 'rx': qubit = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.rx(angle, qubit) elif gate == 'rz': qubit = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.rz(angle, qubit) elif gate == 'ry': qubit = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.ry(angle, qubit) elif gate == 'cx': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.cx(qubit1, qubit2) elif gate == 'cz': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.cz(qubit1, qubit2) elif gate == 'cy': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.cy(qubit1, qubit2) elif gate == 'ch': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.ch(qubit1, qubit2) elif gate == 'cs': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.cs(qubit1, qubit2) elif gate == 'ct': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] self.qc.ct(qubit1, qubit2) elif gate == 'crx': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.crx(angle, qubit1, qubit2) elif gate == 'crz': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.crz(angle, qubit1, qubit2) elif gate == 'cry': qubit1 = self.qubits[np.random.randint(0, len(self.qubits))] qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] while qubit1 == qubit2: qubit2 = self.qubits[np.random.randint(0, len(self.qubits))] angle = self.angles[np.random.randint(0, len(self.angles))] self.qc.cry(angle, qubit1, qubit2) def show_circuit(self): print(self.qc) def execution_historgram(self): qc = self.qc.copy() qc.measure(self.qubits, self.qubits) backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend) return plot_histogram(job.result().get_counts(), color='midnightblue', title="Execution Histogram") def bloch_sphere(self): qc = self.qc.copy() state = Statevector.from_instruction(qc) return plot_bloch_multivector(state, title="Bloch Sphere", reverse_bits=False) def q_sphere(self): qc = self.qc.copy() state = Statevector.from_instruction(qc) return plot_state_qsphere(state) def state_city(self): qc = self.qc.copy() backend = BasicAer.get_backend('statevector_simulator') result = backend.run(transpile(qc, backend)).result() psi = result.get_statevector(qc) return plot_state_city(psi) def add_circuit_guess(self, circuit_guess): qc = self.qc.copy() self.circuit_guess = circuit_guess circuit_guess = circuit_guess.copy() backend = BasicAer.get_backend('statevector_simulator') qc_state = execute(qc, backend).result().get_statevector(qc) circuit_guess_state = execute(circuit_guess, backend).result().get_statevector(circuit_guess) print("State fidelity of your circuit: {}".format(state_fidelity(circuit_guess_state, qc_state))) # Generate a random circuit circuit = RandomCircuitGenerator(qubits=1, max_depth=2) circuit.generate_random_circuit() # Visualize som information about the random circuit #circuit.execution_historgram() circuit.bloch_sphere() #circuit.q_sphere() #circuit.show_circuit() # Try to generate a similar circuit circuit_guess = QuantumCircuit(1) circuit_guess.h(0) circuit.add_circuit_guess(circuit_guess)
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
import numpy as np import matplotlib.pyplot as plt from datetime import datetime import json import copy # Main qiskit imports from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, IBMQ # Error mitigation from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter, MeasurementFilter) # Utility functions from qiskit.tools.jupyter import * from qiskit.tools.monitor import job_monitor from qiskit.providers.jobstatus import JobStatus # Shows a window in the upper left part with real-time information # on the status of the jobs running on the IBM Q device #%qiskit_job_watcher # We use ibmq_vigo IBMQ.load_account() backend = IBMQ.get_provider(hub='ibm-q', group='open', project='main').get_backend('ibmq_vigo') # Local simulator and vector simulator simulator = Aer.get_backend('qasm_simulator') from amplitude_damping import * SHOTS = 200 #8192 # The values for R and corresponding times, # as well as the observables needed for the witness observables = ['xx', 'yy', 'zz'] R_values = np.array([0.2, 100.0]) npoints = 200 t_values = {} for idx, R in enumerate(R_values): t_values[str(idx)] = np.linspace(0.0, 6.0 * np.pi / np.sqrt(abs(2.0 * R - 1.0)), npoints) #t_values = np.linspace(0.0,5.0,npoints) # We create the quantum circuits q = QuantumRegister(5, name="q") c = ClassicalRegister(2, name="c") ## Indices of the system, environment and ancillary qubits sys = 1 env = 2 anc = 3 ## Two values of R and thirty values of t for each ## The witness requires measuring three observables per point circuits = {} for idx, R in enumerate(R_values): circuits[R] = {} for observable in observables: circuits[R][observable] = [] for t in t_values[str(idx)]: circuits[R][observable].append(initial_state_witness(q, sys, anc) +amplitude_damping_channel_witness(q, c, sys, env, anc, observable, R, t)) # Calibration circuits cal_circuits, state_labels = complete_meas_cal([sys, anc], q, c) circuits[0.2]['yy'][1].draw(output='mpl') # Execute the circuits on the local simulator jobs_sim = {} for R in R_values: jobs_sim[R] = {} for observable in observables: jobs_sim[R][observable] = execute(circuits[R][observable], backend = simulator, shots = SHOTS) # Analyse the outcomes ## Compute expected values expected_sim = {} for idx, R in enumerate(R_values): expected_sim[str(idx)] = {} for observable in observables: expected_sim[str(idx)][observable] = [] current_job_res = jobs_sim[R][observable].result() for i in range(npoints): counts = current_job_res.get_counts(i) expc = 0.0 for outcome in counts: if outcome[0] == outcome[1]: expc += counts[outcome]/float(SHOTS) else: expc -= counts[outcome]/float(SHOTS) expected_sim[str(idx)][observable].append(expc) ## Compute witness witness_sim = {} for idx, R in enumerate(R_values): witness_sim[str(idx)] = [] for i in range(npoints): w = 0.25*(1.0+expected_sim[str(idx)]['xx'][i]-expected_sim[str(idx)]['yy'][i]+expected_sim[str(idx)]['zz'][i]) witness_sim[str(idx)].append(w) # Plot the results fig_idx = 221 plt.figure(figsize=(10,12)) for idx, R in enumerate(R_values): plt.subplot(fig_idx) plt.plot(t_values[str(idx)], witness_sim[str(idx)]) plt.xlabel('t') plt.ylabel('Population') fig_idx += 1 plt.grid() from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Slider, CustomJS, Text from bokeh.plotting import Figure, show from bokeh.io import output_notebook R_values_str = [str(i) for i in range(len(R_values))] R_values_str_R = ['R = {:.2f}'.format(R) for R in R_values] # truncate to two decimals # make a dictionary of form {'0': 0.0, '1': 0.2, .. } R_values_dict = {R_values_str[i]:R_values.round(2)[i] for i,_ in enumerate(R_values)} # rounding to two decimals ys = witness_sim rs = {R_values_str[i] : [R_values_str_R[i]] for i,_ in enumerate(R_values)} ts = t_values initial_r = R_values_str[1] # Wrap the data in two ColumnDataSources source_visible = ColumnDataSource(data=dict( x = ts[initial_r], y = ys[initial_r])) source_available_x = ColumnDataSource(data=ts) source_available_y = ColumnDataSource(data=ys) # Define plot elements plot = Figure(plot_width=400, plot_height=400, y_range=(-.01, 1)) plot.line('x', 'y', source=source_visible, legend_label="ρ₁₁", line_width=3, line_alpha=0.6) # Add text text_source = ColumnDataSource({'r_value': [rs[initial_r]]}) r_available = ColumnDataSource(data=rs) text = Text(x=0, x_offset=315, y=.8, text='r_value', text_font_size='15pt', text_align='right') plot.add_glyph(text_source, text) # Add slider slider = Slider(value=int(initial_r), start=np.min([int(i) for i in ys.keys()]), end=np.max([int(i) for i in ys.keys()]), step=1, show_value = False, title = 'R') # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible=source_visible, source_available_x=source_available_x, source_available_y=source_available_y, text_source = text_source, r_available = r_available), code=""" var r_idx = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available_x = source_available_x.data; var data_available_y = source_available_y.data; // Change y-axis data according to the selected value data_visible.x = data_available_x[r_idx]; data_visible.y = data_available_y[r_idx]; // text text_source.data = {'r_value': [String(r_available.data[r_idx])]}; // Update the plot source_visible.change.emit(); """) layout = column(plot,slider) output_notebook() show(layout) # Run the calibration job calibration_job = execute(cal_circuits, backend, shots=SHOTS) # Run the circuits and save the jobs jobs = {} jobs_data = [] for R in R_values: jobs[R] = {} for observable in observables: jobs[R][observable] = execute(circuits[R][observable], backend = backend, shots = SHOTS) job_data = {'jobid': jobs[R][observable].job_id(), 'description': 'Amplitude damping channel for R = '+str(R)+'. Non-Markovianity witness observable: '+observable, 'metadata': {'t_values': list(t_values[R]), 'R': R, 'observable': observable}} jobs_data.append(job_data) experiment_data = [{ "backend": backend.name(), "calibration": calibration_job.job_id(), "description": "Circuits for the simulation of the amplitude damping channel with non-Markovianity witness", "jobs": jobs_data }] filename = 'amplitude_damping_witness_{}.json'.format( datetime.now().strftime(("%Y_%m_%d-%H_%M"))) with open(filename,'w') as file: json.dump(experiment_data, file) # List the available experiment files import glob print("Available experiment files:") for f in glob.glob('*.json'): print(f) # Load the experiment file filename = "amplitude_damping_witness_2019_11_19-14_48.json" with open(filename, 'r') as file: experiment_data = json.load(file) print(experiment_data[0]['description']) print("Run on", experiment_data[0]['backend']) # Get the backend backend = IBMQ.get_provider(hub='ibm-q-university', group='turku', project='main').get_backend(experiment_data[0]['backend']) # Use the calibration job to implement the error mitigation calibration_job = backend.retrieve_job(experiment_data[0]['calibration']) meas_fitter = CompleteMeasFitter(calibration_job.result(), state_labels) meas_filter = meas_fitter.filter # Analyse the outcomes t_values = {} ## Retrieve jobs jobs = {} for job in experiment_data[0]['jobs']: R = job['metadata']['R'] t_values[R] = np.array(job['metadata']['t_values']) observable = job['metadata']['observable'] if R not in jobs: jobs[R] = {} jobs[R][observable] = backend.retrieve_job(job['jobid']) ## Compute expected values expected = {} for R in R_values: expected[R] = {} for observable in observables: expected[R][observable] = [] current_job_res = jobs[R][observable].result() mitigated_res = meas_filter.apply(current_job_res) for i in range(npoints): counts = mitigated_res.get_counts(i) expc = 0.0 for outcome in counts: if outcome[0] == outcome[1]: expc += counts[outcome]/float(SHOTS) else: expc -= counts[outcome]/float(SHOTS) expected[R][observable].append(expc) ## Compute witness witness = {} for R in R_values: witness[R] = [] for i in range(npoints): w = 0.25*(1.0+expected[R]['xx'][i]-expected[R]['yy'][i]+expected[R]['zz'][i]) witness[R].append(w) # Plot the results fig_idx = 221 plt.figure(figsize=(10,12)) for R in R_values: plt.subplot(fig_idx) plt.plot(t_values[R], witness[R], label='Experiment') plt.plot(t_values[R], witness_sim[R], label='Simulation') plt.xlabel('t') plt.ylabel('Witness') fig_idx += 1 plt.grid() plt.legend(); jobs[0.2]['zz'].properties().qubits jobs[0.2]['zz'].properties().gates
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/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# Importing standard Qiskit libraries and configuring account from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute from qiskit.visualization import plot_bloch_multivector # If you run this code outside IBM Quantum Experience, # run the following commands to store your API token locally. # Please refer https://qiskit.org/documentation/install.html#access-ibm-quantum-systems # IBMQ.save_account('MY_API_TOKEN') # Loading your IBM Q account(s) IBMQ.load_account() # Let's do an X-gate on a |0> qubit q = QuantumRegister(1) qc = QuantumCircuit(q) qc.x(q[0]) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result().get_statevector(qc, decimals=3) plot_bloch_multivector(result) # Let's do an H-gate on a |0> qubit q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q[0]) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result().get_statevector(qc, decimals=3) plot_bloch_multivector(result) # Let's do an Z-gate on |+> q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q[0]) qc.z(q[0]) qc.draw(output='mpl') # Let's see the result backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result().get_statevector(qc, decimals=3) print(result) plot_bloch_multivector(result) # Let's do an CX-gate on |00> q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cx(q[0],q[1]) qc.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result().get_statevector(qc, decimals=3) print(result) plot_bloch_multivector(result) # Let's do an CZ-gate on |00> q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cz(q[0],q[1]) qc.draw(output='mpl') # Let's make CZ-gate with CX-gate and H-gate q = QuantumRegister(2) qc = QuantumCircuit(q) qc.h(q[1]) qc.cx(q[0],q[1]) qc.h(q[1]) qc.draw(output='mpl') # Let's do an CCX-gate on |00> q = QuantumRegister(3) qc = QuantumCircuit(q) qc.ccx(q[0],q[1],q[2]) qc.draw(output='mpl') # Create a Quantum Circuit with 1 quantum register and 1 classical register q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.x(q[0]) qc.measure(q[0], c[0]) # Map the quantum measurement to the classical bits qc.draw(output='mpl') q = QuantumRegister(3) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.ccx(q[0], q[1], q[2]) qc.measure(q[2], c[0]) qc.draw(output='mpl') q = QuantumRegister(3) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.ccx(q[0], q[1], q[2]) qc.x(q[2]) qc.measure(q[2], c[0]) qc.draw(output='mpl') q = QuantumRegister(3) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.cx(q[1], q[2]) qc.cx(q[0], q[2]) qc.ccx(q[0], q[1], q[2]) qc.measure(q[2], c[0]) qc.draw(output='mpl') q = QuantumRegister(3) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.cx(q[1], q[2]) qc.cx(q[0], q[2]) qc.measure(q[2], c[0]) qc.draw(output='mpl') q = QuantumRegister(3) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.cx(q[1], q[2]) qc.cx(q[0], q[2]) qc.ccx(q[0], q[1], q[2]) qc.x(q[2]) qc.measure(q[2], c[0]) qc.draw(output='mpl') #Define registers and a quantum circuit q = QuantumRegister(4) c = ClassicalRegister(2) qc = QuantumCircuit(q,c) #XOR qc.cx(q[1], q[2]) qc.cx(q[0], q[2]) qc.barrier() #AND qc.ccx(q[0], q[1], q[3]) qc.barrier() #Sum qc.measure(q[2], c[0]) #Carry out qc.measure(q[3], c[1]) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import BasicAer, execute from qiskit.quantum_info import Pauli, state_fidelity, process_fidelity q = QuantumRegister(4, 'q0') c = ClassicalRegister(1, 'c0') qc = QuantumCircuit(q, c) qc.ccx(q[0], q[1], q[2]) qc.cx(q[3], q[1]) qc.h(q[3]) qc.ccx(q[3], q[2], q[1]) qc.measure(q[3],c[0]) qc.draw(output='mpl') qc.count_ops() from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) new_circuit.draw(output='mpl') new_circuit.count_ops() q = QuantumRegister(3, 'q0') c = ClassicalRegister(1, 'c0') qc = QuantumCircuit(q, c) qc.ccx(q[0], q[1], q[2]) qc.draw(output='mpl') pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) new_circuit.draw(output='mpl') new_circuit.count_ops() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute ##### build your quantum circuit here q = QuantumRegister(8, 'q') c = ClassicalRegister(2, 'c') qc = QuantumCircuit(q,c) qc.x(q[0]) #input 1 #qc.x(q[1]) #input 1 qc.x(q[2]) #input 1 qc.cx(q[2],q[3]) qc.cx(q[1], q[3]) # B XOR X qc.cx(q[3], q[4]) qc.cx(q[0], q[4]) #4 will be my sum - B XOR X XOR A qc.ccx(q[0], q[3], q[5]) # A AND (B XOR X) qc.ccx(q[1], q[2], q[6]) # BX qc.cx(q[6], q[7]) qc.cx(q[5], q[7]) qc.ccx(q[5], q[6], q[7]) # BX AND A(B XOR X) qc.measure(q[4],c[0]) # SUM - B XOR X XOR A qc.measure(q[7],c[1]) # Carry Out - BX OR A(B XOR X) # execute the circuit by qasm_simulator backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute ##### build your quantum circuit here q = QuantumRegister(6, 'q') c = ClassicalRegister(2, 'c') qc = QuantumCircuit(q,c) qc.x(q[0]) #input 1 #qc.x(q[1]) #input 1 qc.x(q[2]) #input 1 qc.ccx(q[1], q[2],q[3]) # BX qc.cx(q[1], q[2]) # B XOR X qc.ccx(q[0], q[2], q[4]) # A(B XOR X) qc.cx(q[0], q[2]) #2 will be my sum - B XOR X XOR A qc.cx(q[4], q[5]) qc.cx(q[3], q[5]) qc.ccx(q[3], q[4], q[5]) # BX OR A(B XOR X) qc.measure(q[2],c[0]) # SUM - B XOR X XOR A qc.measure(q[5],c[1]) # Carry Out - BX OR A(B XOR X) # execute the circuit by qasm_simulator backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute ##### build your quantum circuit here q = QuantumRegister(6, 'q') c = ClassicalRegister(2, 'c') qc = QuantumCircuit(q,c) qc.x(q[0]) #input 1 #qc.x(q[1]) #input 1 qc.x(q[2]) #input 1 qc.ccx(q[1], q[2],q[3]) # BX qc.cx(q[1], q[2]) # B XOR X qc.ccx(q[0], q[2], q[4]) # A(B XOR X) qc.cx(q[0], q[2]) #2 will be my sum - B XOR X XOR A qc.measure(q[2],c[0]) # SUM - B XOR X XOR A qc.x(q[3]) qc.x(q[4]) qc.ccx(q[3], q[4], q[5]) qc.x(q[5])# BX OR A(B XOR X) qc.measure(q[5],c[1]) # Carry Out - BX OR A(B XOR X) # execute the circuit by qasm_simulator backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute ##### build your quantum circuit here q = QuantumRegister(4, 'q') c = ClassicalRegister(2, 'c') qc = QuantumCircuit(q,c) qc.x(q[0]) #input 1 #qc.x(q[1]) #input 1 qc.x(q[2]) #input 1 qc.ccx(q[1], q[2],q[3]) # BX qc.cx(q[1], q[2]) # B XOR X qc.ccx(q[0], q[2], q[3]) # A(B XOR X) qc.cx(q[0], q[2]) #2 will be my sum - A XOR B XOR X qc.measure(q[2],c[0]) # SUM - B XOR X XOR A qc.measure(q[3],c[1]) # Carry Out - BX OR A(B XOR X) # execute the circuit by qasm_simulator backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) #new_circuit.draw(output='mpl') new_circuit.count_ops() # Check your answer using following code from qc_grader import grade_ex1a grade_ex1a(qc) # Submit your answer. You can re-submit at any time. from qc_grader import submit_ex1a submit_ex1a(qc)
https://github.com/Qiskit/feedback
Qiskit
import networkx as nx from qiskit_optimization.applications import Maxcut seed = 1 num_nodes = 6 graph = nx.random_regular_graph(d=3, n=num_nodes, seed=seed) nx.draw(graph, with_labels=True, pos=nx.spring_layout(graph, seed=seed)) maxcut = Maxcut(graph) problem = maxcut.to_quadratic_program() print(problem.prettyprint()) from qiskit.algorithms.optimizers import COBYLA from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Estimator from qiskit_optimization.algorithms.qrao import ( QuantumRandomAccessOptimizer, SemideterministicRounding, ) # Prepare the VQE algorithm ansatz = RealAmplitudes(2) vqe = VQE( ansatz=ansatz, optimizer=COBYLA(), estimator=Estimator(), ) # Use semi-deterministic rounding, known as "Pauli rounding" # in https://arxiv.org/pdf/2111.03167v2.pdf # (This is the default if no rounding scheme is specified.) semidterministic_rounding = SemideterministicRounding() # Construct the optimizer qrao = QuantumRandomAccessOptimizer( min_eigen_solver=vqe, rounding_scheme=semidterministic_rounding ) import numpy as np # Solve the optimization problem results = qrao.solve(problem) print( f"The objective function value: {results.fval}\n" f"x: {results.x}\n" f"relaxed function value: {-1 * results.relaxed_fval}\n" ) print( f"The obtained solution places a partition between nodes {np.where(results.x == 0)[0]} " f"and nodes {np.where(results.x == 1)[0]}." ) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer exact_mes = NumPyMinimumEigensolver() exact = MinimumEigenOptimizer(exact_mes) exact_result = exact.solve(problem) print(exact_result.prettyprint()) print("QRAO Approximate Optimal Function Value:", results.fval) print("Exact Optimal Function Value:", exact_result.fval) print(f"Approximation Ratio: {results.fval / exact_result.fval :.2f}") from qiskit.primitives import Sampler from qiskit_optimization.algorithms.qrao import MagicRounding estimator = Estimator(options={"shots": 1000, "seed": seed}) sampler = Sampler(options={"shots": 10000, "seed": seed}) # Prepare the VQE algorithm ansatz = RealAmplitudes(2) vqe = VQE( ansatz=ansatz, optimizer=COBYLA(), estimator=estimator, ) # Use magic rounding magic_rounding = MagicRounding(sampler=sampler) # Construct the optimizer qrao = QuantumRandomAccessOptimizer(min_eigen_solver=vqe, rounding_scheme=magic_rounding) results = qrao.solve(problem) print( f"The objective function value: {results.fval}\n" f"x: {results.x}\n" f"relaxed function value: {-1 * results.relaxed_fval}\n" ) print(f"The number of distinct samples is {len(results.samples)}.") print("Top 10 samples with the largest fval:") for sample in results.samples[:10]: print(sample) from qiskit_optimization.algorithms.qrao import QuantumRandomAccessEncoding # Encode the QUBO problem into a relaxed Hamiltonian encoding = QuantumRandomAccessEncoding(max_vars_per_qubit=3) encoding.encode(problem) # Solve the relaxed problem relaxed_results, rounding_context = qrao.solve_relaxed(encoding) magic_rounding = MagicRounding(sampler=sampler) mr_results = magic_rounding.round(rounding_context) qrao_results_mr = qrao.process_result( problem=problem, encoding=encoding, relaxed_result=relaxed_results, rounding_result=mr_results ) print( f"The objective function value: {qrao_results_mr.fval}\n" f"x: {qrao_results_mr.x}\n" f"relaxed function value: {-1 * qrao_results_mr.relaxed_fval}\n" f"The number of distinct samples is {len(qrao_results_mr.samples)}." )
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/Tojarieh97/VQE
Tojarieh97
from openfermion.chem import MolecularData from openfermion.transforms import get_fermion_operator, jordan_wigner from openfermion.linalg import get_ground_state, get_sparse_operator import numpy import scipy import scipy.linalg # Load saved file for LiH. diatomic_bond_length = 1.45 geometry = [('Li', (0., 0., 0.)), ('H', (0., 0., diatomic_bond_length))] basis = 'sto-3g' multiplicity = 1 # Set Hamiltonian parameters. active_space_start = 1 active_space_stop = 3 # Generate and populate instance of MolecularData. molecule = MolecularData(geometry, basis, multiplicity, description="1.45") molecule.load() # Get the Hamiltonian in an active space. molecular_hamiltonian = molecule.get_molecular_hamiltonian( occupied_indices=range(active_space_start), active_indices=range(active_space_start, active_space_stop)) # Map operator to fermions and qubits. fermion_hamiltonian = get_fermion_operator(molecular_hamiltonian) qubit_hamiltonian = jordan_wigner(fermion_hamiltonian) qubit_hamiltonian.compress() print('The Jordan-Wigner Hamiltonian in canonical basis follows:\n{}'.format(qubit_hamiltonian)) # Get sparse operator and ground state energy. sparse_hamiltonian = get_sparse_operator(qubit_hamiltonian) energy, state = get_ground_state(sparse_hamiltonian) print('Ground state energy before rotation is {} Hartree.\n'.format(energy)) # Randomly rotate. n_orbitals = molecular_hamiltonian.n_qubits // 2 n_variables = int(n_orbitals * (n_orbitals - 1) / 2) numpy.random.seed(1) random_angles = numpy.pi * (1. - 2. * numpy.random.rand(n_variables)) kappa = numpy.zeros((n_orbitals, n_orbitals)) index = 0 for p in range(n_orbitals): for q in range(p + 1, n_orbitals): kappa[p, q] = random_angles[index] kappa[q, p] = -numpy.conjugate(random_angles[index]) index += 1 # Build the unitary rotation matrix. difference_matrix = kappa + kappa.transpose() rotation_matrix = scipy.linalg.expm(kappa) # Apply the unitary. molecular_hamiltonian.rotate_basis(rotation_matrix) # Get qubit Hamiltonian in rotated basis. qubit_hamiltonian = jordan_wigner(molecular_hamiltonian) qubit_hamiltonian.compress() print('The Jordan-Wigner Hamiltonian in rotated basis follows:\n{}'.format(qubit_hamiltonian)) # Get sparse Hamiltonian and energy in rotated basis. sparse_hamiltonian = get_sparse_operator(qubit_hamiltonian) energy, state = get_ground_state(sparse_hamiltonian) print('Ground state energy after rotation is {} Hartree.'.format(energy))
https://github.com/strangequarkkk/BB84-Protocol-for-QKD
strangequarkkk
import matplotlib as mpl import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(1,1) # Alice prepares qubit in state |+> qc.h(0) qc.barrier() # Alice now sends the qubit to Bob # who measures it in the X-basis qc.h(0) qc.measure(0,0) # Draw and simulate circuit display(qc.draw()) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(assemble(qc)) plot_histogram(job.result().get_counts()) qc = QuantumCircuit(1,1) # Alice prepares qubit in state |+> qc.h(0) # Alice now sends the qubit to Bob # but Eve intercepts and tries to read it qc.measure(0, 0) qc.barrier() # Eve then passes this on to Bob # who measures it in the X-basis qc.h(0) qc.measure(0,0) # Draw and simulate circuit display(qc.draw()) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(assemble(qc)) plot_histogram(job.result().get_counts()) n = 100 ## Step 1 # Alice generates bits. alice_bits = np.random.randint(0,2,n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = np.random.randint(0,2,n) # Function to compare the bits & bases generated by alice, and then 'encode' the message. Basically determines the state of the qubit/photon to send. def encode_message(bits, bases): message = [] for i in range(n): qc = QuantumCircuit(1,1) if bases[i] == 0: # Prepare qubit in Z-basis if bits[i] == 0: pass else: qc.x(0) else: # Prepare qubit in X-basis if bits[i] == 0: qc.h(0) else: qc.x(0) qc.h(0) qc.barrier() message.append(qc) return message # Alice computes the encoded message using the function defined above. message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = np.random.randint(0,2,n) # Function to decode the message sent by alice by comparing qubit/photon states with Bob's generated bases. def measure_message(message, bases): backend = Aer.get_backend('aer_simulator') measurements = [] for q in range(n): if bases[q] == 0: # measuring in Z-basis message[q].measure(0,0) if bases[q] == 1: # measuring in X-basis message[q].h(0) message[q].measure(0,0) aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(message[q], shots=1, memory=True) result = aer_sim.run(qobj).result() measured_bit = int(result.get_memory()[0]) measurements.append(measured_bit) return measurements # Decode the message according to his bases bob_results = measure_message(message, bob_bases) ## Step 4 # Function to perform sifting i.e. disregard the bits for which Bob's & A;ice's bases didnot match. def remove_garbage(a_bases, b_bases, bits): good_bits = [] for q in range(n): if a_bases[q] == b_bases[q]: # If both used the same basis, add # this to the list of 'good' bits good_bits.append(bits[q]) return good_bits # Performing sifting for Alice's and Bob's bits. alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) bob_key = remove_garbage(alice_bases, bob_bases, bob_results) print("Alice's key after sifting (without interception)", alice_key) print("Bob's key after sifting (without interception) ", bob_key) # # Step 5 # # Function for parameter estimation i.e. determining the error rate by comparing subsets taen from both Alice's key & Bob's key. # def sample_bits(bits, selection): # sample = [] # for i in selection: # # use np.mod to make sure the # # bit we sample is always in # # the list range # i = np.mod(i, len(bits)) # # pop(i) removes the element of the # # list at index 'i' # sample.append(bits.pop(i)) # return sample # # Performing parameter estimation & disregarding the bits used for comparison from Alice's & Bob's key. # sample_size = 15 # bit_selection = np.random.randint(0,n,size=sample_size) # bob_sample = sample_bits(bob_key, bit_selection) # alice_sample = sample_bits(alice_key, bit_selection) num = 0 for i in range(0,len(bob_key)): if alice_key[i] == bob_key[i]: num = num + 1 matching_bits = (num/len(bob_key))*100 print(matching_bits,"% of the bits match.") ## Step 1 alice_bits = np.random.randint(2, size=n) ## Step 2 alice_bases = np.random.randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interception!! eve_bases = np.random.randint(2, size=n) intercepted_message = measure_message(message, eve_bases) ## Step 3 bob_bases = np.random.randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) print("Alice's key after sifting (with interception)", alice_key) print("Bob's key after sifting (with interception) ", bob_key) # ## Step 5 # sample_size = 15 # bit_selection = np.random.randint(n, size=sample_size) # bob_sample = sample_bits(bob_key, bit_selection) # alice_sample = sample_bits(alice_key, bit_selection) num = 0 for i in range(0,len(bob_key)): if alice_key[i] == bob_key[i]: num = num + 1 matching_bits = (num/len(bob_key))*100 print(matching_bits,"% of the bits match.") plt.rcParams['axes.linewidth'] = 2 mpl.rcParams['font.family'] = ['Georgia'] plt.figure(figsize=(10.5,6)) ax=plt.axes() ax.set_title('') ax.set_xlabel('$n$ (Number of bits drawn from the sifted keys for determining error rate)',fontsize = 18,labelpad=10) ax.set_ylabel(r'$P(Eve\ detected)$',fontsize = 18,labelpad=10) ax.xaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on') ax.yaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on') ax.tick_params(axis='x', labelsize=20) ax.tick_params(axis='y', labelsize=20) ax. xaxis. label. set_size(20) ax. yaxis. label. set_size(20) n = 30 x = np.arange(n+1) y = 1 - 0.75**x ax.plot(x,y,color = plt.cm.rainbow(np.linspace(0, 1, 5))[0], marker = "s", markerfacecolor='r')
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
alejomonbar
# !pip install --upgrade pip # !pip uninstall tensorflow --y # !pip install tensorflow import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # load csv file import pandas as pd # numpy to the seed import numpy as np # load csv fileframework to neural networks import tensorflow as tf #Method forthe neural network from keras.regularizers import l2 from keras.models import Sequential from keras.layers import Dense, Dropout #save as image the model summary from keras.utils.vis_utils import plot_model # librariesto plot import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns from sklearn.metrics import confusion_matrix, roc_curve, auc from sklearn.preprocessing import StandardScaler # demonstration of calculating metrics for a neural network model using sklearn from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score from sklearn.metrics import cohen_kappa_score from sklearn.metrics import roc_auc_score import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) data_train = pd.read_csv("fair_train.csv") X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values data_test = pd.read_csv("classic_test.csv") X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values (X_train.shape, y_train.shape),(X_test.shape, y_test.shape) np.random.seed(123) tf.random.set_seed(123) scale = StandardScaler() scale.fit(X_train) X_train_std = scale.transform(X_train) X_test_std = scale.transform(X_test) X_train_std[1], y_train[1] model = Sequential() model.add(Dense(25, input_dim=16, activation='relu', kernel_regularizer=l2(1e-6),kernel_initializer="glorot_normal")) model.add(Dropout(0.5)) model.add(Dense(8, activation='relu',kernel_regularizer=l2(1e-6), kernel_initializer="glorot_normal")) model.add(Dropout(0.5)) model.add(Dense(1, activation='sigmoid',kernel_regularizer=l2(1e-6), kernel_initializer="glorot_normal")) plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True) # Compile model auc = tf.keras.metrics.AUC() model.compile(loss='binary_crossentropy', optimizer="Adam", metrics=['accuracy',auc]) model_history = model.fit(X_train_std, y_train, epochs=100, batch_size=32, validation_split=0.2, shuffle=True) train_pred = model.predict(X_train_std) test_pred = model.predict(X_test_std) y_train_pred = (model.predict(X_train_std) > 0.5).astype("int32") y_test_pred = (model.predict(X_test_std) > 0.5).astype("int32") accuracy = accuracy_score(y_train, y_train_pred) print('Accuracy: %f' % accuracy) # precision tp / (tp + fp) precision = precision_score(y_train, y_train_pred) print('Precision: %f' % precision) # recall: tp / (tp + fn) recall = recall_score(y_train, y_train_pred) print('Recall: %f' % recall) # f1: 2 tp / (2 tp + fp + fn) f1 = f1_score(y_train, y_train_pred) print('F1 score: %f' % f1) # kappa kappa = cohen_kappa_score(y_train, y_train_pred) print('Cohens kappa: %f' % kappa) # ROC AUC auc = roc_auc_score(y_train, y_train_pred) print('ROC AUC: %f' % auc) # confusion matrix train_matrix = confusion_matrix(y_train, y_train_pred) print(train_matrix) ax = sns.heatmap(train_matrix, annot=True, cmap='Blues', fmt='g') ax.set_title('Seaborn Confusion Matrix with labels\n\n'); ax.set_xlabel('\nPredicted Values') ax.set_ylabel('Actual Values '); ax.xaxis.set_ticklabels(['0','1']) ax.yaxis.set_ticklabels(['0','1']) ## Display the visualization of the Confusion Matrix. plt.show() accuracy = accuracy_score(y_test, y_test_pred) print('Accuracy: %f' % accuracy) # precision tp / (tp + fp) precision = precision_score(y_test, y_test_pred) print('Precision: %f' % precision) # recall: tp / (tp + fn) recall = recall_score(y_test, y_test_pred) print('Recall: %f' % recall) # f1: 2 tp / (2 tp + fp + fn) f1 = f1_score(y_test, y_test_pred) print('F1 score: %f' % f1) # kappa kappa = cohen_kappa_score(y_test, y_test_pred) print('Cohens kappa: %f' % kappa) # ROC AUC auc = roc_auc_score(y_test, y_test_pred) print('ROC AUC: %f' % auc) # confusion matrix test_matrix = confusion_matrix(y_test, y_test_pred) print(test_matrix) ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g') ax.set_title('Seaborn Confusion Matrix with labels\n\n'); ax.set_xlabel('\nPredicted Values') ax.set_ylabel('Actual Values '); ax.xaxis.set_ticklabels(['0','1']) ax.yaxis.set_ticklabels(['0','1']) ## Display the visualization of the Confusion Matrix. plt.show()
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. # # 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. """ Simulator command to snapshot internal simulator representation. """ import warnings from qiskit import QuantumCircuit from qiskit.circuit import CompositeGate from qiskit import QuantumRegister from qiskit.circuit import Instruction from qiskit.extensions.exceptions import ExtensionError class Snapshot(Instruction): """Simulator snapshot instruction.""" def __init__(self, label, snapshot_type='statevector', num_qubits=0, num_clbits=0, params=None): """Create new snapshot instruction. Args: label (str): the snapshot label for result data. snapshot_type (str): the type of the snapshot. num_qubits (int): the number of qubits for the snapshot type [Default: 0]. num_clbits (int): the number of classical bits for the snapshot type [Default: 0]. params (list or None): the parameters for snapshot_type [Default: None]. Raises: ExtensionError: if snapshot label is invalid. """ if not isinstance(label, str): raise ExtensionError('Snapshot label must be a string.') self._label = label self._snapshot_type = snapshot_type if params is None: params = [] super().__init__('snapshot', num_qubits, num_clbits, params) def assemble(self): """Assemble a QasmQobjInstruction""" instruction = super().assemble() instruction.label = self._label instruction.snapshot_type = self._snapshot_type return instruction def inverse(self): """Special case. Return self.""" return Snapshot(self.num_qubits, self.num_clbits, self.params[0], self.params[1]) @property def snapshot_type(self): """Return snapshot type""" return self._snapshot_type @property def label(self): """Return snapshot label""" return self._label @label.setter def label(self, name): """Set snapshot label to name Args: name (str or None): label to assign unitary Raises: TypeError: name is not string or None. """ if isinstance(name, str): self._label = name else: raise TypeError('label expects a string') def snapshot(self, label, snapshot_type='statevector', qubits=None, params=None): """Take a statevector snapshot of the internal simulator representation. Works on all qubits, and prevents reordering (like barrier). For other types of snapshots use the Snapshot extension directly. Args: label (str): a snapshot label to report the result snapshot_type (str): the type of the snapshot. qubits (list or None): the qubits to apply snapshot to [Default: None]. params (list or None): the parameters for snapshot_type [Default: None]. Returns: QuantumCircuit: with attached command Raises: ExtensionError: malformed command """ # Convert label to string for backwards compatibility if not isinstance(label, str): warnings.warn( "Snapshot label should be a string, " "implicit conversion is depreciated.", DeprecationWarning) label = str(label) # If no qubits are specified we add all qubits so it acts as a barrier # This is needed for full register snapshots like statevector if isinstance(qubits, QuantumRegister): qubits = qubits[:] if not qubits: tuples = [] if isinstance(self, QuantumCircuit): for register in self.qregs: tuples.append(register) if not tuples: raise ExtensionError('no qubits for snapshot') qubits = [] for tuple_element in tuples: if isinstance(tuple_element, QuantumRegister): for j in range(tuple_element.size): qubits.append((tuple_element, j)) else: qubits.append(tuple_element) return self.append( Snapshot( label, snapshot_type=snapshot_type, num_qubits=len(qubits), params=params), qubits) # Add to QuantumCircuit and CompositeGate classes QuantumCircuit.snapshot = snapshot CompositeGate.snapshot = snapshot
https://github.com/erinaldi/bmn2-qiskit
erinaldi
# %% import time import fire import numpy as np import pandas as pd from scipy.sparse import diags from scipy.sparse import identity from scipy.sparse import kron from scipy.sparse.linalg import eigsh from qiskit import Aer from qiskit.opflow import MatrixOp from qiskit.circuit.library import EfficientSU2 from qiskit.algorithms import NumPyEigensolver, VQE from qiskit.algorithms.optimizers import SLSQP, COBYLA, L_BFGS_B, NELDER_MEAD from qiskit.utils import algorithm_globals, QuantumInstance # %% def build_operators(L: int, N: int) -> list: """Generate all the annihilation operators needed to build the hamiltonian Args: L (int): the cutoff of the single site Fock space N (int): the number of colors of gauge group SU(N) Returns: list: a list of annihilation operators, length=2*(N^2-1)+3 """ # The annihilation operator for the single boson a_b = diags(np.sqrt(np.linspace(1, L - 1, L - 1)), offsets=1) # The identity operator of the Fock space of a single boson i_b = identity(L) # The annihilation operator for the fermions (always cutoff = 2 because it is a spin) a_f = diags(np.sqrt(np.linspace(1, 1, 1)), offsets=1) # The Pauli $\sigma_z$ matrix sz = diags([1.0, -1.0]) # Identity for the single fermion space i_f = identity(2) # Bosonic Hilbert space N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> fixed for mini-BMN 2 product_list = [i_b] * N_bos # only the identity for bosons repeated N_bos times a_b_list = [] # this will contain a1...a6 for i in np.arange(0, N_bos): # loop over all bosonic operators operator_list = product_list.copy() # all elements are the identity operator operator_list[ i ] = a_b # the i^th element is now the annihilation operator for a single boson a_b_list.append( operator_list[0] ) # start taking tensor products from first element for a in operator_list[1:]: a_b_list[i] = kron( a_b_list[i], a ) # do the outer product between each operator_list element # Fermionic Hilbert space N_f = 3 # number of fermionic sites -> fixed for the supersymmetric model mini-BMN with 2 matrices product_list = [i_f] * N_f # only the identity for fermions repeated N_f times a_f_list = [] # this will contain f1...f3 for i in np.arange(0, N_f): # loop over all bosonic operators operator_list = product_list.copy() # all elements are the identity operator operator_list[ i ] = a_f # the i^th element is now the annihilation operator for a single fermion for j in np.arange(0, i): # the 0:(i-1) elements are replaced by sigma_Z operator_list[j] = sz a_f_list.append( operator_list[0] ) # start taking tensor products from the first operator for a in operator_list[1:]: a_f_list[i] = kron(a_f_list[i], a) # do the outer product # Combine the Bosonic and Fermionic space # - Identity for bosonic space (dimension will be $L^{N_{bos}} \times L^{N_{bos}}$) i_b_tot = identity(L ** N_bos) # - Identity for fermionic space (dimension will be $2^{N_f} \times 2^{N_f}$) i_f_tot = identity(2 ** N_f) # The new bosonic and fermionic operators combined into one list op_list = [] for a in a_b_list: op_list.append(kron(a, i_f_tot)) for a in a_f_list: op_list.append(kron(i_b_tot, a)) return op_list # %% def build_gauge_casimir(L: int, N: int): """Generate the gauge generators operators Args: L (int): the single site cutoff of the Fock space N (int): the number of colors in the gauge group SU(N) Returns: scipy.sparse : The sparse matrix for \sum_i G_i^2 """ # generate the annihilation operators op_list = build_operators(L, N) N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> FIXED for mini-BMN 2 N_f = 3 # number of fermionic sites -> FIXED for the supersymmetric model mini-BMN with 2 matrices bosons = op_list[:N_bos] fermions = op_list[-N_f:] # define the generator list for FIXED SU(2) g_list = [0] * 3 g_list[0] = 1j * ( bosons[1].conjugate().transpose() * bosons[2] - bosons[2].conjugate().transpose() * bosons[1] + bosons[4].conjugate().transpose() * bosons[5] - bosons[5].conjugate().transpose() * bosons[4] + fermions[1].conjugate().transpose() * fermions[2] - fermions[2].conjugate().transpose() * fermions[1] ) g_list[1] = 1j * ( bosons[2].conjugate().transpose() * bosons[0] - bosons[0].conjugate().transpose() * bosons[2] + bosons[5].conjugate().transpose() * bosons[3] - bosons[3].conjugate().transpose() * bosons[5] + fermions[2].conjugate().transpose() * fermions[0] - fermions[0].conjugate().transpose() * fermions[2] ) g_list[2] = 1j * ( bosons[0].conjugate().transpose() * bosons[1] - bosons[1].conjugate().transpose() * bosons[0] + bosons[3].conjugate().transpose() * bosons[4] - bosons[4].conjugate().transpose() * bosons[3] + fermions[0].conjugate().transpose() * fermions[1] - fermions[1].conjugate().transpose() * fermions[0] ) return g_list[0] * g_list[0] + g_list[1] * g_list[1] + g_list[2] * g_list[2] # %% def bmn2_hamiltonian(L: int = 2, N: int = 2, g2N: float = 0.2): """Construct the Hamiltonian of the minimal BMN model as a sparse matrix. The cutoff for each boson is L while the 't Hooft coupling in g2N for a gauge group SU(N). The limited number of qubits only let us simulate N=2 and L=2 => for 6 bosons and 3 fermions this is a 9 qubits problem. Args: L (int, optional): The cutoff of the bosonic modes (the annihilation operators will be LxL matrices). Defaults to 2. N (int, optional): The number of colors of a SU(N) gauge group. The degrees of freedom of one matrix will be N^2-1. Defaults to 2. g2N (float, optional): The 't Hooft coupling. Defaults to 0.2. """ print( f"Building minimal BMN Hamiltonian for SU({N}) with cutoff={L} and coupling={g2N}\n" ) # Built the annihilation operators op_list = build_operators(L,N) N_bos = int(2 * (N ** 2 - 1)) # number of boson sites -> FIXED for mini-BMN 2 N_f = 3 # number of fermionic sites -> FIXED for the supersymmetric model mini-BMN with 2 matrices # Build the Hamiltonian # Start piece by piece x_list = [] # only use the bosonic operators bosons = op_list[:N_bos] for op in bosons: x_list.append(1 / np.sqrt(2) * (op.conjugate().transpose() + op)) # save the fermions operators for convenience in a new list fermions = op_list[-N_f:] # Free Hamiltonian H_k = 0 for a in op_list[:N_bos]: H_k = H_k + a.conjugate().transpose() * a for a in op_list[-N_f:]: H_k = H_k + (3.0 / 2) * a.conjugate().transpose() * a # vacuum energy H_k = H_k + 0.25 * (2 * N_bos - 3 * N_f - 3) # Interaction among bosons V_b = ( x_list[2] * x_list[2] * x_list[3] * x_list[3] + x_list[2] * x_list[2] * x_list[4] * x_list[4] + x_list[1] * x_list[1] * x_list[3] * x_list[3] + x_list[1] * x_list[1] * x_list[5] * x_list[5] + x_list[0] * x_list[0] * x_list[4] * x_list[4] + x_list[0] * x_list[0] * x_list[5] * x_list[5] - 2 * x_list[0] * x_list[2] * x_list[3] * x_list[5] - 2 * x_list[0] * x_list[1] * x_list[3] * x_list[4] - 2 * x_list[1] * x_list[2] * x_list[4] * x_list[5] ) # Interactions between bosons and fermions V_bf = (2j / np.sqrt(2)) * ( (x_list[0] - 1j * x_list[3]) * fermions[1].conjugate().transpose() * fermions[2].conjugate().transpose() + (x_list[1] - 1j * x_list[4]) * fermions[2].conjugate().transpose() * fermions[0].conjugate().transpose() + (x_list[2] - 1j * x_list[5]) * fermions[0].conjugate().transpose() * fermions[1].conjugate().transpose() - (x_list[0] + 1j * x_list[3]) * fermions[2] * fermions[1] - (x_list[1] + 1j * x_list[4]) * fermions[0] * fermions[2] - (x_list[2] + 1j * x_list[5]) * fermions[1] * fermions[0] ) # full hamiltonian return H_k + g2N / N * V_b + np.sqrt(g2N / N) * V_bf # %% def eigenvalues_scipy(H, k: int = 10): """Compute the lowest k eigenvalues of a sparse symmetric matrix H. Args: H (scipy.sparse matrix): The Hamiltonian in the form of a sparse matrix k (int): The number of lowest eigenvalues to compute. Defaults to 10. """ eigv = eigsh(H, k, which="SA", return_eigenvectors=False, tol=0) return np.real(eigv[::-1]) # %% def eigenvalues_qiskit(qOp: MatrixOp, k: int = 10): """Compute the lowest k eigenvalues of a quantum operator in matrix form qOp. Internally it uses numpy. Args: qOp (MatrixOp): The quantum operator build from a matrix. k (int, optional): The number of lowest eigenvalues. Defaults to 10. """ mes = NumPyEigensolver(k) # k is the number of eigenvalues to compute result = mes.compute_eigenvalues(qOp) return np.real(result.eigenvalues) # %% def check_expectation(H, O, k: int = 1): """Compute the lowest k eigenstates of a sparse symmetric matrix H and then compute the expectation value of O. Args: H (scipy.sparse matrix): The Hamiltonian in the form of a sparse matrix O (scipy.sparse matrix): The operator to "measure" in the form of a sparse matrix k (int): The number of lowest eigenstates to compute. Defaults to 1. """ _, eigk = eigsh(H, k, which="SA", return_eigenvectors=True, tol=0) expect = [] for i in np.arange(k): bra = eigk[:,i].conjugate().transpose() ket = eigk[:,i] expect.append(bra.dot(O.dot(ket))) return np.real(np.array(expect)) # %% def run_vqe( L: int = 2, N: int = 2, g2N: float = 0.2, optimizer: str = "COBYLA", maxit: int = 5000, varform: list = ["ry"], depth: int = 3, nrep: int = 1, rngseed: int = 0, G2: bool = False, h5: bool = True, ): """Run the main VQE solver for a minimal BMN Hamiltonian where bosons are LxL matrices and the 't Hooft coupling is g2N for a SU(N) gauge group. The VQE is initialized with a specific optimizer and a specific variational quantum circuit based on EfficientSU2. Args: L (int, optional): Cutoff of each bosonic degree of freedom. Defaults to 2. N (int, optional): Colors for the SU(N) gauge group. Defaults to 2. g2N (float, optional): 't Hooft coupling. Defaults to 0.2. optimizer (str, optional): VQE classical optimizer. Defaults to "COBYLA". maxit (int, optional): Max number of iterations for the optimizer. Defaults to 5000. varform (str, optional): EfficientSU2 rotation gates. Defaults to 'ry'. depth (int, optional): Depth of the variational form. Defaults to 3. nrep (int, optional): Number of different random initializations of parameters. Defaults to 1. rngseed (int, optional): The random seed. Defaults to 0. G2 (bool, optional): The flag to compute the expectation value of the gauge Casimir. Defaults to False. h5 (bool, optional): The flag to save in HDF5 format. Defaults to True. """ # Create the matrix Hamiltonian H = bmn2_hamiltonian(L, N, g2N) # Now, we take the Hamiltonian matrix and map it onto a qubit operator. qubitOp = MatrixOp(primitive=H) # check the exact eigenvalues print(f"Exact Result of discrete hamiltonian (matrix): {eigenvalues_scipy(H)}") print( f"Exact Result of discrete hamiltonian (qubit): {eigenvalues_qiskit(qubitOp)}" ) # create the gauge casimir and check it if requested if G2: G = build_gauge_casimir(L,N) print(f"Exact Result of Casimir on GS (matrix): {check_expectation(H,G)}") gOp = MatrixOp(primitive=G) # Next, we create the variational form. var_form = EfficientSU2( qubitOp.num_qubits, su2_gates=varform, entanglement="full", reps=depth ) # start a quantum instance # fix the random seed of the simulator to make values reproducible rng = np.random.default_rng(seed=rngseed) algorithm_globals.random_seed = rngseed backend = Aer.get_backend( "statevector_simulator", max_parallel_threads=6, max_parallel_experiments=0 ) q_instance = QuantumInstance( backend, seed_transpiler=rngseed, seed_simulator=rngseed ) # initialize optimizers' parameters: number of iterations optimizers = { "COBYLA": COBYLA(maxiter=maxit), "L-BFGS-B": L_BFGS_B(maxfun=maxit), "SLSQP": SLSQP(maxiter=maxit), "NELDER-MEAD": NELDER_MEAD(maxfev=maxit), } print(f"\nRunning VQE main loop ...") start_time = time.time() try: optim = optimizers[optimizer] print(f"{optimizer} settings: {optim.settings}") except KeyError: print( f"Optimizer {optimizer} not found in our list. Try one of {[x for x in optimizers.keys()]}" ) return results = {"counts": [], "energy": [], "casimir": []} casimir_result = 'NaN' # callback functions to store the counts from each iteration of the VQE def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # run multiple random initial points for i in np.arange(nrep): counts = [] values = [] # initital points for the angles of the rotation gates random_init = rng.uniform(-2 * np.pi, 2 * np.pi, var_form.num_parameters) # Setup the VQE algorithm vqe = VQE( ansatz=var_form, optimizer=optim, initial_point=random_init, quantum_instance=q_instance, callback=store_intermediate_result, ) # run the VQE with our Hamiltonian operator if G2: result = vqe.compute_minimum_eigenvalue(qubitOp,aux_operators=[gOp]) vqe_result = np.real(result.eigenvalue) casimir_result = np.real(result.aux_operator_eigenvalues[0,0]) print(f"[{i}] - {varform} - [{optimizer}]: VQE gs energy: {vqe_result} | VQE gs gauge casimir: {casimir_result}") else: result = vqe.compute_minimum_eigenvalue(qubitOp) vqe_result = np.real(result.eigenvalue) print(f"[{i}] - {varform} - [{optimizer}]: VQE gs energy: {vqe_result}") # collect results results["counts"].append(counts) results["energy"].append(values) results["casimir"].append(casimir_result) end_time = time.time() runtime = end_time - start_time print(f"Program runtime: {runtime} s") # make a dataframe from the results and save it on disk with HDF5 df = pd.DataFrame.from_dict(results) data_types_dict = {"counts": int, "energy": float} df = df.explode(["counts", "energy"]).astype(data_types_dict).rename_axis("rep") # report summary of energy across reps converged = df["energy"].groupby("rep").apply(min).values print(f"Statistics across {nrep} repetitions:\n-------------------") print( f"Least upper bound: {np.min(converged)}\nWorst upper bound: {np.max(converged)}\nMean bound: {np.mean(converged)}\nStd bound: {np.std(converged)}" ) # save on disk varname = "-".join(varform) g2Nstr = str(g2N).replace(".", "") if h5: outfile = f"data/miniBMN_L{L}_l{g2Nstr}_convergence_{optimizer}_{varname}_depth{depth}_reps{nrep}_max{maxit}.h5" print(f"Save results on disk: {outfile}") df.to_hdf(outfile, "vqe") else: outfile = f"data/miniBMN_L{L}_l{g2Nstr}_convergence_{optimizer}_{varname}_depth{depth}_reps{nrep}_max{maxit}.gz" print(f"Save results on disk: {outfile}") df.to_pickle(outfile) return # %% if __name__ == "__main__": fire.Fire(run_vqe)
https://github.com/arian-code/nptel_quantum_assignments
arian-code
from sympy import * from sympy.physics.quantum.state import Ket, Bra from sympy.physics.quantum import TensorProduct import numpy as np init_printing(use_unicode=True) # Q bit gates H=Matrix([[1/sqrt(2), 1/sqrt(2)],[1/sqrt(2), -1/sqrt(2)]]) S=Matrix([[1, 0],[0, I]]) X=Matrix([[0, 1],[1, 0]]) Y=Matrix([[0, -I],[I, 0]]) Z=Matrix([[1, 0],[0, -1]]) Identity=Matrix([[1, 0],[0, 1]]) H, S, X, Y, Z, Identity #Q bit gates CCX=Matrix([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]]) CNOT=Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) SWAP=Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) CIIX=(TensorProduct(Identity, Identity, SWAP) #4 qbit CNOT, Cqbit=0 and acted qbit=3 *TensorProduct(Identity, SWAP, Identity) *TensorProduct(CNOT, Identity, Identity) *TensorProduct(Identity, SWAP, Identity) *TensorProduct(Identity, Identity, SWAP)) CCX, SWAP,CIIX, CNOT zero=Matrix([[1],[0]]) one=Matrix([[0],[1]]) plus=Matrix([[1/sqrt(2)], [1/sqrt(2)]]) minus=Matrix([[1/sqrt(2)], [-1/sqrt(2)]]) zero, one, plus, minus circuit=(TensorProduct(Identity, Identity, CNOT) * TensorProduct(Identity, CCX) * CIIX * TensorProduct(H, Identity, H, H) * TensorProduct(zero, one, zero, one)) circuit lhs=circuit lhs #option A rhs=TensorProduct(minus, one, plus, minus) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option B rhs=(1/sqrt(2))*(TensorProduct(minus, one, zero, minus)+TensorProduct(minus, one, one, minus)) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option C rhs=(-1)*(TensorProduct(plus, one, plus, minus)) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option D rhs=(TensorProduct(plus, one, plus, minus)) print (lhs) print (rhs) if (lhs==rhs): print ("It is true") else: print ("It is false") #option A and B opt_b=(1/sqrt(2))*(TensorProduct(minus, one, zero, minus)+TensorProduct(minus, one, one, minus)) opt_b opt_a=TensorProduct(minus, one, plus, minus) opt_a
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for graph MPL drawer""" import unittest import os from test.visual import VisualTestUtilities from contextlib import contextmanager from pathlib import Path from qiskit import BasicAer, execute from qiskit.test import QiskitTestCase from qiskit import QuantumCircuit from qiskit.utils import optionals from qiskit.visualization.state_visualization import state_drawer from qiskit.visualization.counts_visualization import plot_histogram from qiskit.visualization.gate_map import plot_gate_map, plot_coupling_map from qiskit.providers.fake_provider import ( FakeArmonk, FakeBelem, FakeCasablanca, FakeRueschlikon, FakeMumbai, FakeManhattan, ) if optionals.HAS_MATPLOTLIB: from matplotlib.pyplot import close as mpl_close else: raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".') BASE_DIR = Path(__file__).parent RESULT_DIR = Path(BASE_DIR) / "graph_results" TEST_REFERENCE_DIR = Path(BASE_DIR) / "references" FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures" FAILURE_PREFIX = "graph_failure_" @contextmanager def cwd(path): """A context manager to run in a particular path""" oldpwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(oldpwd) class TestGraphMatplotlibDrawer(QiskitTestCase): """Graph MPL visualization""" def setUp(self): super().setUp() self.graph_state_drawer = VisualTestUtilities.save_data_wrap( state_drawer, str(self), RESULT_DIR ) self.graph_count_drawer = VisualTestUtilities.save_data_wrap( plot_histogram, str(self), RESULT_DIR ) self.graph_plot_gate_map = VisualTestUtilities.save_data_wrap( plot_gate_map, str(self), RESULT_DIR ) self.graph_plot_coupling_map = VisualTestUtilities.save_data_wrap( plot_coupling_map, str(self), RESULT_DIR ) if not os.path.exists(FAILURE_DIFF_DIR): os.makedirs(FAILURE_DIFF_DIR) if not os.path.exists(RESULT_DIR): os.makedirs(RESULT_DIR) def tearDown(self): super().tearDown() mpl_close("all") @staticmethod def _image_path(image_name): return os.path.join(RESULT_DIR, image_name) @staticmethod def _reference_path(image_name): return os.path.join(TEST_REFERENCE_DIR, image_name) def test_plot_bloch_multivector(self): """test bloch sphere See https://github.com/Qiskit/qiskit-terra/issues/6397. """ circuit = QuantumCircuit(1) circuit.h(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "bloch_multivector.png" self.graph_state_drawer(state=state, output="bloch", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_state_hinton(self): """test plot_state_hinton""" circuit = QuantumCircuit(1) circuit.x(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "hinton.png" self.graph_state_drawer(state=state, output="hinton", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_state_qsphere(self): """test for plot_state_qsphere""" circuit = QuantumCircuit(1) circuit.x(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "qsphere.png" self.graph_state_drawer(state=state, output="qsphere", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_state_city(self): """test for plot_state_city""" circuit = QuantumCircuit(1) circuit.x(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "state_city.png" self.graph_state_drawer(state=state, output="city", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_state_paulivec(self): """test for plot_state_paulivec""" circuit = QuantumCircuit(1) circuit.x(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "paulivec.png" self.graph_state_drawer(state=state, output="paulivec", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram(self): """for testing the plot_histogram""" # specifing counts because we do not want oscillation of # result until a changes is made to plot_histogram counts = {"11": 500, "00": 500} fname = "histogram.png" self.graph_count_drawer(counts, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_with_rest(self): """test plot_histogram with 2 datasets and number_to_keep""" data = [{"00": 3, "01": 5, "10": 6, "11": 12}] fname = "histogram_with_rest.png" self.graph_count_drawer(data, number_to_keep=2, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_2_sets_with_rest(self): """test plot_histogram with 2 datasets and number_to_keep""" data = [ {"00": 3, "01": 5, "10": 6, "11": 12}, {"00": 5, "01": 7, "10": 6, "11": 12}, ] fname = "histogram_2_sets_with_rest.png" self.graph_count_drawer(data, number_to_keep=2, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_color(self): """Test histogram with single color""" counts = {"00": 500, "11": 500} fname = "histogram_color.png" self.graph_count_drawer(data=counts, color="#204940", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_multiple_colors(self): """Test histogram with multiple custom colors""" counts = [ {"00": 10, "01": 15, "10": 20, "11": 25}, {"00": 25, "01": 20, "10": 15, "11": 10}, ] fname = "histogram_multiple_colors.png" self.graph_count_drawer( data=counts, color=["#204940", "#c26219"], filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_hamming(self): """Test histogram with hamming distance""" counts = {"101": 500, "010": 500, "001": 500, "100": 500} fname = "histogram_hamming.png" self.graph_count_drawer(data=counts, sort="hamming", target_string="101", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_value_sort(self): """Test histogram with sorting by value""" counts = {"101": 300, "010": 240, "001": 80, "100": 150, "110": 160, "000": 280, "111": 60} fname = "histogram_value_sort.png" self.graph_count_drawer(data=counts, sort="value", target_string="000", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_desc_value_sort(self): """Test histogram with sorting by descending value""" counts = {"101": 150, "010": 50, "001": 180, "100": 10, "110": 190, "000": 80, "111": 260} fname = "histogram_desc_value_sort.png" self.graph_count_drawer( data=counts, sort="value_desc", target_string="000", filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_legend(self): """Test histogram with legend""" counts = [{"0": 50, "1": 30}, {"0": 30, "1": 40}] fname = "histogram_legend.png" self.graph_count_drawer( data=counts, legend=["first", "second"], filename=fname, figsize=(15, 5), ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_title(self): """Test histogram with title""" counts = [{"0": 50, "1": 30}, {"0": 30, "1": 40}] fname = "histogram_title.png" self.graph_count_drawer(data=counts, title="My Histogram", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_1_qubit_gate_map(self): """Test plot_gate_map using 1 qubit backend""" # getting the mock backend from FakeProvider backend = FakeArmonk() fname = "1_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_5_qubit_gate_map(self): """Test plot_gate_map using 5 qubit backend""" # getting the mock backend from FakeProvider backend = FakeBelem() fname = "5_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_7_qubit_gate_map(self): """Test plot_gate_map using 7 qubit backend""" # getting the mock backend from FakeProvider backend = FakeCasablanca() fname = "7_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_16_qubit_gate_map(self): """Test plot_gate_map using 16 qubit backend""" # getting the mock backend from FakeProvider backend = FakeRueschlikon() fname = "16_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_27_qubit_gate_map(self): """Test plot_gate_map using 27 qubit backend""" # getting the mock backend from FakeProvider backend = FakeMumbai() fname = "27_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_65_qubit_gate_map(self): """test for plot_gate_map using 65 qubit backend""" # getting the mock backend from FakeProvider backend = FakeManhattan() fname = "65_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_figsize(self): """Test figsize parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeBelem() fname = "figsize.png" self.graph_plot_gate_map(backend=backend, figsize=(10, 10), filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_qubit_size(self): """Test qubit_size parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeBelem() fname = "qubit_size.png" self.graph_plot_gate_map(backend=backend, qubit_size=38, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_qubit_color(self): """Test qubit_color parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeCasablanca() fname = "qubit_color.png" self.graph_plot_gate_map(backend=backend, qubit_color=["#ff0000"] * 7, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_qubit_labels(self): """Test qubit_labels parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeCasablanca() fname = "qubit_labels.png" self.graph_plot_gate_map( backend=backend, qubit_labels=list(range(10, 17, 1)), filename=fname ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_line_color(self): """Test line_color parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeManhattan() fname = "line_color.png" self.graph_plot_gate_map(backend=backend, line_color=["#00ff00"] * 144, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_font_color(self): """Test font_color parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeManhattan() fname = "font_color.png" self.graph_plot_gate_map(backend=backend, font_color="#ff00ff", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_coupling_map(self): """Test plot_coupling_map""" num_qubits = 5 qubit_coordinates = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]] coupling_map = [[1, 0], [1, 2], [1, 3], [3, 4]] fname = "coupling_map.png" self.graph_plot_coupling_map( num_qubits=num_qubits, qubit_coordinates=qubit_coordinates, coupling_map=coupling_map, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_bloch_multivector_figsize_improvements(self): """test bloch sphere figsize, font_size, title_font_size and title_pad See https://github.com/Qiskit/qiskit-terra/issues/7263 and https://github.com/Qiskit/qiskit-terra/pull/7264. """ circuit = QuantumCircuit(3) circuit.h(1) circuit.sxdg(2) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "bloch_multivector_figsize_improvements.png" self.graph_state_drawer( state=state, output="bloch", figsize=(3, 2), font_size=10, title="|0+R> state", title_font_size=14, title_pad=8, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) if __name__ == "__main__": unittest.main(verbosity=1)
https://github.com/mrvee-qC-bee/SMU_Feb1
mrvee-qC-bee
#make sure your qiskit version is up to date import qiskit.tools.jupyter %qiskit_version_table from qiskit import QuantumCircuit # Create a Quantum Circuit acting on a quantum register of two qubits circ = QuantumCircuit(2) print(circ) # Add a H gate on qubit 0, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. circ.cx(0, 1) circ.draw('mpl', style="iqp") #One can also draw this as an ascii drawing circ.draw() from qiskit.primitives import Sampler #Instantiate a new Sampler object sampler = Sampler() #We'll also need to add measurement circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) # Insert measurements on all qubits circ.measure_all() circ.draw('mpl', style='iqp') # Now run the job and examine the results sampler_job = sampler.run(circ) result = sampler_job.result() print(f"Job Result:\n>>> {result}") print(f" > Quasi-probability distribution (integer): {result.quasi_dists[0]}") print(f" > Quasi-probability distribution (bits): {result.quasi_dists[0].binary_probabilities(2)}") print(f" > Metadata: {result.metadata[0]}") from qiskit.tools.visualization import plot_distribution prob_distribution = sampler_job.result().quasi_dists[0].binary_probabilities() plot_distribution(prob_distribution) from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session #Initialize a QiskitRuntimeService object service = QiskitRuntimeService() #We will use the 127-qubit ibm_nazca or 133-qubit ibm_torino backend backend = service.get_backend('ibm_cusco') session = Session(service=service, backend=backend) # sampler = Sampler(backend=backend) sampler = Sampler(session=session) job = sampler.run(circ) print(f">>> Job ID: {job.job_id()}") print(f">>> Session ID: {job.session_id}") print(f">>> Job Status: {job.status()}") # Use a job id from a previous result job = service.job("cnxwrpjmbjng0081zhc0") print(f">>> Job Status: {job.status()}") result = job.result() print(f"Job Result:\n>>> {result}") print(f" > Quasi-probability distribution (integer): {result.quasi_dists[0]}") print(f" > Quasi-probability distribution (bits): {result.quasi_dists[0].binary_probabilities(2)}") print(f" > Metadata: {result.metadata[0]}") from qiskit.visualization import plot_distribution import matplotlib.pyplot as plt plt.style.use('dark_background') #plot_distribution(result.quasi_dists[0]) plot_distribution([result.quasi_dists[0].binary_probabilities(2),prob_distribution]) from qiskit import QuantumRegister, ClassicalRegister #Create the circuit qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) # we can also write "qc = QuantumCircuit(2,2)" #Add the hadamard and CNOT gates to the circuit qc.h(0) qc.cx(0, 1) qc.draw('mpl', style="iqp") # Import the SparesPauliOp class and create our observables variable from qiskit.quantum_info import SparsePauliOp observable = SparsePauliOp(["II", "XX", "YY", "ZZ"], coeffs=[1, 1, -1, 1]) # Import qiskit primitives from qiskit.primitives import Estimator estimator = Estimator() job = estimator.run(qc, observable) result_exact = job.result() print(result_exact) print(f"Expectation Value of <II+XX-YY+ZZ> = {result_exact.values[0]:.3f}") from qiskit_ibm_runtime import Estimator, Session #Initialize a QiskitRuntimeService object service = QiskitRuntimeService() #We will use the 127-qubit ibm_nazca backend backend = service.get_backend('ibm_torino') # create a Runtime session for efficient execution (optional) session = Session(service=service, backend=backend) # estimator = Estimator(backend=backend) estimator = Estimator(session=session) #Here we can get some status information about the backend status = backend.status() is_operational = status.operational jobs_in_queue = status.pending_jobs print('Operational?: {} \n Jobs in Queue: {}\n'.format(is_operational, jobs_in_queue)) # We can also obtain some configuration information config = backend.configuration() print(64*"#","\nConfiguration for: {}, version: {}".format(config.backend_name, config.backend_version)) print(" Number of Qubits: {}".format(config.n_qubits)) print(" Basis Gates: {}".format(config.basis_gates)) print(" OpenPulse Enabled: {}".format(config.open_pulse)) job = estimator.run(qc, observable) print(f">>> Job ID: {job.job_id()}") print(f">>> Session ID: {job.session_id}") print(f">>> Job Status: {job.status()}") # Use a job id from a previous result job = service.job("cnxwwhtmbjng0081zhxg") print(f">>> Job Status: {job.status()}") #Examine our results once the job has completed result = job.result() print(f">>> {result}") print(f" > Expectation value: {result.values[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt plt.style.use('dark_background') data = {"Ideal": result_exact.values[0],"Result": result.values[0]} plt.bar(range(len(data)), data.values(), align='center', color = "#7793f2") plt.xticks(range(len(data)), list(data.keys())) plt.show() from qiskit_ibm_runtime import Options # To set our resilience and optimization level we need to create this `Options` object options = Options() options.resilience_level = 2 options.optimization_level = 3 # We'll prepare the same example circuit as before qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) # we can also write "qc = QuantumCircuit(2,2)" #Add the hadamard and CNOT gates to the circuit qc.h(0) qc.cx(0, 1) # We'll also instantiate a new Runtime Estimator() object # estimator = Estimator(options=options, backend=backend) estimator = Estimator(options=options, session=session) # and use the same observable as before observable = SparsePauliOp(["II", "XX", "YY", "ZZ"], coeffs=[1, 1, -1, 1]) job = estimator.run(circuits=qc, observables=observable) print(f">>> Job ID: {job.job_id()}") print(f">>> Session ID: {job.session_id}") print(f">>> Job Status: {job.status()}") # Use a job id from a previous result job = service.job("cnxwx04ja3gg0085f6cg") print(f">>> Job Status: {job.status()}") #Examine our results once the job has completed result_mitigated = job.result() print(f">>> {result_mitigated}") print(f" > Expectation value: {result_mitigated.values[0]}") print(f" > Metadata: {result_mitigated.metadata[0]}") from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt plt.style.use('dark_background') data = {"Ideal": result_exact.values[0],"Result": result.values[0],"Mitigated result": result_mitigated.values[0]} plt.bar(range(len(data)), data.values(), align='center', color = "#7793f2") plt.xticks(range(len(data)), list(data.keys())) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": ### added x gate ### qc.x(qubit) qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import qiskit.qasm3 program = """ OPENQASM 3.0; include "stdgates.inc"; input float[64] a; qubit[3] q; bit[2] mid; bit[3] out; let aliased = q[0:1]; gate my_gate(a) c, t { gphase(a / 2); ry(a) c; cx c, t; } gate my_phase(a) c { ctrl @ inv @ gphase(a) c; } my_gate(a * 2) aliased[0], q[{1, 2}][0]; measure q[0] -> mid[0]; measure q[1] -> mid[1]; while (mid == "00") { reset q[0]; reset q[1]; my_gate(a) q[0], q[1]; my_phase(a - pi/2) q[1]; mid[0] = measure q[0]; mid[1] = measure q[1]; } if (mid[0]) { let inner_alias = q[{0, 1}]; reset inner_alias; } out = measure q; """ circuit = qiskit.qasm3.loads(program) circuit.draw("mpl")
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/JouziP/MQITE
JouziP
# -*- 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. """ Created on Wed Mar 11 18:03:12 2020 Functional interface to Qasm2 source loading and exporting Supersede QuantumCircuit member functions Provide for pluggable qasm translator Based on conversation with Dr. Luciano Bello @author: jax """ from importlib import import_module from os import linesep from typing import List, BinaryIO, TextIO from qiskit import QuantumCircuit, QiskitError from qiskit_openqasm2 import Qasm from .funhelp import qasm_load, qasm_export def _load_from_string(qasm_src: str or List[str], loader: str = None, include_path: str = '') -> QuantumCircuit: """ Parameters ---------- qasm_src : str or List[str] Qasm program source as string or list of string. loader : str, optional Name of module with functional attribute load(filename: str = None, data: str = None, include_path: str = None) -> QuantumCircuit: ... to use for qasm translation. None means "use Qiskit qasm" The default is None. include_path : str, optional Loader-specific include path for qasm include directives. The default is ''. Raises ------ QiskitError If unknown loader. Returns ------- QuantumCircuit Circuit factoried from Qasm src. """ circ = None if not loader: if isinstance(qasm_src, list): qasm_src = ''.join(s + linesep for s in qasm_src) qasm = Qasm(data=qasm_src) circ = qasm_load(qasm) else: m_m = import_module(loader) circ = getattr(m_m, 'load')(data=qasm_src, include_path=include_path) return circ def _load_from_file(filename: str, loader: str = None, include_path: str = '') -> QuantumCircuit: """ Parameters ---------- filename : str Filepath to qasm program source. loader : str, optional Name of module with functional attribute load(filename: str = None, data: str = None, include_path: str = None) -> QuantumCircuit: ... to use for qasm translation. None means "use Qiskit qasm" The default is None. include_path : str, optional Loader-specific include path for qasm include directives. The default is ''. Returns ------- QuantumCircuit Circuit factoried from Qasm src. """ circ = None if not loader: qasm = Qasm(filename=filename) circ = qasm_load(qasm) else: m_m = import_module(loader) circ = getattr(m_m, 'load')(filename=filename, include_path=include_path) return circ def load(data: str or List[str] = None, filename: str = None, loader: str = None, include_path: str = None) -> QuantumCircuit: """ Parameters ---------- data : str or List[str], optional Qasm program source as string or list of string. The default is None. filename : str, optional Filepath to qasm program source. The default is None. loader : str, optional Name of module with functional attribute load(filename: str = None, data: str = None, include_path: str = None) -> QuantumCircuit: ... to use for qasm translation. None means "use Qiskit qasm" The default is None. include_path : str, optional Loader-specific include path for qasm include directives. The default is None. Raises ------ QiskitError If both filename and data or neither filename nor data. Returns ------- QuantumCircuit The factoried circuit. """ if (not data and not filename) or (data and filename): raise QiskitError("To load, either filename or data (and not both) must be provided.") circ = None if data: circ = _load_from_string(data, loader=loader, include_path=include_path) elif filename: circ = _load_from_file(filename, loader=loader, include_path=include_path) return circ def export(qc: QuantumCircuit, exporter: str = None, file: BinaryIO or TextIO = None, filename: str = None, include_path: str = None,) -> str: """ Decompile a QuantumCircuit into Return OpenQASM string Parameters ---------- qc : QuantumCircuit Circuit to decompile ("export") exporter : str, optional Name of module with functional attribute export(qc: QuantumCircuit, include_path: str = None) -> QuantumCircuit: ... to use for qasm translation. None means "use Qiskit qasm" The default is None. file : BinaryIO or TextIO, optional File object to write to as well as return str Written in UTF-8 Caller must close file. Mutually exclusive with filename= The default is None. filename : str, optional Name of file to write export to as well as return str Mutually exclusive with file= The default is None. include_path: str, optional Unloader-specific include path for qasm include directives Raises ------ QiskitError If both filename and file Returns ------- str OpenQASM source for circuit. """ if filename and file: raise QiskitError("export: file= and filename= are mutually exclusive") qasm_src = None if not exporter: qasm_src = qasm_export(qc) else: m_m = import_module(exporter) qasm_src = getattr(m_m, 'export')(qc, include_path=include_path) if filename: f_f = open(filename, 'w') f_f.write(qasm_src) f_f.close() elif file: if 'b' in file.mode: file.write(bytes(qasm_src, 'utf-8')) else: file.write(qasm_src) return qasm_src
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests PassManager.run()""" from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import CXGate from qiskit.transpiler.preset_passmanagers import level_1_pass_manager from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeMelbourne from qiskit.transpiler import Layout, PassManager from qiskit.transpiler.passmanager_config import PassManagerConfig class TestPassManagerRun(QiskitTestCase): """Test default_pass_manager.run(circuit(s)).""" def test_bare_pass_manager_single(self): """Test that PassManager.run(circuit) returns a single circuit.""" qc = QuantumCircuit(1) pm = PassManager([]) new_qc = pm.run(qc) self.assertIsInstance(new_qc, QuantumCircuit) self.assertEqual(qc, new_qc) # pm has no passes def test_bare_pass_manager_single_list(self): """Test that PassManager.run([circuit]) returns a list with a single circuit.""" qc = QuantumCircuit(1) pm = PassManager([]) result = pm.run([qc]) self.assertIsInstance(result, list) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], QuantumCircuit) self.assertEqual(result[0], qc) # pm has no passes def test_bare_pass_manager_multiple(self): """Test that PassManager.run(circuits) returns a list of circuits.""" qc0 = QuantumCircuit(1) qc1 = QuantumCircuit(2) pm = PassManager([]) result = pm.run([qc0, qc1]) self.assertIsInstance(result, list) self.assertEqual(len(result), 2) for qc, new_qc in zip([qc0, qc1], result): self.assertIsInstance(new_qc, QuantumCircuit) self.assertEqual(new_qc, qc) # pm has no passes def test_default_pass_manager_single(self): """Test default_pass_manager.run(circuit). circuit: qr0:-[H]--.------------ -> 1 | qr1:-----(+)--.-------- -> 2 | qr2:---------(+)--.---- -> 3 | qr3:-------------(+)--- -> 5 device: 0 - 1 - 2 - 3 - 4 - 5 - 6 | | | | | | 13 - 12 - 11 - 10 - 9 - 8 - 7 """ qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) coupling_map = FakeMelbourne().configuration().coupling_map initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] pass_manager = level_1_pass_manager( PassManagerConfig.from_backend( FakeMelbourne(), initial_layout=Layout.from_qubit_list(initial_layout), seed_transpiler=42, ) ) new_circuit = pass_manager.run(circuit) self.assertIsInstance(new_circuit, QuantumCircuit) bit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qregs[0])} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([bit_indices[x] for x in instruction.qubits], coupling_map) def test_default_pass_manager_two(self): """Test default_pass_manager.run(circuitS). circuit1 and circuit2: qr0:-[H]--.------------ -> 1 | qr1:-----(+)--.-------- -> 2 | qr2:---------(+)--.---- -> 3 | qr3:-------------(+)--- -> 5 device: 0 - 1 - 2 - 3 - 4 - 5 - 6 | | | | | | 13 - 12 - 11 - 10 - 9 - 8 - 7 """ qr = QuantumRegister(4, "qr") circuit1 = QuantumCircuit(qr) circuit1.h(qr[0]) circuit1.cx(qr[0], qr[1]) circuit1.cx(qr[1], qr[2]) circuit1.cx(qr[2], qr[3]) circuit2 = QuantumCircuit(qr) circuit2.cx(qr[1], qr[2]) circuit2.cx(qr[0], qr[1]) circuit2.cx(qr[2], qr[3]) coupling_map = FakeMelbourne().configuration().coupling_map initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] pass_manager = level_1_pass_manager( PassManagerConfig.from_backend( FakeMelbourne(), initial_layout=Layout.from_qubit_list(initial_layout), seed_transpiler=42, ) ) new_circuits = pass_manager.run([circuit1, circuit2]) self.assertIsInstance(new_circuits, list) self.assertEqual(len(new_circuits), 2) for new_circuit in new_circuits: self.assertIsInstance(new_circuit, QuantumCircuit) bit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qregs[0])} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([bit_indices[x] for x in instruction.qubits], coupling_map)
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
from numpy.polynomial.polynomial import Polynomial from numpy.polynomial.polynomial import polyfit import matplotlib.pyplot as plt import numpy as np import copy from qiskit.circuit.library import QFT from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from collections.abc import Iterable def hellinger_fidelity(p, q): p_sum = sum(p.values()) q_sum = sum(q.values()) p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) dist = np.sqrt(total)/np.sqrt(2) return 1-dist from numpy.polynomial.polynomial import Polynomial from numpy.polynomial.polynomial import polyfit from collections.abc import Iterable import functools import math import random import numpy as np import copy ########## Classical math functions def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist def power_f(i, num_state_qubits, power): if isinstance(i, Iterable): out = [] for val in i: out.append((val / ((2**num_state_qubits) - 1))**power) return np.array(out) else: return (i / ((2**num_state_qubits) - 1))**power def estimated_value(target_dist, f): avg = 0 for key in target_dist.keys(): x = int(key,2) avg += target_dist[key]*f(x) return avg def zeta_from_f(i, func, epsilon, degree, c): """ Intermediate polynomial derived from f to serve as angle for controlled Ry gates. """ rad = np.sqrt(c*(func(i) - 0.5) + 0.5) return np.arcsin(rad) def simplex(n, k): """ Get all ordered combinations of n integers (zero inclusive) which add up to k; the n-dimensional k simplex. """ if k == 0: z = [0]*n return [z] l = [] for p in simplex(n,k-1): for i in range(n): a = p[i]+1 ns = copy.copy(p) ns[i] = a if ns not in l: l.append(ns) return l def binary_expansion(num_state_qubits, poly): """ Convert a polynomial into expression replacing x with its binary decomposition x_0 + 2 x_1 + 4 x_2 + ... Simplify using (x_i)^p = x_i for all integer p > 0 and collect coefficients of equivalent expression """ n = num_state_qubits if isinstance(poly, Polynomial): poly_c = poly.coef else: poly_c = poly out_front = {} out_front[()] = poly_c[0] for k in range(1,len(poly_c)): for pow_list in simplex(n,k): two_exp, denom, t = 0, 1, 0 for power in pow_list: two_exp += t*power denom *= np.math.factorial(power) t+=1 nz = np.nonzero(pow_list)[0] key = tuple(nz) if key not in out_front.keys(): out_front[key] = 0 out_front[key] += poly_c[k]*((np.math.factorial(k) / denom) * (2**(two_exp))) return out_front def starting_regions(num_state_qubits): """ For use in bisection search for state preparation subroutine. Fill out the necessary region labels for num_state_qubits. """ sub_regions = [] sub_regions.append(['1']) for d in range(1,num_state_qubits): region = [] for i in range(2**d): key = bin(i)[2:].zfill(d) + '1' region.append(key) sub_regions.append(region) return sub_regions def region_probs(target_dist, num_state_qubits): """ Fetch bisected region probabilities for the desired probability distribution {[p1], [p01, p11], [p001, p011, p101, p111], ...}. """ regions = starting_regions(num_state_qubits) probs = {} n = len(regions) for k in range(n): for string in regions[k]: p = 0 b = n-k-1 for i in range(2**b): subkey = bin(i)[2:].zfill(b) if b == 0: subkey = '' try: p += target_dist[string+subkey] except KeyError: pass probs[string] = p return probs %run mc_benchmark.py def arcsin_approx(f, x, epsilon, degree, c_star): zeta_ = functools.partial(zeta_from_f, func=f_, epsilon=epsilon, degree=degree, c=c_star) poly = Polynomial(polyfit(x, zeta_(x), degree)) return poly num_state_qubits_=2 epsilon_=0.05 degree_= 3 power = 2 c_star_ = (2*epsilon_)**(1/(degree_+1)) x_plot = np.linspace(0.0, 2**(num_state_qubits_) - 1, num=100) x_eval = np.linspace(0.0, 2**(num_state_qubits_) - 1, num= degree_+1) f_ = functools.partial(power_f, num_state_qubits=num_state_qubits_, power=power) poly_ = arcsin_approx(f_, x_eval, epsilon_, degree_, c_star_) def corrected_amplitudes(x): #return poly_(x) #return (np.sin(poly_(x))**2) return (((np.sin(poly_(x))**2) - 0.5) / c_star_) + 0.5 ######## plt.plot(x_plot, f_(x_plot), label="f") plt.plot(x_plot, corrected_amplitudes(x_plot), label=f"degree={degree_}") # Test coefficient list in the increasing degree; i.e. [a, b, c, ... {z}] for a + b x + c x^2 ... {z} x^n num_q = 2 coef_list = [3, 1, 1] poly = Polynomial(coef_list) print(poly.coef) print(binary_expansion(num_q, poly)) num_q = 3 t_d = {'101': 0, '000': 0.25, '011': 0.125, '100': 0.125, '001': 0.0, '010': 0.25, '110': 0.125, '111': 0.125} u_d = uniform_dist(num_q) m_d = {'000': 0.5, '001': 0.25, '010':0.25} # Change to whatever distribution you like dist = m_d qr_ = QuantumRegister(num_q) cr_ = ClassicalRegister(num_q) qc_ = QuantumCircuit(qr_, cr_) state_prep(qc_, qr_, dist, num_state_qubits=num_q) qc_.measure(qr_, cr_) from qiskit import execute, BasicAer backend = BasicAer.get_backend("dm_simulator") job = execute(qc_, backend, shots=1000) result = job.result() counts = result.get_counts() print('') print(dist) print(counts) print(hellinger_fidelity(dist,counts)) def state_prep(qc, qr, target_dist, num_state_qubits): """ Use controlled Ry gates to construct the superposition Sum \sqrt{p_i} |i> """ r_probs = region_probs(target_dist, num_state_qubits) regions = r_probs.keys() r_norm = {} for r in regions: num_controls = len(r) - 1 super_key = r[:num_controls] if super_key=='': r_norm[super_key] = 1 elif super_key == '1': r_norm[super_key] = r_probs[super_key] r_norm['0'] = 1-r_probs[super_key] else: try: r_norm[super_key] = r_probs[super_key] except KeyError: r_norm[super_key] = r_norm[super_key[:num_controls-1]] - r_probs[super_key[:num_controls-1] + '1'] norm = r_norm[super_key] p = 0 if norm != 0: p = r_probs[r] / norm theta = -2*np.arcsin(np.sqrt(p)) if r == '1': qc.ry(theta, num_state_qubits-1) else: for k in range(num_controls): if r[k] == '0': qc.x(num_state_qubits-1 - k) controls = [qr[num_state_qubits-1 - i] for i in range(num_controls)] qc.mcry(theta, controls, qr[num_state_qubits-1 - num_controls], q_ancillae=None) for k in range(num_controls): if r[k] == '0': qc.x(num_state_qubits-1 - k) def f_on_objective(qc, qr, f, epsilon=0.05, degree=3): """ Assume last qubit is the objective. Function f is evaluated on first n-1 qubits """ num_state_qubits = qc.num_qubits - 1 c_star = (2*epsilon)**(1/(degree+1)) f_ = functools.partial(f, num_state_qubits=num_state_qubits) zeta_ = functools.partial(zeta_from_f, func=f_, epsilon=epsilon, degree=degree, c=c_star) x_eval = np.linspace(0.0, 2**(num_state_qubits) - 1, num= degree+1) poly = Polynomial(polyfit(x_eval, zeta_(x_eval), degree)) b_exp = binary_expansion(num_state_qubits, poly) for controls in b_exp.keys(): theta = 2*b_exp[controls] controls = list(controls) if len(controls)==0: qc.ry(-theta, qr[num_state_qubits]) else: qc.mcry(-theta, [qr[i] for i in controls], qr[num_state_qubits], q_ancillae=None) from qiskit import execute, BasicAer backend = Aer.get_backend("dm_simulator") num_state_qubits_=4 epsilon_ = 0.05 degree_= 3 power = 1 c_star_ = (2*epsilon_)**(1/(degree_+1)) f_ = functools.partial(power_f, power=power) x_vals = list(range(2**num_state_qubits_)) y_vals = [] f_vals = f_(x_vals, num_state_qubits_) for i in x_vals: qr_ = QuantumRegister(num_state_qubits_+1) cr_ = ClassicalRegister(num_state_qubits_+1) qc_ = QuantumCircuit(qr_, cr_) b = bin(i)[2:].zfill(num_state_qubits_)[::-1] for q in range(len(b)): if b[q]=='1': qc_.x(q) f_on_objective(qc_, qr_, f_, epsilon_, degree_) qc_.measure(qr_, cr_) job = execute(qc_, backend, shots=1000) result = job.result() counts = result.get_counts() print(counts) try: print(i, '', b, '', counts['1'+b[::-1]]/1000) y_vals.append(counts['1'+b[::-1]]/1000) except KeyError: print(i, '', b, '', 0) y_vals.append(0) y_corrected = [] for y in y_vals: y_corrected.append(((y - 0.5) / c_star_) + 0.5) #plt.plot(x_vals, y_vals) plt.plot(x_vals, y_corrected) plt.plot(x_vals, f_vals) print('') plt.show() dist = u_d print(u_d) num_state_qubits_= 3 num_ancillas = 6 epsilon_=0.05 degree_= 2 power = 2 c_star_ = (2*epsilon_)**(1/(degree_+1)) p = uniform_dist dist = p(num_state_qubits_) f_ = functools.partial(power_f, power=power) qc_ = MonteCarloSampling(dist, f_, num_state_qubits_, num_ancillas, epsilon_, degree_) backend = Aer.get_backend("dm_simulator") job = execute(qc_, backend, shots=1000) result = job.result() counts = result.get_counts(qc_) v_string = max(counts, key=counts.get) v = int(v_string,2) #print(v, v_string) a = pow(np.sin(np.pi*v/pow(2,num_ancillas)),2) a_est = ((a - 0.5)/c_star_) + 0.5 a_exact = actual_(dist, f_, num_state_qubits_) print(a_est, a_exact) best_result = max(counts, key=counts.get) v = int(best_result,2) print(v, best_result) #a_ = pow(np.cos(2*np.pi*v/pow(2,num_ancillas)),2) #a_est = a_ best_result = max(counts, key=counts.get) v = int(best_result,2) a_int = pow(np.sin(np.pi*v/pow(2,num_ancillas)),2) a_est = ((a_int - 0.5) / c_star_) + 0.5 a_exact = actual_(dist,f_,num_state_qubits_) a_ex = ((a_exact - 0.5) * c_star_) + 0.5 print(a_est, a_exact) print(a_int, a_ex) print(counts) def actual_(dist, f_, num_state_qubits): s = 0 _f = functools.partial(f_, num_state_qubits=num_state_qubits) for key in dist.keys(): x = int(key,2) s += dist[key]*_f(x) return s def MonteCarloSampling(target_dist, f, num_state_qubits, num_ancillas, epsilon=0.05, degree=2): A_qr = QuantumRegister(num_state_qubits+1) A = QuantumCircuit(A_qr) state_prep(A, A_qr, target_dist, num_state_qubits) f_on_objective(A, A_qr, f, epsilon=epsilon, degree=degree) qc = AE_Subroutine(num_state_qubits, num_ancillas, A) return qc # Construct the grover-like operator and a controlled version of it def Ctrl_Q(num_state_qubits, A_circ): # index n is the objective qubit, and indexes 0 through n-1 are state qubits qc = QuantumCircuit(num_state_qubits+1, name=f"Q") temp_A = copy.copy(A_circ) A_gate = temp_A.to_gate() A_gate_inv = temp_A.inverse().to_gate() ### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ # -S_chi qc.x(num_state_qubits) qc.z(num_state_qubits) qc.x(num_state_qubits) # A_circ_inverse qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)]) # S_0 for i in range(num_state_qubits+1): qc.x(i) qc.h(num_state_qubits) qc.mcx([x for x in range(num_state_qubits)], num_state_qubits) qc.h(num_state_qubits) for i in range(num_state_qubits+1): qc.x(i) # A_circ qc.append(A_gate, [i for i in range(num_state_qubits+1)]) # Create a gate out of the Q operator qc.to_gate(label='Q') # and also a controlled version of it Ctrl_Q_ = qc.control(1) # and return both return Ctrl_Q_, qc def AE_Subroutine(num_state_qubits, num_ancillas, A_circuit): ctr, unctr = Ctrl_Q(num_state_qubits, A_circuit) qr_state = QuantumRegister(num_state_qubits+1) qr_ancilla = QuantumRegister(num_ancillas) cr = ClassicalRegister(num_ancillas) qc_full = QuantumCircuit(qr_ancilla, qr_state, cr) qc_full.append(A_circuit, [qr_state[i] for i in range(num_state_qubits+1)]) repeat = 1 for j in range(num_ancillas): qc_full.h(qr_ancilla[j]) for k in range(repeat): qc_full.append(ctr, [qr_ancilla[j]] + [qr_state[l] for l in range(num_state_qubits+1)]) repeat *= 2 qc_full.barrier() qc_full.append(QFT(num_qubits=num_ancillas, inverse=True), qr_ancilla) qc_full.barrier() qc_full.measure([qr_ancilla[m] for m in range(num_ancillas)], list(range(num_ancillas))) return qc_full
https://github.com/grossiM/Qiskit_workshop1019
grossiM
# qiskit packages from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, IBMQ, execute # visualization packages from qiskit.tools.visualization import plot_histogram, qx_color_scheme, plot_state_city, plot_bloch_multivector, plot_state_paulivec, plot_state_hinton, plot_state_qsphere backend = Aer.get_backend('qasm_simulator') # select the qasm simulator # to use a real processor uncomment the following lines: #IBMQ.load_accounts() #from qiskit.providers.ibmq import least_busy #backend = least_busy(IBMQ.backends(simulator=False)) #print("the best backend is " + backend.name()) # Create the registers q2 = QuantumRegister(2) c2 = ClassicalRegister(2) # Create the Bell's State bell = QuantumCircuit(q2, c2) bell.h(q2[0]) bell.cx(q2[0], q2[1]) # Measure the qubits in the standard base (Z) measureZZ = QuantumCircuit(q2, c2) measureZZ.measure(q2[0], c2[0]) measureZZ.measure(q2[1], c2[1]) bellZZ = bell+measureZZ # Measure the qubits in the superposition base (X) measureXX = QuantumCircuit(q2, c2) measureXX.h(q2) measureXX.measure(q2, c2) bellXX = bell+measureXX bellZZ.draw(output='mpl') circuits = [bellZZ,bellXX] job = execute(circuits, backend) result = job.result() #plot_histogram(result.get_counts(bellZZ)) legend = ['bellZZ', 'bellXX'] plot_histogram([result.get_counts(bellZZ), result.get_counts(bellXX)], legend=legend, sort='desc', figsize=(15,12), color=['orange', 'black'], bar_labels=False) # Create a circuit that measures the qubits in 0 and one that flips and measures them in 1: mixed1 = QuantumCircuit(q2, c2) mixed2 = QuantumCircuit(q2, c2) mixed2.x(q2) mixed1.measure(q2[0], c2[0]) mixed1.measure(q2[1], c2[1]) mixed2.measure(q2[0], c2[0]) mixed2.measure(q2[1], c2[1]) mixed1.draw(output='mpl') mixed2.draw(output='mpl') mixed_state = [mixed1,mixed2] job = execute(mixed_state, backend) result = job.result() counts1 = result.get_counts(mixed_state[0]) counts2 = result.get_counts(mixed_state[1]) from collections import Counter ground = Counter(counts1) excited = Counter(counts2) plot_histogram(ground+excited) backend = Aer.get_backend('') # select the appropriate backend # Create registers q2 = QuantumRegister(2) c2 = ClassicalRegister(2) # Create the Bell's State bell = QuantumCircuit(q2, c2) bell.h(q2[0]) bell.cx(q2[0], q2[1]) # Run the job to see the matrix that creates the entanglement circuit = bell job = execute(circuit, backend) result = job.result() print(result.get_unitary(bell, decimals=3)) backend = Aer.get_backend('') # select the appropriate simulator # Create registers q2 = QuantumRegister(2) c2 = ClassicalRegister(2) # Create the mixed state mix1 = QuantumCircuit(q2, c2) mix2 = QuantumCircuit(q2, c2) mix1.iden(q2) mix2.x(q2) # Execute the circuits to obtain the matrices mixed_state = [mix1,mix2] job = execute(mixed_state, backend) result = job.result() print(result.get_unitary(mixed_state[0], decimals=3),'\n \n',result.get_unitary(mixed_state[1],decimals=3)) backend= Aer.get_backend('qasm_simulator') q2 = QuantumRegister(2) c2 = ClassicalRegister(2) # Create Bell's State env = QuantumCircuit(q2, c2) env.h(q2[0]) env.cx(q2[0], q2[1]) # Apply the X gates env.x(q2[0]) env.iden(q2[1]) env.iden(q2[0]) env.x(q2[1]) meas = QuantumCircuit(q2, c2) meas.measure(q2[0], c2[0]) meas.measure(q2[1], c2[1]) env = env+meas env.draw(output='mpl') circuit = env job = execute(circuit, backend) result = job.result() plot_histogram(result.get_counts(env))
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb Udfp = (1/sqrt(2))*Matrix([[1,1j,0,0],[1j,1,0,0],[0,0,1,1j],[0,0,1j,1]]); Udfp Udfp*conjugate(Udfp), conjugate(Udfp)*Udfp # ok! Udf = (1/sqrt(2))*Matrix([[1,1j],[1j,1]]); Udf X = Matrix([[0,1],[1,0]]); C_Udf = tp(proj(cb(2,0)),id(2)) + tp(proj(cb(2,1)),Udf) C_Udf, tp(X,id(2))*C_Udf*tp(X,id(2)), tp(X,id(2))*C_Udf*tp(X,id(2))*C_Udf, C_Udf*tp(X,id(2))*C_Udf*tp(X,id(2)) C_Udf*tp(X,id(2))*C_Udf*tp(X,id(2)) def P(al): return Matrix([[1,0],[0,cos(al)+1j*sin(al)]]) S = Matrix([[1,0],[0,1j]]); Sd = Matrix([[1,0],[0,-1j]]); H = (1/sqrt(2))*Matrix([[1,1],[1,-1]]) X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]) def U(th,ph,lb): return Matrix([[cos(th/2),-(cos(lb)+1j*sin(lb))*sin(th/2)],[(cos(ph)+1j*sin(ph))*sin(th/2),cos(th/2)]]) th, ph, lb = symbols('theta phi lambda'); U(pi,-pi/2,pi/2)*S*X*H*X*S A = U(pi,-pi/2,pi/2)*S; B = H; C = S; A*B*C # = Udf^dagger != I a,b,c,d, x, y, z, w = symbols('a,b,c,d, x, y, z, w') A = Matrix([[a,b],[c,d]]); B = Matrix([[x,y],[z,w]]); A, B, A*B a = -1/sqrt(2); b = 1j/sqrt(2); c = b; d = a # para trocar o sinal dos elementos da diagonal principal solve([a*x+b*z+a, a*y+b*w-b, c*x+d*z-c, c*y+d*w+d], [x,y,z,w]) from qiskit import * from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter nshots = 8192 qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_belem') from qiskit.tools.monitor import job_monitor def state_prep(th, ph): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name = 'prep') qc.u(th, ph, 0, qr[0]) qc.u(th, ph, 0, qr[1]) return qc def qc_dfp(): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name='DFP') '''qc.x(qr[1]) qc.cu(math.pi/2, math.pi/2, -math.pi/2, 0.0, qr[1], qr[0]) # Udf controlada qc.x(qr[1]) qc.cu(math.pi/2, math.pi/2, -math.pi/2, 0.0, qr[1], qr[0])''' qc.cu(math.pi, math.pi/2, -math.pi/2, 0.0, qr[0], qr[1]) return qc qc_dfp_ = qc_dfp(); qc_dfp_.draw() ###### Para ver a matriz unitário implementada por um certo circuito quântico ########## backend = Aer.get_backend('unitary_simulator'); qc_dfp_ = qc_dfp(); job = execute(qc_dfp_, backend) result = job.result(); print(result.get_unitary(qc_dfp_, decimals=3)) # agora tá certo, mas ao contrário em relação aos qubits... qr = QuantumRegister(2); qc = QuantumCircuit(qr, name='DFP') #qc.cx(qr[0],qr[1]) # Sai a matrix para C21 qc.cx(qr[1],qr[0]) # Sai a matrix para C12 job = execute(qc, backend); result = job.result(); print(result.get_unitary(qc, decimals=3)) qr = QuantumRegister(2); qc = QuantumCircuit(qr, name='DFP') qc.h(qr[0]) #qc.cx(qr[0], qr[1]) # sai o estado certo, |00>+|11> qc.cx(qr[1], qr[0]) # sai |+0> qstc = state_tomography_circuits(qc, [qr[0],qr[1]]) job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') rho # Verificação da Udf controlada qr = QuantumRegister(2); qc = QuantumCircuit(qr, name='DFP') qc.x(qr[1]) qc.cu(math.pi/2, math.pi/2, -math.pi/2, 0.0, qr[1], qr[0]) # a sequência é target depois control qc.x(qr[1]) job = execute(qc, backend); result = job.result(); print(result.get_unitary(qc, decimals=3)) qc.draw() # Verificação da Udf controlada qr = QuantumRegister(2); qc = QuantumCircuit(qr, name='DFP') qc.cx(qr[1], qr[0]) # a sequência é target depois control job = execute(qc, backend); result = job.result(); print(result.get_unitary(qc, decimals=3)) def qc_mzi_dfp(ph): # quantum circuit for the Mach-Zehnder interferometer com DFP qr = QuantumRegister(2); qc = QuantumCircuit(qr) state_prep_ = state_prep(0, 0); qc.append(state_prep_, [qr[0],qr[1]]) # estado prep qc_dfp_ = qc_dfp(); qc.append(qc_dfp_, [qr[0],qr[1]]) # DFP qc.z(qr[1]); qc.y(qr[1]) # espelho qc.p(ph, qr[1]); # fase qc.s(qr[1]); qc.h(qr[1]); qc.s(qr[1]) # DF return qc qcmzi = qc_mzi_dfp(math.pi/8); qcmzi.draw() phmax = 2*math.pi; dph = phmax/20; ph = np.arange(0, phmax+dph, dph)#; ph d = ph.shape[0]; PD0teo = np.zeros(d); PD0sim = np.zeros(d); PD0exp = np.zeros(d) for j in range(0, d): PD0teo[j] = 1/2 # theoretical qr = QuantumRegister(2); qc = QuantumCircuit(qr) state_prep_ = state_prep(0, 0); qc.append(state_prep_, [qr[0],qr[1]]) # state preparation (estado |00>) qc_mzi_dfp_ = qc_mzi_dfp(ph[j]); qc.append(qc_mzi_dfp_, [qr[0],qr[1]]) # apply sim mzip qstc = state_tomography_circuits(qc, qr[1]) # circuit for state tomography job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') PD0sim[j] = rho[0,0].real #print(rho[0,0].real) # 1º fiz as simulações, só depois adicionei o código para os experimentos '''job = qiskit.execute(qstc, backend = device, shots = nshots) print(job.job_id()); job_monitor(job) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') PD0exp[j] = rho[0,0].real''' matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100) plt.plot(ph, PD0teo, label = r'$P_{teo}(D_{0})$') plt.plot(ph, PD0sim, 'o', label = r'$P_{sim}(D_{0})$') #plt.plot(ph, PD0exp, '*', label = r'$P_{exp}(D_{0})$') plt.legend(); plt.xlabel(r'$\phi$'); plt.ylim(-0.02,1.02); plt.show() def state_prep_psip(): qr = QuantumRegister(3); qc = QuantumCircuit(qr, name = 'prep') qc.h(qr[0]); qc.cx(qr[0],qr[1]); qc.x(qr[1]) # prepara psi+_01 return qc state_prep_psip_ = state_prep_psip(); state_prep_psip_.draw() def qc_dfp(): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name='DFP') qc.cu(math.pi, math.pi/2, -math.pi/2, 0.0, qr[0], qr[1]) return qc qc_dfp_ = qc_dfp(); qc_dfp_.draw() def qc_df(): qr = QuantumRegister(1); qc = QuantumCircuit(qr, name='DF') qc.s(qr[0]); qc.h(qr[0]); qc.s(qr[0]) return qc qc_df_ = qc_df(); qc_df_.draw() def qc_pmo(): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name='PMO') qc.cx(qr[1],qr[0]) return qc qc_pmo_ = qc_pmo(); qc_pmo_.draw() def qc_pqo(): qr = QuantumRegister(1); qc = QuantumCircuit(qr, name='PQO') qc.h(qr[0]); qc.s(qr[0]) return qc qc_pqo_ = qc_pqo(); qc_pqo_.draw() def qc_apagador(ph): qr = QuantumRegister(3); qc = QuantumCircuit(qr) state_prep_psip_ = state_prep_psip(); qc.append(state_prep_psip_, [qr[0],qr[1],qr[2]]) qc_dfp_ = qc_dfp(); qc.append(qc_dfp_, [qr[1],qr[2]]) # DFP qc_pmo_ = qc_pmo(); qc.append(qc_pmo_, [qr[1],qr[2]]) # PMO qc_pqo_ = qc_pqo(); qc.append(qc_pqo_, [qr[0]]) qc.z(qr[2]); qc.y(qr[2]) # espelho qc.p(ph, qr[2]); # fase qc_df_ = qc_df(); qc.append(qc_df_, [qr[2]]) # DF return qc qc_apagador_ = qc_apagador(math.pi/3); qc_apagador_.draw() phmax = 2*math.pi; dph = phmax/20; ph = np.arange(0, phmax+dph, dph)#; ph d = ph.shape[0]; PD0teo = np.zeros(d); PD0sim = np.zeros(d); PD0exp = np.zeros(d) for j in range(0, d): PD0teo[j] = (2+math.cos(ph[j])+math.sin(ph[j]))/4 # theoretical qr = QuantumRegister(3); qc = QuantumCircuit(qr) qc_apagador_ = qc_apagador(ph[j]); qc.append(qc_apagador_, [qr[0],qr[1],qr[2]]) # apagador q qstc = state_tomography_circuits(qc, qr[2]) # circuit for state tomography job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') PD0sim[j] = rho[0,0].real #print(rho[0,0].real) # 1º fiz as simulações, só depois adicionei o código para os experimentos '''job = qiskit.execute(qstc, backend = device, shots = nshots) print(job.job_id()); job_monitor(job) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') PD0exp[j] = rho[0,0].real''' matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100) plt.plot(ph, PD0teo, label = r'$P_{teo}(D_{0})$') plt.plot(ph, PD0sim, 'o', label = r'$P_{sim}(D_{0})$') #plt.plot(ph, PD0exp, '*', label = r'$P_{exp}(D_{0})$') plt.legend(); plt.xlabel(r'$\phi$'); plt.ylim(-0.02,1.02); plt.show() H = (1/sqrt(2))*Matrix([[1,1],[1,-1]]); S = Matrix([[1,0],[0,1j]]); X = Matrix([[0,1],[1,0]]) def U(th, ph, lb): return Matrix([[cos(th/2),-(cos(lb)+1j*sin(lb))*sin(th/2)], [(cos(ph)+1j*sin(ph))*sin(th/2),(cos(ph+lb)+1j*sin(ph+lb))*cos(th/2)]]) def dfp(): return tp(proj(cb(2,0)), id(2)) + tp(proj(cb(2,1)), U(math.pi, math.pi/2, -math.pi/2)) def pmo(): return tp(id(2), proj(cb(2,0))) + tp(X, proj(cb(2,1))) th, ph, lb = symbols('theta phi lambda');# U(th, ph, lb) psi0 = tp(tp(cb(2,0),cb(2,0)),cb(2,0))#; psi0 dfp_ = dfp(); psi1 = tp(id(2), dfp_)*psi0; psi1 pmo_ = pmo(); psi2 = tp(id(2), pmo_)*psi1; psi2
https://github.com/BOBO1997/osp_solutions
BOBO1997
import re import itertools import numpy as np import random random.seed(42) import mitiq from qiskit import QuantumCircuit, QuantumRegister from qiskit.ignis.mitigation import expectation_value # Pauli Twirling def pauli_twirling(circ: QuantumCircuit) -> QuantumCircuit: """ [internal function] This function takes a quantum circuit and return a new quantum circuit with Pauli Twirling around the CNOT gates. Args: circ: QuantumCircuit Returns: QuantumCircuit """ def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! split the quantum circuit into qasm operators for op in ops: if (op[:2] == 'cx'): # add Pauli Twirling around the CNOT gate num = random.randrange(len(paulis)) qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return QuantumCircuit.from_qasm_str(new_circ) def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0], pt = False): """ This function outputs the circuit list for zero-noise extrapolation. Args: qcs: List[QuantumCircuit], the input quantum circuits. scale_factors: List[float], to what extent the noise scales are investigated. pt: bool, whether add Pauli Twirling or not. Returns: folded_qcs: List[QuantumCircuit] """ folded_qcs = [] #! ZNE用の回路 for qc in qcs: folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化 if pt: folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] return folded_qcs def make_stf_basis(n, basis_elements = ["X","Y","Z"]): """ [internal function] This function outputs all the combinations of length n string for given basis_elements. When basis_elements is X, Y, and Z (default), the output becomes the n-qubit Pauli basis. Args: n: int basis_elements: List[str] Returns: basis: List[str] """ if n == 1: return basis_elements basis = [] for i in basis_elements: sub_basis = make_stf_basis(n - 1, basis_elements) basis += [i + j for j in sub_basis] return basis def reduce_hist(hist, poses): """ [internal function] This function returns the reduced histogram to the designated positions. Args: hist: Dict[str, float] poses: List[int] Returns: ret_hist: Dict[str, float] """ n = len(poses) ret_hist = {format(i, "0" + str(n) + "b"): 0 for i in range(1 << n)} for k, v in hist.items(): pos = "" for i in range(n): pos += k[poses[i]] ret_hist[pos] += v return ret_hist def make_stf_expvals(n, stf_hists): """ [internal function] This function create the expectations under expanded basis, which are used to reconstruct the density matrix. Args: n: int, the size of classical register in the measurement results. stf_hists: List[Dict[str, float]], the input State Tomography Fitter histograms. Returns: st_expvals: List[float], the output State Tomography expectation values. """ assert len(stf_hists) == 3 ** n stf_basis = make_stf_basis(n, basis_elements=["X","Y","Z"]) st_basis = make_stf_basis(n, basis_elements=["I","X","Y","Z"]) stf_hists_dict = {basis: hist for basis, hist in zip(stf_basis, stf_hists)} st_hists_dict = {basis: stf_hists_dict.get(basis, None) for basis in st_basis} # remaining for basis in sorted(set(st_basis) - set(stf_basis)): if basis == "I" * n: continue reduction_poses = [] reduction_basis = "" for i, b in enumerate(basis): if b != "I": reduction_poses.append(n - 1 - i) # big endian reduction_basis += b # こっちはそのまま(なぜならラベルはlittle endianだから) else: reduction_basis += "Z" st_hists_dict[basis] = reduce_hist(stf_hists_dict[reduction_basis], reduction_poses) st_expvals = dict() for basis, hist in st_hists_dict.items(): if basis == "I" * n: st_expvals[basis] = 1.0 continue st_expvals[basis], _ = expectation_value(hist) return st_expvals def zne_decoder(n, result, scale_factors=[1.0, 2.0, 3.0], fac_type="lin"): """ This function applies the zero-noise extrapolation to the measured results and output the mitigated zero-noise expectation values. Args: n: int, the size of classical register in the measurement results. result: Result, the returned results from job. scale_factors: List[float], this should be the same as the zne_wrapper. fac_type: str, "lin" or "exp", whether to use LinFactory option or ExpFactory option in mitiq, to extrapolate the expectation values. Returns: zne_expvals: List[float], the mitigated zero-noise expectation values. """ hists = result.get_counts() num_scale_factors = len(scale_factors) assert len(hists) % num_scale_factors == 0 scale_wise_expvals = [] # num_scale_factors * 64 for i in range(num_scale_factors): scale_wise_hists = [hists[3 * j + i] for j in range(len(hists) // num_scale_factors)] st_expvals = make_stf_expvals(n, scale_wise_hists) scale_wise_expvals.append( list(st_expvals.values()) ) scale_wise_expvals = np.array(scale_wise_expvals) linfac = mitiq.zne.inference.LinearFactory(scale_factors) expfac = mitiq.zne.ExpFactory(scale_factors) zne_expvals = [] for i in range(4 ** n): if fac_type == "lin": zne_expvals.append( linfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) else: zne_expvals.append( expfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) return zne_expvals
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for swap strategies.""" from typing import List from ddt import data, ddt, unpack import numpy as np from qiskit import QiskitError from qiskit.test import QiskitTestCase from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import SwapStrategy @ddt class TestSwapStrategy(QiskitTestCase): """A class to test the swap strategies.""" def setUp(self): super().setUp() self.line_coupling_map = CouplingMap( couplinglist=[ (0, 1), (1, 2), (2, 3), (3, 4), (1, 0), (2, 1), (3, 2), (4, 3), ] ) self.line_swap_layers = ( ((0, 1), (2, 3)), ((1, 2), (3, 4)), ((0, 1), (2, 3)), ((1, 2), (3, 4)), ((0, 1), (2, 3)), ) self.line_edge_coloring = {(0, 1): 0, (1, 2): 1, (2, 3): 0, (3, 4): 1} self.line_strategy = SwapStrategy(self.line_coupling_map, self.line_swap_layers) @data( (0, [0, 1, 2, 3, 4]), (1, [1, 0, 3, 2, 4]), (2, [1, 3, 0, 4, 2]), (3, [3, 1, 4, 0, 2]), (4, [3, 4, 1, 2, 0]), (5, [4, 3, 2, 1, 0]), ) @unpack def test_inverse_composed_permutation(self, layer_idx: int, expected: List[int]): """Test the inverse of the permutations.""" self.assertEqual(self.line_strategy.inverse_composed_permutation(layer_idx), expected) def test_apply_swap_layer(self): """Test that swapping a list of elements is correct.""" list_to_swap = [0, 10, 20, 30, 40] swapped_list = self.line_strategy.apply_swap_layer(list_to_swap, 0) self.assertEqual(swapped_list, [10, 0, 30, 20, 40]) self.assertFalse(list_to_swap == swapped_list) swapped_list = self.line_strategy.apply_swap_layer(list_to_swap, 1, inplace=True) self.assertEqual(swapped_list, [0, 20, 10, 40, 30]) self.assertTrue(list_to_swap == swapped_list) def test_length(self): """Test the __len__ operator.""" self.assertEqual(len(self.line_strategy), 5) def test_swapped_coupling_map(self): """Test the edges generated by a swap strategy.""" edge_set = {(2, 0), (0, 4), (4, 1), (1, 3), (3, 1), (1, 4), (4, 0), (0, 2)} swapped_map = self.line_strategy.swapped_coupling_map(3) self.assertEqual(edge_set, set(swapped_map.get_edges())) def test_check_configuration(self): """Test that tries to initialize an invalid swap strategy.""" with self.assertRaises(QiskitError): SwapStrategy( coupling_map=self.line_coupling_map, swap_layers=(((0, 1), (2, 3)), ((1, 3), (2, 4))), ) def test_only_one_swap_per_qubit_per_layer(self): """Test that tries to initialize an invalid swap strategy.""" message = "The 0th swap layer contains a qubit with multiple swaps." with self.assertRaises(QiskitError, msg=message): SwapStrategy( coupling_map=self.line_coupling_map, swap_layers=(((0, 1), (1, 2)),), ) def test_distance_matrix(self): """Test the computation of the swap strategy distance matrix.""" line_distance_matrix = np.array( [ [0, 0, 3, 1, 2], [0, 0, 0, 2, 3], [3, 0, 0, 0, 1], [1, 2, 0, 0, 0], [2, 3, 1, 0, 0], ] ) self.assertTrue(np.all(line_distance_matrix == self.line_strategy.distance_matrix)) # Check that the distance matrix cannot be written to. with self.assertRaises(ValueError): self.line_strategy.distance_matrix[1, 2] = 5 def test_reaches_full_connectivity(self): """Test to reach full connectivity on the longest line of Mumbai.""" # The longest line on e.g. Mumbai has 21 qubits ll27 = list(range(21)) ll27_map = [[ll27[idx], ll27[idx + 1]] for idx in range(len(ll27) - 1)] ll27_map += [[ll27[idx + 1], ll27[idx]] for idx in range(len(ll27) - 1)] # Create a line swap strategy on this line layer1 = tuple((ll27[idx], ll27[idx + 1]) for idx in range(0, len(ll27) - 1, 2)) layer2 = tuple((ll27[idx], ll27[idx + 1]) for idx in range(1, len(ll27), 2)) n = len(ll27) for n_layers, result in [ (n - 4, False), (n - 3, False), (n - 2, True), (n - 1, True), ]: swap_strat_ll = [] for idx in range(n_layers): if idx % 2 == 0: swap_strat_ll.append(layer1) else: swap_strat_ll.append(layer2) strat = SwapStrategy(CouplingMap(ll27_map), tuple(swap_strat_ll)) self.assertEqual(len(strat.missing_couplings) == 0, result) def test_new_connections(self): """Test the new connections method.""" new_cnx = self.line_strategy.new_connections(0) expected = [{1, 0}, {2, 1}, {3, 2}, {4, 3}] self.assertListEqual(new_cnx, expected) # Test after first swap layer (0, 1) first new_cnx = self.line_strategy.new_connections(1) expected = [{3, 0}, {4, 2}] self.assertListEqual(new_cnx, expected) def test_possible_edges(self): """Test that possible edges works as expected.""" coupling_map = CouplingMap(couplinglist=[(0, 1), (1, 2), (2, 3)]) strat = SwapStrategy(coupling_map, (((0, 1), (2, 3)), ((1, 2),))) expected = set() for i in range(4): for j in range(4): if i != j: expected.add((i, j)) self.assertSetEqual(strat.possible_edges, expected) class TestSwapStrategyExceptions(QiskitTestCase): """A class to test the exceptions raised by swap strategies.""" def test_invalid_strategy(self): """Test that a raise properly occurs.""" coupling_map = CouplingMap(couplinglist=[(0, 1), (1, 2)]) swap_layers = (((0, 1), (2, 3)), ((1, 2), (3, 4))) with self.assertRaises(QiskitError): SwapStrategy(coupling_map, swap_layers) def test_invalid_line_strategy(self): """Test the number of layers.""" message = "Negative number -1 passed for number of swap layers." with self.assertRaises(ValueError, msg=message): SwapStrategy.from_line([0, 1, 2], -1) class TestLineSwapStrategy(QiskitTestCase): """A class to test the line swap strategy.""" def test_invalid_line(self): """Test that lines should be longer than 1.""" message = "The line cannot have less than two elements, but is [1]" with self.assertRaises(ValueError, msg=message): SwapStrategy.from_line([1], 0) def test_full_line(self): """Test to reach full connectivity on a line.""" n_nodes = 5 strategy = SwapStrategy.from_line(list(range(n_nodes))) self.assertEqual(len(strategy._swap_layers), n_nodes - 2) # The LineSwapStrategy will apply the following permutations layers = [ [0, 1, 2, 3, 4], # coupling map [1, 0, 3, 2, 4], # layer 1 [1, 3, 0, 4, 2], # layer 2 [3, 1, 4, 0, 2], # layer 3 <-- full connectivity is reached. ] for layer_idx, layer in enumerate(layers): expected = set() for idx in range(len(layer) - 1): expected.add((layer[idx], layer[idx + 1])) expected.add((layer[idx + 1], layer[idx])) strat_edges = strategy.swapped_coupling_map(layer_idx).get_edges() self.assertEqual(len(strat_edges), len(expected)) for edge in strat_edges: self.assertTrue(edge in expected) self.assertEqual(strategy.swap_layer(0), [(0, 1), (2, 3)]) self.assertEqual(strategy.swap_layer(1), [(1, 2), (3, 4)]) self.assertEqual(strategy.swap_layer(2), [(0, 1), (2, 3)]) self.assertEqual(len(strategy.missing_couplings), 0) def test_line(self): """Test the creation of a line swap strategy.""" n_nodes = 5 strategy = SwapStrategy.from_line(list(range(n_nodes))) self.assertEqual(strategy.swap_layer(0), [(0, 1), (2, 3)]) self.assertEqual(strategy.swap_layer(1), [(1, 2), (3, 4)]) self.assertEqual(strategy.swap_layer(2), [(0, 1), (2, 3)]) self.assertEqual(len(strategy.missing_couplings), 0) def test_repr(self): """The the representation.""" expected = ( "SwapStrategy with swap layers:\n((0, 1),),\non " "[[0, 1], [1, 0], [1, 2], [2, 1]] coupling map." ) self.assertEqual(repr(SwapStrategy.from_line([0, 1, 2])), expected)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test OptimizeSwapBeforeMeasure pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.transpiler import PassManager from qiskit.transpiler.passes import OptimizeSwapBeforeMeasure, DAGFixedPoint from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestOptimizeSwapBeforeMeasure(QiskitTestCase): """Test swap-followed-by-measure optimizations.""" def test_optimize_1swap_1measure(self): """Remove a single swap qr0:--X--m-- qr0:---- | | qr1:--X--|-- ==> qr1:--m- | | cr0:-----.-- cr0:--.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[1], cr[0]) pass_ = OptimizeSwapBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_1swap_2measure(self): """Remove a single swap affecting two measurements qr0:--X--m-- qr0:--m---- | | | qr1:--X--|--m ==> qr1:--|--m- | | | | cr0:-----.--|-- cr0:--|--.- cr1:--------.-- cr1:--.---- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[1], cr[0]) expected.measure(qr[0], cr[1]) pass_ = OptimizeSwapBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_nswap_nmeasure(self): """Remove severals swap affecting multiple measurements ┌─┐ ┌─┐ q_0: ─X──X─────X────┤M├───────────────────────────────── q_0: ──────┤M├─────────────── │ │ │ └╥┘ ┌─┐ ┌─┐└╥┘ q_1: ─X──X──X──X──X──╫─────X────┤M├───────────────────── q_1: ───┤M├─╫──────────────── │ │ ║ │ └╥┘ ┌─┐ ┌─┐└╥┘ ║ q_2: ───────X──X──X──╫──X──X─────╫──X────┤M├──────────── q_2: ┤M├─╫──╫──────────────── │ ║ │ ║ │ └╥┘┌─┐ └╥┘ ║ ║ ┌─┐ q_3: ─X─────X──X─────╫──X──X──X──╫──X─────╫─┤M├───────── q_3: ─╫──╫──╫────┤M├───────── │ │ ║ │ │ ║ ║ └╥┘┌─┐ ║ ║ ║ └╥┘ ┌─┐ q_4: ─X──X──X──X─────╫──X──X──X──╫──X─────╫──╫─┤M├────── ==> q_4: ─╫──╫──╫─────╫───────┤M├ │ │ ║ │ ║ │ ║ ║ └╥┘┌─┐ ║ ║ ║ ┌─┐ ║ └╥┘ q_5: ────X──X──X──X──╫──X──X─────╫──X──X──╫──╫──╫─┤M├─── q_5: ─╫──╫──╫─┤M├─╫────────╫─ │ │ ║ │ ║ │ ║ ║ ║ └╥┘┌─┐ ║ ║ ║ └╥┘ ║ ┌─┐ ║ q_6: ─X──X──X──X──X──╫──X──X─────╫─────X──╫──╫──╫──╫─┤M├ q_6: ─╫──╫──╫──╫──╫─┤M├────╫─ │ │ │ ║ │ ┌─┐ ║ ║ ║ ║ ║ └╥┘ ║ ║ ║ ║ ║ └╥┘┌─┐ ║ q_7: ─X──X─────X─────╫──X─┤M├────╫────────╫──╫──╫──╫──╫─ q_7: ─╫──╫──╫──╫──╫──╫─┤M├─╫─ ║ └╥┘ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ └╥┘ ║ c: 8/════════════════╩═════╩═════╩════════╩══╩══╩══╩══╩═ c: 8/═╩══╩══╩══╩══╩══╩══╩══╩═ 0 7 1 2 3 4 5 6 0 1 2 3 4 5 6 7 """ circuit = QuantumCircuit(8, 8) circuit.swap(3, 4) circuit.swap(6, 7) circuit.swap(0, 1) circuit.swap(6, 7) circuit.swap(4, 5) circuit.swap(0, 1) circuit.swap(5, 6) circuit.swap(3, 4) circuit.swap(1, 2) circuit.swap(6, 7) circuit.swap(4, 5) circuit.swap(2, 3) circuit.swap(0, 1) circuit.swap(5, 6) circuit.swap(1, 2) circuit.swap(6, 7) circuit.swap(4, 5) circuit.swap(2, 3) circuit.swap(3, 4) circuit.swap(3, 4) circuit.swap(5, 6) circuit.swap(1, 2) circuit.swap(4, 5) circuit.swap(2, 3) circuit.swap(5, 6) circuit.measure(range(8), range(8)) dag = circuit_to_dag(circuit) expected = QuantumCircuit(8, 8) expected.measure(0, 2) expected.measure(1, 1) expected.measure(2, 0) expected.measure(3, 4) expected.measure(4, 7) expected.measure(5, 3) expected.measure(6, 5) expected.measure(7, 6) pass_ = OptimizeSwapBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_cannot_optimize(self): """Cannot optimize when swap is not at the end in all of the successors qr0:--X-----m-- | | qr1:--X-[H]-|-- | cr0:--------.-- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]) circuit.h(qr[1]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) pass_ = OptimizeSwapBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(circuit), after) def test_if_else(self): """Test that the pass recurses into a simple if-else.""" pass_ = OptimizeSwapBeforeMeasure() base_test = QuantumCircuit(2, 1) base_test.swap(0, 1) base_test.measure(0, 0) base_expected = QuantumCircuit(2, 1) base_expected.measure(1, 0) test = QuantumCircuit(2, 1) test.if_else( (test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits ) expected = QuantumCircuit(2, 1) expected.if_else( (expected.clbits[0], True), base_expected.copy(), base_expected.copy(), expected.qubits, expected.clbits, ) self.assertEqual(pass_(test), expected) def test_nested_control_flow(self): """Test that the pass recurses into nested control flow.""" pass_ = OptimizeSwapBeforeMeasure() base_test = QuantumCircuit(2, 1) base_test.swap(0, 1) base_test.measure(0, 0) base_expected = QuantumCircuit(2, 1) base_expected.measure(1, 0) body_test = QuantumCircuit(2, 1) body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits) body_expected = QuantumCircuit(2, 1) body_expected.for_loop( (0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits ) test = QuantumCircuit(2, 1) test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits) expected = QuantumCircuit(2, 1) expected.while_loop( (expected.clbits[0], True), body_expected, expected.qubits, expected.clbits ) self.assertEqual(pass_(test), expected) class TestOptimizeSwapBeforeMeasureFixedPoint(QiskitTestCase): """Test swap-followed-by-measure optimizations in a transpiler, using fixed point.""" def test_optimize_undone_swap(self): """Remove redundant swap qr0:--X--X--m-- qr0:--m--- | | | | qr1:--X--X--|-- ==> qr1:--|-- | | cr0:--------.-- cr0:--.-- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]) circuit.swap(qr[0], qr[1]) circuit.measure(qr[0], cr[0]) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) pass_manager = PassManager() pass_manager.append( [OptimizeSwapBeforeMeasure(), DAGFixedPoint()], do_while=lambda property_set: not property_set["dag_fixed_point"], ) after = pass_manager.run(circuit) self.assertEqual(expected, after) def test_optimize_overlap_swap(self): """Remove two swaps that overlap qr0:--X-------- qr0:--m-- | | qr1:--X--X----- qr1:--|-- | ==> | qr2:-----X--m-- qr2:--|-- | | cr0:--------.-- cr0:--.-- """ qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]) circuit.swap(qr[1], qr[2]) circuit.measure(qr[2], cr[0]) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) pass_manager = PassManager() pass_manager.append( [OptimizeSwapBeforeMeasure(), DAGFixedPoint()], do_while=lambda property_set: not property_set["dag_fixed_point"], ) after = pass_manager.run(circuit) self.assertEqual(expected, after) def test_no_optimize_swap_with_condition(self): """Do not remove swap if it has a condition qr0:--X--m-- qr0:--X--m-- | | | | qr1:--X--|-- ==> qr1:--X--|-- | | | | cr0:--1--.-- cr0:--1--.-- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]).c_if(cr, 1) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.swap(qr[0], qr[1]).c_if(cr, 1) expected.measure(qr[0], cr[0]) pass_ = OptimizeSwapBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit 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/bagmk/Quantum_Machine_Learning_Express
bagmk
# The code below is a hack in case Travis' kernel fails. #import os #os.environ['KMP_DUPLICATE_LIB_OK'] ='True' # Pull in the helper files. import sys sys.path.append('../../Pyfiles') # Pull in the helper files. from experiments import * # Set up the experiment circuitID = 9 epochs = 20 import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) lr_list=[round(((i+1)/10)**2,2) for i in range(20)] ds_list=['0','1a','2a','3c'] for dsID in ds_list: # Run the experiment print('--------dataset',dsID,'is initialized------') lr_acc=[] for lr in lr_list: # Load in the data data = load_data(dsID) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr, train_X, train_y) # Check the validation accuracy. val_accuracy = check_accuracy(model, validate_X, validate_y) lr_acc.append([lr,val_accuracy]) np.savetxt(r"Learning_Rate_Data\circuit{0}_data{1}.txt".format(circuitID,dsID),lr_acc,fmt='%.2f') import numpy import sys numpy.set_printoptions(threshold=sys.maxsize) lr_list=[round(((i+1)/10)**2,2) for i in range(20)] # Run the experiment lr_acc=[] for lr in lr_list: # Load in the data data = load_data('0') # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr, train_X, train_y) # Check the validation accuracy. val_accuracy = check_accuracy(model, validate_X, validate_y) lr_acc.append([lr,val_accuracy]) np.savetxt(r"Learning_Rate_Data\circuit{0}_data{1}.txt".format(circuitID,dsID),lr_acc,fmt='%.2f') # Set up the experiment circuitID = 9 epochs = 20 ds_list=['0','1a','2a','3c'] #selected learning rates lr_opt=[2.89,0.16,0.09,2.25] model_list=[] for i in range(4): data = load_data(ds_list[i]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr_opt[i], train_X, train_y) model_list.append(model) # Check the validation accuracy. val_accuracy = check_accuracy(model, test_X, test_y) import matplotlib.pyplot as plt for lr in range(4): data = load_data(ds_list[lr]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(4, 2, 2*lr+1) y_predict = [] for x in test_X: output = model_list[lr](Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print(check_accuracy(model_list[lr], test_X, test_y)) # plot results # red == wrongly classified for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') if y_target != y_: ax.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2) ax = fig.add_subplot(4, 2, 2*lr+2) for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') X1 = np.linspace(0, 1, num=10) Z1 = np.zeros((len(X1), len(X1))) # Contour map for j in range(len(X1)): for k in range(len(X1)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z1[j, k] = np.argmax(model_list[lr](Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy()) ax.contourf(X1, X1, Z1, cmap='bwr', levels=30)
https://github.com/cjsproject/qiskit_learning
cjsproject
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import * from os import environ #local environment variable to store the access token :) token = environ.get('ibmq_token') # Loading IBM Q account account = IBMQ.save_account(token, overwrite=True) provider = IBMQ.load_account() # quasm_sim simulator = Aer.get_backend('qasm_simulator') # circuit on q reg with 1 qubit circuit = QuantumCircuit(2, 2) # hadamard gate on qbit A circuit.h(0) # CNOT on qbit B controlled by A circuit.cx(0, 1) circuit.measure([0, 1], [0, 1]) job = execute(circuit, simulator, shots=1000) results = job.result() counts = results.get_counts(circuit) print(f"total count for 0 and 1 are: {counts}") circuit.draw() plot_histogram(counts)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 1000 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from linear_entangelment_and_full_entangelment_ansatz_circuits import * def get_ansatz_state(thetas, ansatz_entangelment, input_state): if ansatz_entangelment=="full": return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state) if ansatz_entangelment=="linear": return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in tqdm(zip(pauli_coeffs, pauli_strings)): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile def cost_function(thetas, hamiltonian, ansatz_entangelment): initial_eigenvector = np.identity(N)[0] pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector) L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(L) return L def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment): initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM) optimizer_result = minimize(cost_function, x0=initial_thetas, args=(hamiltonian, ansatz_entangelment), method="COBYLA", options={"maxiter":NUM_ITERATIONS, "disp": True}) optimal_thetas = optimizer_result.x return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment) print(optimal_thetas) initial_eigenvector = np.identity(N)[0] optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian): eigen_values = LA.eigvals(hamiltonian.to_matrix()) print(sorted(eigen_values)) return min(sorted(eigen_values)) def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian) print("Exact Eigenvalue:") print(exact_eigenvalue) print("\nApproximated Eigenvalue:") print(approximated_eigenvalue) print("\nApproximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3) approximated_energies = [] def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 3 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 1000 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit.opflow import X, Z, I transverse_ising_3_qubits = 0.0 * (I^I^I) \ + 0.012764169333459807 * (X^I^I) \ + 0.7691573729160869 * (I^X^I) \ + 0.398094746026449 * (Z^Z^I) \ + 0.15250261906586637 * (I^I^X) \ + 0.2094051920882264 * (Z^I^Z) \ + 0.5131291860752999 * (I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 2 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 1000 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \ + 0.43305656297810435 * (X^I) \ + 0.8538597608997253 * (Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) from qiskit.opflow import X, Z, I H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
https://github.com/minminjao/qiskit1
minminjao
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() import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(10) qc.h(2) qc.cp(pi/2, 1, 2) qc.cp(pi/4, 0, 2) qc.h(1) qc.cp(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 qc.h(0) qc.swap(0,2) def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) # Let's see how it looks: qc = QuantumCircuit(10) qft_rotations(qc,10) qc.draw() def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit # Let's see how it looks: qc = QuantumCircuit(10) qft(qc,10) qc.draw() 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]) return circuit.decompose() # .decompose() allows us to see the individual gates nqubits = 10 number = 5 qc = QuantumCircuit(nqubits) for qubit in range(nqubits): qc.h(qubit) qc.p(number*pi/4,0) qc.p(number*pi/2,1) qc.p(number*pi,2) qc.p(number*pi/4,3) qc.p(number*pi/2,4) qc.p(number*pi,5) qc.p(number*pi/4,6) qc.p(number*pi/2,7) qc.p(number*pi,8) qc.p(number*pi/4,9) qc.draw() 위에 코드들은 ibm qiskit textbook을 기초로 하여서 작성한 코드이다. 10큐비트로 바뀌었으므로 nqubits = 10) <- 10을 작성하여서 10큐비트를 구현하도록 하였고 위 그림은 그에 따른 결과이다. 그리고 원래는 3큐비트만 하여서 코드들이 구현이 되도록 하였지만 문제를 풀기위해서는 10큐비트를 작성하고 코드연산들을 적용해야한다. 그러므로 h 게이트도 10큐비트까지 다 적용되도록 하였고 p 게이트가 도는 각도들도 일정패턴을 가지고 적용되도록 작성하였다. qc.p(number*pi/4,n) qc.p(number*pi/2,n) qc.p(number*pi,n) => 의 파이 각도들이 일정하게 반복되도록 코드들을 추가하였다. qc_init = qc.copy() qc_init.save_statevector() sim = Aer.get_backend("aer_simulator") statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qc = inverse_qft(qc, nqubits) qc.measure_all() qc.draw() shots = 2048 backend = Aer.get_backend('qasm_simulator') transpiled_qc = transpile(qc, backend, optimization_level=3) job = backend.run(transpiled_qc, shots=shots) job_monitor(job) counts = job.result().get_counts() plot_histogram(counts) print(counts)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, execute from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.providers.aer import QasmSimulator backend = Aer.get_backend('statevector_simulator') qc1 = QuantumCircuit(4) # perform gate operations on individual qubits qc1.x(0) qc1.y(1) qc1.z(2) qc1.s(3) # Draw circuit qc1.draw() # Plot blochshere out1 = execute(qc1,backend).result().get_statevector() plot_bloch_multivector(out1) qc2 = QuantumCircuit(4) # initialize qubits qc2.x(range(4)) # perform gate operations on individual qubits qc2.x(0) qc2.y(1) qc2.z(2) qc2.s(3) # Draw circuit qc2.draw() # Plot blochshere out2 = execute(qc2,backend).result().get_statevector() plot_bloch_multivector(out2) qc3 = QuantumCircuit(4) # initialize qubits qc3.h(range(4)) # perform gate operations on individual qubits qc3.x(0) qc3.y(1) qc3.z(2) qc3.s(3) # Draw circuit qc3.draw() # Plot blochshere out3 = execute(qc3,backend).result().get_statevector() plot_bloch_multivector(out3) qc4 = QuantumCircuit(4) # initialize qubits qc4.x(range(4)) qc4.h(range(4)) # perform gate operations on individual qubits qc4.x(0) qc4.y(1) qc4.z(2) qc4.s(3) # Draw circuit qc4.draw() # Plot blochshere out4 = execute(qc4,backend).result().get_statevector() plot_bloch_multivector(out4) qc5 = QuantumCircuit(4) # initialize qubits qc5.h(range(4)) qc5.s(range(4)) # perform gate operations on individual qubits qc5.x(0) qc5.y(1) qc5.z(2) qc5.s(3) # Draw circuit qc5.draw() # Plot blochshere out5 = execute(qc5,backend).result().get_statevector() plot_bloch_multivector(out5) qc6 = QuantumCircuit(4) # initialize qubits qc6.x(range(4)) qc6.h(range(4)) qc6.s(range(4)) # perform gate operations on individual qubits qc6.x(0) qc6.y(1) qc6.z(2) qc6.s(3) # Draw circuit qc6.draw() # Plot blochshere out6 = execute(qc6,backend).result().get_statevector() plot_bloch_multivector(out6) import qiskit qiskit.__qiskit_version__
https://github.com/Juan-Varela11/BNL_2020_Summer_Internship
Juan-Varela11
import numpy as np from qiskit import Aer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import VQE, ExactEigensolver from qiskit.aqua.operators import Z2Symmetries from qiskit.aqua.components.optimizers import COBYLA from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() map_type = 'parity' # please be aware that the idx here with respective to original idx freeze_list = [0] remove_list = [-3, -2] # negative number denotes the reverse order h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals nuclear_repulsion_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 print("HF energy: {}".format(molecule.hf_energy - molecule.nuclear_repulsion_energy)) print("# of electrons: {}".format(num_particles)) print("# of spin orbitals: {}".format(num_spin_orbitals)) # prepare full idx of freeze_list and remove_list # convert all negative idx to positive remove_list = [x % molecule.num_orbitals for x in remove_list] freeze_list = [x % molecule.num_orbitals for x in freeze_list] # update the idx in remove_list of the idx after frozen, since the idx of orbitals are changed after freezing remove_list = [x - len(freeze_list) for x in remove_list] remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list] freeze_list += [x + molecule.num_orbitals for x in freeze_list] # prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian # and if PARITY mapping is selected, reduction qubits energy_shift = 0.0 qubit_reduction = True if map_type == 'parity' else False ferOp = FermionicOperator(h1=h1, h2=h2) if len(freeze_list) > 0: ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) if len(remove_list) > 0: ferOp = ferOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = ferOp.mapping(map_type=map_type, threshold=0.00000001) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) if qubit_reduction else qubitOp qubitOp.chop(10**-10) print(qubitOp) print(qubitOp.print_details())
https://github.com/KPRoche/quantum-raspberry-tie
KPRoche
#---------------------------------------------------------------------- # QuantumRaspberryTie.qk1_local # by KPRoche (Kevin P. Roche) (c) 2017,2018,2019,2020,2021,2022.2024 # # NEW RELEASE # April 2024 to accomodate the official release of Qiskit 1.0 # using new QiskitRuntime libraries and call techniques; # runs OPENQASM code on an IBM Quantum backend or simulator # Display the results using the 8x8 LED array on a SenseHat (or SenseHat emulator) # Will Default to local simulator because the cloud simulator is being retired. # # Will Connect and authenticate to the IBM Quantum platform via the QiskitRuntime module (if necessary) # # NEW default behavior: # Spins up a 5-qubit test backend (local simulator) based on FakeManilaV2 # in a "bowtie" arrangement based on older processors # New Qiskit-logo inspired "thinking" graphic # NEW backend options: # -b:aer | spins up a local Aer simulator # -b:aer_noise or -b:aer_model | spins up a local Aer simulator with a noise model # based on the least busy real processor for your account (this does require access to # the IBM Quantum processors and account credentials properly saved via QiskitRuntime # -b:least | will run code once on the least busy *real* backend for your account # NOTE: this may take hours before the result returns # -b:[backend_name] | will use the specified backend if it is available (see note above) # NEW display options # NOTE: if multiple options are specified the last one in the parameters will be applied # hex or -hex | displays on a 12 qubit pattern # (topologically identical to the heavy hex in IBM processors) # d16 or -d16 | displays on a 16 qubit pattern # NOTE: overrides default or tee option for 5 qubit code! # NOTE: if your quantum circuit has fewer qubits than available in the display mode, # unmeasured qubits will be displayed in purple # # NEW interactive options # -input | prompts you to add more parameters to what was on the command line # -select | prompts you for the backend option before initializing # OTHER options: # -tee | switches to a tee-shaped 5-qubit arrangement # -16 or 16 | loads a 16-qubit QASM file and switches to a 16-bit display arrangement # NOTE: hex display mode will override the 16 qubit display and show only the first 12 # -noq | does not show a logo during the rainbow "thinking" moment; instead rainbows the qubit display # -e | will attempt to spin up a SenseHat emulator display on your desktop. # -d | will attempt to display on BOTH the SenseHat and a emulator display # These require that both the libraries and a working version of the emulator executable be present # -f:filename load an alternate QASM file # ----------------------------- pre Qiskit 1.0 History ----------------------- # # April 2023 -- added dual display option. If sensehat is available, will spin up a second emulator to show # on the desktop # Nov 2022 -- Cleaned up -local option to run a local qasm simulator if supported # # Feb 2020 -- Added fix to IBM Quantum Experience URL (Thanks Jan Lahman) # # October 2019 -- added extra command line parameters. Can force use of Sensehat emulator, or specify backend # (specifying use of a non-simulator backend will disable loop) # October 2019 -- will attempt to load SenseHat and connect to hardware. # If that fails, then loads and launches SenseHat emulator for display instead # # September 2019 -- adaptive version can use either new (0.3) ibmq-provider with provider object # or older (0.2) IBMQ object # July 2019 -- convert to using QISKIT full library authentication and quantum circuit # techniques # March 2018 -- Detect a held center switch on the SenseHat joystick to trigger shutdown # # Original (2017) version # Spin off the display functions in a separate thread so they can exhibit # smooth color changes while "thinking" # Use a ping function to try to make sure the website is available before # sending requests and thus avoid more hangs that way # Move the QASM code into an outside file # #---------------------------------------------------------------------- # import the necessary modules print("importing libraries...") print(" ....sys") import sys # used to check for passed filename print(" ....os") import os # used to find script directory print(" ....requests") import requests # used for ping print(" ....threading") from threading import Thread # used to spin off the display functions print(" ....colorsys") from colorsys import hsv_to_rgb # used to build the color array print(" ....time") from time import process_time # used for loop timer print(" ....sleep") from time import sleep #used for delays print(" ....qiskit QiskitRuntimeService") from qiskit_ibm_runtime import QiskitRuntimeService # classes for accessing IBM Quantum online services print(" ....QuantumCircuit and transpile") from qiskit import QuantumCircuit, transpile, qiskit from qiskit.providers import JobStatus print(" .....simple local emulator (fakeManila)") from qiskit_ibm_runtime.fake_provider import FakeManilaV2 print (" .....Aer for building local simulators")#importing Aer to use local simulator") from qiskit_aer import Aer print(" ....warnings") import warnings IBMQVersion = qiskit.__version__ print(IBMQVersion) #Initialize then check command arguments UseEmulator = False DualDisplay = False QWhileThinking = True UseTee = False UseHex = False UseQ16 = False UseLocal = True backendparm = '[localsim]' SelectBackend = False #for interactive selection of backend fake_name = "FakeManilaV2" qubits_needed = 5 #default size for the five-qubit simulation AddNoise = False debug = False qasmfileinput='expt.qasm' #---------------------------------------------------------------------------- # Create a SVG rendition of the pixel array #---------------------------------------------------------------------------- def svg_pixels(pixel_list, brighten=1): # Create canvas svg_inline = '<svg width="128" height="128" version="1.1" xmlns="http://www.w3.org/2000/svg">\n' # fill canvas with black background #svg_inline = svg_inline + '<rect x="0" y="0" width="128" height="128" stroke="black" fill="black" stroke-width="0"/>\n' # iterate through the list for i in range(64): # get the coordinates x = 4 * 4 * (i % 8) y = 4 * 4 * (i//8) pixel=pixel_list[i] red=pixel[0] green=pixel[1] blue=pixel[2] if brighten > 0: red = min(int(red * brighten),255) green = min(int(green * brighten),255) blue = min(int(blue * brighten),255) # build the "pixel" rectangle and append it pixel_str=f'<rect x="{x}" y="{y}" fill="rgb({red},{green},{blue})" width="16" height="16" stroke="white" stroke-width="1"/>\n' svg_inline = svg_inline + pixel_str #close the svg svg_inline = svg_inline + "</svg>" return svg_inline def write_svg_file(pixels, label='0000', brighten=1, init=False): # This uses multiple files to create the webpage qubit display: # qubits.html is only written if init is True # It contains the refresh command and the html structure, and pulls in the other two # pixels.svg holds the display pattern # pixels.lbl holds the caption if init: print("initializing html wrapper for svg display") try: #create the svg directory if it doesn't exist yet os.mkdir(r'./svg') except OSError as error: print(error) html_file = open (r'./svg/qubits.html',"w") browser_str='''<!DOCTYPE html>\r<html>\r<head>\r <title>SenseHat Display</title>\r <meta http-equiv="refresh" content="2.5">\r </head>\r<body>\r <h3>Latest Display on RPi SenseHat</h3>\r <object data="pixels.html"/ height='425' width='400'>\r </body></html>''' #browser_str = browser_str + '<br> Qubit Pattern: ' + label + '</body></html>' html_file.write(browser_str) html_file.close() svg_file = open (r'./svg/pixels.html',"w") #lbl_file = open (r'./svg/pixels.lbl',"w") #browser_str='''<!DOCTYPE html>\r<html>\r<head>\r # <title>SenseHat Display</title>\r # <meta http-equiv="refresh" content="1">\r # </head>\r<body>\r # <h3>Latest Display on RPi SenseHat</h3>''' browser_str= svg_pixels(pixels, brighten) + '\r <br/>Qubit Pattern: ' + label + '<br/><br/>\r' svg_file.write(browser_str) svg_file.close() #browser_str = 'Qubit Pattern: ' + label + '\r' #lbl_file.write(browser_str) #lbl_file.close() # -- prompt for any extra arguments if specified print(sys.argv) print ("Number of arguments: ",len(sys.argv)) # first check for interactive input request if (len(sys.argv)>1): parmlist = sys.argv if "-input" in sys.argv: bparmstr = input("add any additional parameters to the initial program call:\n") if len(bparmstr) > 0: bparms = bparmstr.split() print("Command parms:",parmlist,"extra parms:",bparms) parms = parmlist + bparms else: parms = parmlist print("all parms:",parms) if debug: input("Press Enter to continue") # now process the option parameters #for p in range (1, len(sys.argv)): for p in range (1, len(parms)): parameter = parms[p] if type(parameter) is str: print("Parameter ",p," ",parameter) if 'debug' in parameter: debug = True if ('16' == parameter or "-16" == parameter): qasmfileinput='16' if '-local' in parameter: UseLocal = True # use the aer local simulator instead of the web API if '-nois' in parameter: # add noise model to local simulator UseLocal = True AddNoise = True if '-noq' in parameter: QWhileThinking = False # do the rainbow wash across the qubit pattern while "thinking" if '-tee' in parameter: UseTee = True # use the new tee-shaped 5 qubit layout for the display if 'hex' in parameter: UseHex = True # use the heavy hex 12 qubit layout for the display UseTee = False # (and give it precedence over the tee display if 'q16' in parameter: UseQ16 = True # use the 12 qubit layout for the display UseTee = False # (and give it precedence over the tee display UseHex = False if '-e' in parameter: UseEmulator = True # force use of the SenseHat emulator even if hardware is installed if '-dual' in parameter: DualDisplay = True if '-select' in parameter: SelectBackend = True UseLocal = False elif ':' in parameter: # parse two-component parameters print("processing two part parameter ", parameter) token = parameter.split(':')[0] # before the colon is the key value = parameter.split(':')[1] # after the colon is the value if '-b' in token: backendparm = value # if the key is -b, specify the backend UseLocal = False print("requested backend: ", backendparm, ", UseLocal set ",UseLocal) elif '-f' in token: qasmfileinput = value # if the key is -f, specify the qasm file print("-f option: filename",qasmfileinput) elif '-nois' in token: fake_name = value if debug: input("press Enter to continue") print ("QASM File input",qasmfileinput) # Now we are going to try to instantiate the SenseHat, unless we have asked for the emulator. # if it fails, we'll try loading the emulator SenseHatEMU = False if not UseEmulator: print ("... importing SenseHat and looking for hardware") try: from sense_hat import SenseHat hat = SenseHat() # instantiating hat right away so we can use it in functions except: print ("... problem finding SenseHat") UseEmulator = True print(" ....trying SenseHat Emulator instead") if UseEmulator: print ("....importing SenseHat Emulator") from sense_emu import SenseHat # class for controlling the SenseHat hat = SenseHat() # instantiating hat emulator so we can use it in functions while not SenseHatEMU: try: hat.set_imu_config(True,True,True) #initialize the accelerometer simulation except: sleep(1) else: SenseHatEMU = True else: if DualDisplay: from sense_emu import SenseHat # class for controlling the SenseHat hat2 = SenseHat() # instantiating hat emulator so we can use it in functions while not SenseHatEMU: try: hat2.set_imu_config(True,True,True) #initialize the accelerometer simulation except: sleep(1) else: SenseHatEMU = True # some variables and settings we are going to need as we start up print("Setting up...") # This (hiding deprecation warnings) is temporary because the libraries are changing again warnings.filterwarnings("ignore", category=DeprecationWarning) Looping = True # this will be set false after the first go-round if a real backend is called angle = 180 result = None runcounter=0 maxpattern='00000' interval=5 stalled_time = 60 # how many seconds we're willing to wait once a job status is "Running" thinking=False # used to tell the display thread when to show the result shutdown=False # used to tell the display thread to trigger a shutdown qdone=False showlogo=False ########################################################################################### #------------------------------------------------------------------------------- # These variables and functions are for lighting up the qubit display on the SenseHat # ibm_qx5 builds a "bowtie" # They were moved up here so we can flash a "Q" as soon as the libraries load # # the color shift effect is based on the rainbow example included with the SenseHat library #------------------------------------------------------------------------------- # pixel coordinates to draw the bowtie qubits or the 16 qubit array ibm_qx5 = [[40,41,48,49],[8,9,16,17],[28,29,36,37],[6,7,14,15],[54,55,62,63]] ibm_qx5t = [[0,1,8,9],[3,4,11,12],[6,7,14,15],[27,28,35,36],[51,52,59,60]] ibm_qhex = [ [3], [10], [12], [17], [21], [24], [30], [33], [37], [42], [44], [51] ] ibm_qx16 = [[63],[54],[61],[52],[59],[50],[57],[48], [7],[14],[5],[12],[3],[10],[1],[8]] #[[0],[9],[2],[11],[4],[13],[6],[15], #[56],[49],[58],[51],[60],[53],[62],[55]] # global to spell OFF in a single operation X = [255, 255, 255] # white O = [ 0, 0, 0] # black off = [ O, O, O, O, O, O, O, O, O, X, O, X, X, O, X, X, X, O, X, X, O, O, X, O, X, O, X, X, X, O, X, X, X, O, X, X, O, O, X, O, O, X, O, X, O, O, X, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, ] Qlogo = [ O, O, O, X, X, O, O, O, O, O, X, O, O, X, O, O, O, O, X, O, O, X, O, O, O, O, X, O, O, X, O, O, O, O, X, O, O, X, O, O, O, O, O, X, X, O, O, O, O, O, O, O, X, O, O, O, O, O, O, X, X, O, O, O, ] QLarray = [ [3],[4], [10], [13], [18], [21], [26], [29], [34], [37], [43],[44], [52], [59],[60] ] QArcs = [ O, O, O, O, O, O, X, O, O, O, O, O, X, X, X, X, O, O, X, X, O, O, X, O, O, O, X, O, O, O, X, O, O, X, O, O, O, X, X, O, O, X, O, O, X, X, O, O, X, X, X, X, O, O, O, O, O, X, O, O, O, O, O, O, ] QArcsArray = [ [6] , [12],[13],[14],[15], [18],[19], [22], [26], [30], [33], [37], [41], [44],[45], [48],[49],[50],[51], [57] ] QKLogo = [ O, O, X, X, X, X, O, O, O, X, X, O, O, X, X, O, X, X, X, O, O, X, X, X, X, X, O, X, X, O, X, X, X, X, O, O, O, O, X, X, X, O, X, X, X, X, O, X, O, X, O, O, O, O, X, O, O, O, X, X, X, X, O, O, ] QKLogo_mask = [ [2], [3], [4], [5], [9],[10], [13],[14], [16],[17],[18], [21],[22],[23], [24],[25], [27],[28], [31], [32],[33], [38],[39], [40], [42],[43], [44],[45], [47], [49], [54], [58],[59],[60],[61] ] QHex = [ O, O, O, X, O, O, O, O, O, O, X, O, X, O, O, O, O, X, O, O, O, X, O, O, X, O, O, O, O, O, X, O, O, X, O, O, O, X, O, O, O, O, X, O, X, O, O, O, O, O, O, X, O, O, O, O, O, O, O, O, O, O, O, O, ] Arrow = [ O, O, O, X, O, O, O, O, O, O, X, X, X, O, O, O, O, X, O, X, O, X, O, O, X, O, O, X, O, O, X, O, O, O, O, X, O, O, O, O, O, O, O, X, O, O, O, O, O, O, O, X, O, O, O, O, O, O, O, X, O, O, O, O, ] # setting up the 8x8=64 pixel variables for color shifts hues = [ 0.00, 0.00, 0.06, 0.13, 0.20, 0.27, 0.34, 0.41, 0.00, 0.06, 0.13, 0.21, 0.28, 0.35, 0.42, 0.49, 0.07, 0.14, 0.21, 0.28, 0.35, 0.42, 0.50, 0.57, 0.15, 0.22, 0.29, 0.36, 0.43, 0.50, 0.57, 0.64, 0.22, 0.29, 0.36, 0.44, 0.51, 0.58, 0.65, 0.72, 0.30, 0.37, 0.44, 0.51, 0.58, 0.66, 0.73, 0.80, 0.38, 0.45, 0.52, 0.59, 0.66, 0.73, 0.80, 0.87, 0.45, 0.52, 0.60, 0.67, 0.74, 0.81, 0.88, 0.95, ] pixels = [hsv_to_rgb(h, 1.0, 1.0) for h in hues] qubits = pixels # scale lets us do a simple color rotation of hues and convert it to RGB in pixels def scale(v): return int(v * 255) def resetrainbow(show=False): global pixels,hues pixels = [hsv_to_rgb(h, 1.0, 1.0) for h in hues] pixels = [(scale(r), scale(g), scale(b)) for r, g, b in pixels] if (show): hat.set_pixels(pixels) if DualDisplay: hat2.set_pixels(pixels) def showqubits(pattern='0000000000000000'): global hat, qubits padding='' svgpattern=pattern if len(pattern)<len(display): for x in range(len(display)-len(pattern)): padding = padding + '0' pattern = pattern + padding for p in range(64): #first set all pixels off pixels[p]=[0,0,0] for q in range(len(display)): if pattern[q]=='1': # if the digit is "1" assign blue for p in display[q]: pixels[p]=[0,0,255] elif q >= qubits_needed: for p in display[q]: # if outside the number of measured qubits in the circuit, dim purple pixels[p]=[75,0,75] else: # otherwise assign it red for p in display[q]: pixels[p]=[255,0,0] qubits=pixels qubitpattern=pattern hat.set_pixels(pixels) # turn them all on write_svg_file(pixels, svgpattern, 2.5, False) if DualDisplay: hat2.set_pixels(pixels) #write_svg_file(qubits,2.5) #-------------------------------------------------- # blinky lets us use the rainbow rotation code to fill the bowtie pattern # it can be interrupted by tapping the joystick or if # an experiment ID is provided and the # status returns "DONE" # #------------------------------------------------------ def blinky(time=20,experimentID=''): global pixels,hues,experiment, Qlogo, showlogo, QArcs, QKLogo, QHex, qubits, qubitpattern if QWhileThinking: mask = QKLogo_mask else: mask = display #resetrainbow() count=0 GoNow=False while ((count*.02<time) and (not GoNow)): # Rotate the hues hues = [(h + 0.01) % 1.0 for h in hues] # Convert the hues to RGB values pixels = [hsv_to_rgb(h, 1.0, 1.0) for h in hues] # hsv_to_rgb returns 0..1 floats; convert to ints in the range 0..255 pixels = [(scale(r), scale(g), scale(b)) for r, g, b in pixels] for p in range(64): #if QWhileThinking: # if p in sum(Qlogo,[]): # pass # else: # pixels[p]=[0,0,0] # else: if p in sum(mask,[]): #if p in sum(display,[]): pass else: pixels[p]=[0,0,0] if (result is not None): if (result.status=='COMPLETED'): GoNow=True # Update the display if not showlogo: hat.set_pixels(pixels) if DualDisplay: hat2.set_pixels(pixels) else: hat.set_pixels(QKLogo) if DualDisplay: hat2.set_pixels(QArcs) sleep(0.002) count+=1 for event in hat.stick.get_events(): if event.action == 'pressed': goNow=True if event.action == 'held' and event.direction =='middle': shutdown=True #------------------------------------------------ # now that the light pattern functions are defined, # build a class glow so we can launch display control as a thread #------------------------------------------------ class glow(): global thinking,hat, maxpattern, shutdown,off,Qlogo, QArcs, Qhex def __init__(self): self._running = True def stop(self): self._running = False self._stop = True def run(self): #thinking=False while self._running: if shutdown: hat.set_rotation(angle) hat.set_pixels(off) sleep(1) hat.clear() if DualDisplay: hat2.clear() path = 'sudo shutdown -P now ' os.system (path) else: if thinking: blinky(.1) else: showqubits(maxpattern) #---------------------------------------------------------------- # Set the display size and rotation Turn on the display with an IBM "Q" logo #---------------------------------------------------------------- def orient(): global hat,angle acceleration = hat.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] x=round(x, 0) y=round(y, 0) z=round(z, 0) print("current acceleration: ",x,y,z) if y == -1: angle = 180 elif y == 1 or (SenseHatEMU and not DualDisplay): angle = 0 elif x == -1: angle = 90 elif x == 1: angle = 270 #else: #angle = 180 print("angle selected:",angle) hat.set_rotation(angle) if DualDisplay: hat2.set_rotation(0) # Now call the orient function and show an arrow orient() display=ibm_qx16 hat.set_pixels(Arrow) if DualDisplay: hat2.set_pixels(Arrow) ################################################################## # Input file functions ################################################################## #---------------------------------------------------------- # find our experiment file... alternate can be specified on command line # use a couple tricks to make sure it is there # if not fall back on our default file #def loadQASMfile(): scriptfolder = os.path.dirname(os.path.realpath("__file__")) #print(sys.argv) #print ("Number of arguments: ",len(sys.argv)) # look for a filename option #if (len(sys.argv) > 1) and type(sys.argv[1]) is str: #print (type(sys.argv[1])) # qasmfilename=sys.argv[1] # print ("input arg:",qasmfilename) if (qasmfileinput == '16'): qasmfilename='expt16.qasm' else: qasmfilename = qasmfileinput #qasmfilename='expt.qasm' print("QASM File:",qasmfilename) #complete the path if necessary if ('/' not in qasmfilename): qasmfilename=scriptfolder+"/"+qasmfilename if (not os.path.isfile(qasmfilename)): qasmfilename=scriptfolder+"/"+'expt.qasm' print("OPENQASM file: ",qasmfilename) if (not os.path.isfile(qasmfilename)): print("QASM file not found... exiting.") exit() # Parse any other parameters: # end DEF ---------------------- ############################################################### # Connection functions # ping and authentication ############################################################### #---------------------------------------------------------------------------- # set up a ping function so we can confirm the service can connect before we attempt it # ping uses the requests library # based on pi-ping by Wesley Archer (raspberrycoulis) (c) 2017 # https://github.com/raspberrycoulis/Pi-Ping #---------------------------------------------------------------------------- def ping(website='https://quantum-computing.ibm.com/',repeats=1,wait=0.5,verbose=False): msg = 'ping response' for n in range(repeats): response = requests.get(website) if int(response.status_code) == 200: # OK pass elif int(response.status_code) == 500: # Internal server error msg ='Internal server error' elif int(response.status_code) == 503: # Service unavailable msg = 'Service unavailable' elif int(response.status_code) == 502: # Bad gateway msg = 'Bad gateway' elif int(response.status_code) == 520: # Cloudflare: Unknown error msg = 'Cloudflare: Unknown error' elif int(response.status_code) == 522: # Cloudflare: Connection timed out msg = 'Cloudflare: Connection timed out' elif int(response.status_code) == 523: # Cloudflare: Origin is unreachable msg = 'Cloudflare: Origin is unreachable' elif int(response.status_code) == 524: # Cloudflare: A Timeout occurred msg = 'Cloudflare: A Timeout occurred' if verbose: print(response.status_code,msg) if repeats>1: sleep(wait) return int(response.status_code) # end DEF ---------------------------------------------------------------- # ------------------------------------------------------------------------ # try to start our IBM Quantum backend (simulator or real) and connection to IBM Quantum APIs # Here we attempt to ping the IBM Quantum Computing API servers. If no response, we exit # If we get a 200 response, the site is live and we initialize our connection to it #------------------------------------------------------------------------------- def startIBMQ(): global Q, backend, UseLocal, backendparm # This version written to work only with the new QiskitRuntimeService module from Qiskit > v1.0 sQPV = IBMQVersion pd = '.' dot1 = [pos for pos, char in enumerate(sQPV) if char==pd][0] dot2 = [pos for pos, char in enumerate(sQPV) if char==pd][1] IBMQP_Vers=float(sQPV[0:dot2]) if SelectBackend: backendparm = input("type the backend you wish to use:\n" "'least' will find a least-busy real backend.\n" " 'aer' will generate a basic Aer Simulator\n" " 'aernois' or 'airmodel' will create a real-system noise modeled Aer simulator.\n") elif UseLocal: backendparm = "FakeManilaV2" print('IBMQ Provider v',IBMQP_Vers, "backendparm ",backendparm,", UseLocal",UseLocal) if debug: input("Press Enter Key") if qubits_needed > 5 and UseLocal: UseLocal = False backendparm = 'aer' if not UseLocal: print ('Pinging IBM Quantum API server before start') p=ping('https://api.quantum-computing.ibm.com',1,0.5,True) #p=ping('https://auth.quantum-computing.ibm.com/api',1,0.5,True) #p=ping('https://quantum-computing.ibm.com/',1,0.5,True) try: print("requested backend: ",backendparm) except: sleep(0) # specify the simulator as the backup backend (this must change after May 15 2024) backend='ibmq_qasm_simulator' if p==200: if (IBMQP_Vers >= 1): # The new authentication technique with provider as the object print("trying to create backend connection") Qservice=QiskitRuntimeService() if "aer" in backendparm: from qiskit_aer import AerSimulator if "model" in backendparm or "nois" in backendparm or AddNoise: print("getting a real backend connection for aer model") real_backend = Qservice.least_busy(simulator=False)#operational=True, backend("ibm_brisbane") print("creating AerSimulator modeled from ",real_backend.name) Q = AerSimulator.from_backend(real_backend) else: print("creating basic Aer Simulator") Q = AerSimulator() UseLocal=True #now that it's built, mark the backend as local else: try: if "least" in backendparm: Q = Qservice.least_busy(operational=True, simulator=False) else: Q = Qservice.backend(backendparm) except: print("first backend attempt failed...") Q=Qservice.backend(backend) else: interval = 300 else: # The older IBMQ authentication technique exit() #this code only works with the new Qiskit>v1.0 else: exit() else: # THIS IS THE CASE FOR USING LOCAL SIMULATOR backend='local aer qasm_simulator' print ("Building ",backend, "with requested attributes...") if not AddNoise: from qiskit_aer import AerSimulator Q = AerSimulator() #Aer.get_backend('qasm_simulator') else: Q = FakeManilaV2() #------------------------------------------------------------------------------- ################################################################################# # # Main program loop (note: we turned on a logo earlier at line 202) # ################################################################################# # Instantiate an instance of our glow class print("Instantiating glow...") glowing = glow() # create the html shell file write_svg_file(pixels, maxpattern, 2.5, True) #------------------------------------------------- # OK, let's get this shindig started #------------------------------------------------- #First, let's read our input file and see how many qubits we need? exptfile = open(qasmfilename,'r') # open the file with the OPENQASM code in it qasm= exptfile.read() # read the contents into our experiment string if (len(qasm)<5): # if that is too short to be real, exit exit else: # otherwise print it to the console for reference print("OPENQASM code to send:\n",qasm) #to determin the number of qubits, we have to make the circuit qcirc=QuantumCircuit.from_qasm_str(qasm) qubits_needed = qcirc.num_qubits rainbowTie = Thread(target=glowing.run) # create the display thread startIBMQ() # try to connect and instantiate the IBMQ qcirc=QuantumCircuit.from_qasm_str(qasm) try: print("generating circuit from QASM")# (qcirc) except UnicodeEncodeError: print ('Unable to render quantum circuit drawing; incompatible Unicode environment') except: print ('Unable to render quantum circuit drawing for some reason') if (qubits_needed > 5 and not UseHex) or UseQ16: display = ibm_qx16 maxpattern='0000000000000000' print ("circuit width: ",qubits_needed," using 16 qubit display") else: if (UseTee and qubits_needed <= 5 ): display = ibm_qx5t maxpattern='00000' elif (UseHex): display = ibm_qhex maxpattern='000000000000' else: display = ibm_qx5 maxpattern='00000' print ("circuit width: ",qubits_needed," using 5 qubit display") qubitpattern=maxpattern #backend='simulator' rainbowTie.start() # start the display thread while Looping: runcounter += 1 if "aer" in backendparm: UseLocal=True try: if not UseLocal: p=ping() else: p=200 except: print("connection problem with IBMQ") else: if p==200: orient() showlogo = True thinking = True Qname=Q.name print("Name:",Q.name,"Version:",Q.version,"No. of qubits:",Q.num_qubits) if not UseLocal and not "aer" in backendparm: Qstatus=Q.status() print(Qstatus.backend_name, "is simulator? ", Q.simulator, "| operational: ", Qstatus.operational ,"| jobs in queue:",Qstatus.pending_jobs) try: if not UseLocal: Qstatus = Q.status() # check the availability except: print('Problem getting backend status... waiting to try again') else: if not UseLocal: Qstatus=Q.status() print('Backend Status: ',Qstatus.status_msg, 'operational:',Qstatus.operational) if debug: input('press enter') qstatmsg=Qstatus.status_msg q_operational=Qstatus.operational else: qstatmsg='active' q_operational=False if (qstatmsg == 'active' and q_operational) or UseLocal: print(' executing quantum circuit... on ',Q.name) #print(Q.name,' options:',Q.options) try: print (qcirc) except UnicodeEncodeError: print ('Unable to render quantum circuit drawing; incompatible Unicode environment') except: print ('Unable to render quantum circuit drawing for some reason') try: qk1_circ=transpile(qcirc, Q) # transpile for the new primitive except: print("problem transpiling circuit") else: print("transpilation complete") #try: if not UseLocal: print("backend: ",Q.name," operational? ",Q.status().operational," Pending:",Q.status().pending_jobs) else: print("backend: ",Q.name," operational? ALWAYS") if debug: input('Press the Enter Key') print("running job") qjob=Q.run(qk1_circ) # run print("JobID: ",qjob.job_id()) print("Job Done?",qjob.done()) #if qjob.errored(): # print("error message:",qjob.error_message()) #qjob=execute(qcirc, Q, shots=500, memory=False) Looping = UseLocal or Q.simulator if runcounter < 3: print("Using ", Qname, " ... Looping is set ", Looping) running_start = 0 running_timeout = False running_cancelled = False showlogo = False qdone = False while not (qdone or running_timeout or running_cancelled): qdone = qjob.in_final_state() or qjob.cancelled() if not UseLocal: print(running_start,qjob.job_id(),"Job Done? ", qjob.in_final_state(),"| Cancelled? ",qjob.cancelled(),"| queued jobs:",qjob.backend().status().pending_jobs) else: print(running_start,qjob.job_id(),"Job Done? ", qjob.in_final_state(),"| Cancelled? ",qjob.cancelled()) if not qdone: running_start+=1; #if qjob.errored(): # print("error message:",qjob.error_message()) # running_cancelled = True if qjob.done() : # only get here once we get DONE status result=qjob.result() # get the result counts=result.get_counts(qcirc) #print("counts:",counts) maxpattern=max(counts,key=counts.get) qubitpattern=maxpattern maxvalue=counts[maxpattern] print("Maximum value:",maxvalue, "Maximum pattern:",maxpattern) if UseLocal: sleep(3) thinking = False # this cues the display thread to show the qubits in maxpattern if running_timeout : print(backend,' Queue appears to have stalled. Restarting Job.') if running_cancelled : print(backend,' Job cancelled at backend. Restarting.') #except: # print(Q.name, qjob.job_id(), 'problem; waiting to try again') #else: # print(p,'response to ping; waiting to try again') #print("qubit list",qubits) #write_svg_file(qubits,maxpattern, 2.5) goAgain=False # wait to do it again if Looping: print('Waiting ',interval,'s before next run...') myTimer=process_time() while not goAgain: for event in hat.stick.get_events(): if event.action == 'pressed': #somebody tapped the joystick -- go now goAgain=True blinky(.001) hat.set_pixels(pixels) if DualDisplay: hat2.set_pixels(pixels) if event.action == 'held' and event.direction =='middle': shutdown=True if event.action == 'held' and event.direction !='middle': Looping = False break if (process_time()-myTimer>interval): # 10 seconds elapsed -- go now goAgain=True print("Program Execution ended normally")
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """DAGFixedPoint pass testing""" import unittest from qiskit.transpiler.passes import DAGFixedPoint from qiskit import QuantumRegister, QuantumCircuit from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestFixedPointPass(QiskitTestCase): """Tests for PropertySet methods.""" def test_empty_dag_true(self): """Test the dag fixed point of an empty dag.""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = DAGFixedPoint() pass_.run(dag) self.assertFalse(pass_.property_set["dag_fixed_point"]) pass_.run(dag) self.assertTrue(pass_.property_set["dag_fixed_point"]) def test_nonempty_dag_false(self): """Test the dag false fixed point of a non-empty dag.""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = DAGFixedPoint() pass_.run(dag) self.assertFalse(pass_.property_set["dag_fixed_point"]) dag.remove_all_ops_named("h") pass_.run(dag) self.assertFalse(pass_.property_set["dag_fixed_point"]) if __name__ == "__main__": unittest.main()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import getpass, time from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import available_backends, execute, register, least_busy # import basic plot tools from qiskit.tools.visualization import plot_histogram, circuit_drawer APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url":"https://quantumexperience.ng.bluemix.net/api"} try: register(qx_config['APItoken'], qx_config['url']) print('\nYou have access to great power!') print(available_backends({'local': False, 'simulator': False})) except: print('Something went wrong.\nDid you enter a correct token?') backend = least_busy(available_backends({'simulator': False, 'local': False})) print("The least busy backend is " + backend) q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) job_exp = execute(qc, backend=backend, shots=1024, max_credits=3) lapse = 0 interval = 30 while not job_exp.done: print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status) time.sleep(interval) lapse += 1 print(job_exp.status) plot_histogram(job_exp.result().get_counts(qc)) print('You have made entanglement!') circuit_drawer(qc)
https://github.com/quantumjim/qreative
quantumjim
%matplotlib notebook import sys sys.path.append('../') import CreativeQiskit grid = CreativeQiskit.pauli_grid() grid.update_grid() for gate in [['x','1'],['h','0'],['z','0'],['h','1'],['z','1']]: command = 'grid.qc.'+gate[0]+'(grid.qr['+gate[1]+'])' eval(command) grid.update_grid() grid = CreativeQiskit.pauli_grid(mode='line') grid.update_grid() grid = CreativeQiskit.pauli_grid(y_boxes=True) grid.update_grid() grid.qc.h(grid.qr[0]) grid.update_grid() grid = CreativeQiskit.pauli_grid(y_boxes=True) grid.update_grid(labels=True) grid.qc.h(grid.qr[0]) grid.qc.s(grid.qr[0]) grid.update_grid(labels=True) grid = CreativeQiskit.pauli_grid(noisy=True) grid.update_grid()
https://github.com/hugoecarl/TSP-Problem-Study
hugoecarl
with open('in-exemplo.txt', 'r') as f: print(f.read()) with open('out-exemplo.txt', 'r') as f: print(f.read()) import time import matplotlib.pyplot as plt import pandas as pd import os import subprocess %matplotlib inline #Roda entradas def roda_com_entrada(executavel, arquivo_in, envs = '1', deb = '0'): with open(arquivo_in) as f: start = time.perf_counter() a = f.read() proc = subprocess.run([executavel], input=a, text=True, capture_output=True, env=dict(OMP_NUM_THREADS=envs, DEBUG=deb, **os.environ)) end = time.perf_counter() f.close() ret = '' for i in a: if i == "\n": break ret += i return (proc.stdout, end - start, int(ret)) v #retorna tamanho do tour apartir do stdout buf = '' for i in out: if i == " ": return float(buf) buf += i #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] tempos_2 = [] resultados1 = [] resultados2 = [] resultados3 = [] #Usando as mesmas entradas for i in range(8): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca_local_antigo','busca-exaustiva/in-'+str(i)+'.txt') b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt') c = roda_com_entrada('./heuristico/heuristico','busca-exaustiva/in-'+str(i)+'.txt') tempos.append(a[1]) tempos_1.append(b[1]) tempos_2.append(c[1]) tamanho_entradas.append(a[2]) resultados1.append(tamanho_tour(a[0])) resultados2.append(tamanho_tour(b[0])) resultados3.append(tamanho_tour(c[0])) #Teste com entrada um pouco maior print("Rodando entrada: 8") tempos.append(roda_com_entrada('./busca_local_antigo','maior.txt')[1]) tempos_1.append(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[1]) tempos_2.append(roda_com_entrada('./heuristico/heuristico','maior.txt')[1]) tamanho_entradas.append(roda_com_entrada('./busca-local/busca-local','maior.txt')[2]) resultados1.append(tamanho_tour(roda_com_entrada('./busca_local_antigo','maior.txt')[0])) resultados2.append(tamanho_tour(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[0])) resultados3.append(tamanho_tour(roda_com_entrada('./heuristico/heuristico','maior.txt')[0])) plt.title("Comparacao Desempenho") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos_1) plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_2) plt.legend(["busca-exaustiva", "busca-local","heuristico"]) plt.show() plt.title("Comparacao Desempenho") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_2) plt.legend(["busca-local","heuristico"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-local-tempo"] = pd.Series(tempos) df["busca-exaustiva-tempo"] = pd.Series(tempos_1) df["heuristica-tempo"] = pd.Series(tempos_2) df["busca-local-resultado"] = pd.Series(resultados1) df["busca-exaustiva-resultado"] = pd.Series(resultados2) df["heuristica-resultado"] = pd.Series(resultados3) df df.describe() #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] tempos_2 = [] tempos_3 = [] tempos_4 = [] tempos_5 = [] #Usando as mesmas entradas for i in range(7): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt') b = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','2') c = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','3') d = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','4') e = roda_com_entrada('./busca_local_antigo','busca-local/in-'+str(i)+'.txt') f = roda_com_entrada('./busca-local/busca-local-gpu','busca-local/in-'+str(i)+'.txt') tempos.append(a[1]) tempos_1.append(b[1]) tempos_2.append(c[1]) tempos_3.append(d[1]) tempos_4.append(e[1]) tempos_5.append(f[1]) tamanho_entradas.append(a[2]) plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_1) plt.plot(tamanho_entradas, tempos_2) plt.plot(tamanho_entradas, tempos_3) plt.legend(["1 thread otimizado", "2 threads otimizado","3 threads otimizado", "4 threads otimizado", "Sem otimizações"]) plt.show() plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos_3) plt.plot(tamanho_entradas, tempos_5) plt.legend(["4 thread otimizado", "GPU"]) plt.show() plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_4) plt.legend(["1 thread otimizado", "Sem otimizações"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-local-1-thread"] = pd.Series(tempos) df["busca-local-2-threads"] = pd.Series(tempos_1) df["busca-local-3-threads"] = pd.Series(tempos_2) df["busca-local-4-threads"] = pd.Series(tempos_3) df["busca-local-gpu"] = pd.Series(tempos_5) df["busca-local-semopt"] = pd.Series(tempos_4) df #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] tempos_2 = [] #Usando as mesmas entradas for i in range(8): print("Rodando entrada: "+str(i)) if i != 7: a = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '1') tempos.append(a[1]) b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '8', '0') c = roda_com_entrada('./busca-exaustiva-apenasbb','busca-exaustiva/in-'+str(i)+'.txt', '1', '0') tempos_1.append(b[1]) tempos_2.append(c[1]) tamanho_entradas.append(a[2]) plt.title("Comparacao Desempenho Busca Exaustiva") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas[:-1], tempos) plt.plot(tamanho_entradas[:-1], tempos_2[:-1]) plt.legend(["Exaustivo Simples", "Exaustivo Branch and Bound"]) plt.show() plt.title("Comparacao Desempenho Busca Exaustiva") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos_1) plt.plot(tamanho_entradas, tempos_2) plt.legend(["Branch and Bound Paralelo", "Branch and Bound Simples"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-exaustiva-simples"] = pd.Series(tempos) df["busca-exaustiva-branchnbound"] = pd.Series(tempos_2) df["busca-exaustiva-branchnbound-par"] = pd.Series(tempos_1) df
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') from qiskit import IBMQ from qiskit.providers.ibmq.visualization import iplot_gate_map IBMQ.load_account() provider = IBMQ.get_provider(group='open', project='main') backend = provider.get_backend('ibmq_vigo') iplot_gate_map(backend, as_widget=True)
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
ahkatlio
# We import the necessary functions from Qiskit from qiskit.visualization import plot_bloch_multivector, plot_state_qsphere, visualize_transition from qiskit import QuantumCircuit, Aer, execute # We create a quantum circuit with one qubit qc = QuantumCircuit(1) # We execute the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') # This code executes a quantum circuit `qc` on a backend and stores the result in the `result` variable. # The `execute` function is used to run the circuit on the specified backend and returns a job object. # The `result()` method is then called on the job object to get the result of the execution. result = execute(qc, backend).result() # We get the statevector of the quantum circuit statevector = result.get_statevector(qc) # We plot the statevector on the Bloch sphere plot_bloch_multivector(statevector) plot_state_qsphere(statevector, show_state_phases = True, use_degrees = True) # We add a Hadamard gate to the circuit qc.h(0) visualize_transition(qc)
https://github.com/arian-code/nptel_quantum_assignments
arian-code
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 * # Loading your IBM Q account(s) provider = IBMQ.load_account() from qiskit import assemble import numpy as np import matplotlib.pyplot as plt n=4 grover_ckt = QuantumCircuit(n+1, n) marked = [1,0,1,1] # 1101 element is marked (lsb to msb)=>13 def apply_oracle(n,marked,ckt): control0 = [i for i in range(n) if not marked[i]] ckt.x(control0) ckt.mct(list(range(n)),n) ckt.x(control0) ckt.draw() #option A def reflect_uniform(ckt,n): ckt.h(list(range(n))) ckt.x(list(range(n))) ckt.mct(list(range(n)),n) ckt.x(list(range(n))) ckt.h(list(range(n))) ckt.x(n) #Test option A qc=QuantumCircuit(5) reflect_uniform(qc,4) qc.draw()
https://github.com/biswaroopmukherjee/Quantum-Waddle
biswaroopmukherjee
import qiskit import numpy as np from qiskit import( IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister, execute, QuantumCircuit, execute, Aer) from qiskit.visualization import plot_histogram, plot_state_city def increment_gate(circuit, qpos, qcoin): n = len(qpos) for i in range(n): circuit.mct(qcoin[:]+qpos[i+1:], qpos[i], None, mode='noancilla') def decrement_gate(circuit, qpos, qcoin): n = len(qpos) for i in range(n): if i+1 < n: circuit.x(qpos[i+1:]) circuit.mct(qcoin[:]+qpos[i+1:], qpos[i], None, mode='noancilla') if i+1 < n: circuit.x(qpos[i+1:]) def step(circuit, qpos, qcoin): circuit.h(qcoin) circuit.barrier() # y operations increment_gate(circuit, qpos[len(qpos)//2:], qcoin) circuit.x(qcoin[0]) decrement_gate(circuit, qpos[len(qpos)//2:], qcoin) # x operations circuit.x(qcoin) increment_gate(circuit, qpos[:len(qpos)//2], qcoin) circuit.x(qcoin[0]) decrement_gate(circuit, qpos[:len(qpos)//2:], qcoin) circuit.barrier() simulator = Aer.get_backend('qasm_simulator') n=3 qpos = QuantumRegister(2*n,'qc') qcoin = QuantumRegister(2,'qanc') cpos = ClassicalRegister(2*n,'cr') circuit = QuantumCircuit(qpos, qcoin, cpos) step(circuit, qpos, qcoin) # # Map the quantum measurement to the classical bits circuit.measure(qpos,cpos) # # 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("\nTotal count for 00 and 11 are:",counts) # Draw the circuit # circuit.draw() # Plot a histogram plot_histogram(counts) counts
https://github.com/Qiskit/feedback
Qiskit
from matplotlib import pyplot as plt import numpy as np from scipy.integrate import quad from qiskit.quantum_info.states import Statevector, DensityMatrix from qiskit.quantum_info.operators import Operator from qiskit.quantum_info.operators import SuperOp, Choi, Kraus, PTM from qiskit_dynamics import solve_ode, solve_lmde from qiskit_dynamics.signals import Signal from qiskit_dynamics.models import (HamiltonianModel, LindbladModel, rotating_wave_approximation) def gaussian(amp, sig, t0, t): return amp * np.exp( -(t - t0)**2 / (2 * sig**2) ) amp = 1. # amplitude sig = 2. # sigma t0 = 3.5*sig # center of Gaussian T = 7*sig # end of signal gaussian_envelope = lambda t: gaussian(amp, sig, t0, t) gauss_signal = Signal(envelope=gaussian_envelope, carrier_freq=0.5) print(gauss_signal.envelope(0.25)) print(gauss_signal(0.25)) gauss_signal.draw(0, T, 100, function='envelope') gauss_signal.draw(0, T, 200) ##################### # construct operators ##################### r = 0.5 w = 1. X = Operator.from_label('X') Y = Operator.from_label('Y') Z = Operator.from_label('Z') drift = 2 * np.pi * w * Z/2 operators = [2 * np.pi * r * X/2] ################### # construct signals ################### # Define gaussian envelope function to have max amp and area approx 2 amp = 1. sig = 0.399128/r t0 = 3.5*sig T = 7*sig gaussian_envelope = lambda t: gaussian(amp, sig, t0, t) signals = [Signal(envelope=gaussian_envelope, carrier_freq=w)] ################# # construct model ################# hamiltonian = HamiltonianModel(drift=drift, operators=operators, signals=signals) print(hamiltonian.evaluate(0.12)) hamiltonian.get_drift() def plot_qubit_hamiltonian_components(hamiltonian, t0, tf, N=200): t_vals = np.linspace(t0, tf, N) model_vals = np.array([1j*hamiltonian.evaluate(t) for t in t_vals]) x_coeff = model_vals[:, 0, 1].real y_coeff = -model_vals[:, 0, 1].imag z_coeff = model_vals[:, 0, 0].real plt.plot(t_vals, x_coeff, label='X component') plt.plot(t_vals, y_coeff, label='Y component') plt.plot(t_vals, z_coeff, label='Z component') plt.legend() plot_qubit_hamiltonian_components(hamiltonian, 0., T) hamiltonian.rotating_frame = hamiltonian.get_drift() print(hamiltonian.evaluate(0.12)) # validate with independent computation t = 0.12 -1j*(2 * np.pi * r * np.real(signals[0](t)) * (np.cos(2*np.pi * w * t) * X / 2 - np.sin(2*np.pi * w * t) * Y / 2 )) plot_qubit_hamiltonian_components(hamiltonian, 0., T) # set the cutoff frequency rwa_hamiltonian = rotating_wave_approximation(hamiltonian, 2*w) # evaluate again print(rwa_hamiltonian.evaluate(0.12)) plot_qubit_hamiltonian_components(rwa_hamiltonian, 0., T) # solve the problem, with some options specified y0 = Statevector([0., 1.]) %time sol = solve_lmde(hamiltonian, t_span=[0., T], y0=y0, atol=1e-10, rtol=1e-10) y = sol.y[-1] print("\nFinal state:") print("----------------------------") print(y) print("\nPopulation in excited state:") print("----------------------------") print(np.abs(y[0])**2) %time sol = solve_lmde(rwa_hamiltonian, t_span=[0., T], y0=y0, atol=1e-10, rtol=1e-10) y = sol.y[-1] print("\nFinal state:") print("----------------------------") print(y) print("\nPopulation in excited state:") print("----------------------------") print(np.abs(y[0])**2) # construct quantum model with noise operators noise_ops = [np.array([[0., 0.], [1., 0.]])] noise_signals = [0.001] lindblad_model = LindbladModel.from_hamiltonian(hamiltonian=hamiltonian, dissipator_operators=noise_ops, dissipator_signals=noise_signals) lindblad_model = LindbladModel(hamiltonian_operators=operators, drift=drift, rotating_frame=drift, hamiltonian_signals=signals, dissipator_operators=noise_ops, dissipator_signals=noise_signals) # density matrix y0 = DensityMatrix([[0., 0.], [0., 1.]]) %time sol = solve_lmde(lindblad_model, t_span=[0., T], y0=y0, atol=1e-10, rtol=1e-10) sol.y[-1] rwa_lindblad_model = rotating_wave_approximation(lindblad_model, 2.0*w) %time sol = solve_lmde(rwa_lindblad_model, t_span=[0., T], y0=y0, atol=1e-10, rtol=1e-10) sol.y[-1] lindblad_model.evaluation_mode = 'dense_vectorized' lindblad_model.rotating_frame = None # identity quantum channel in superop representation y0 = SuperOp(np.eye(4)) %time sol = solve_lmde(lindblad_model.__call__, t_span=[0., T], y0=y0, atol=1e-12, rtol=1e-12) print(sol.y[-1]) print(PTM(sol.y[-1]))
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# -*- coding: utf-8 -*- # 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. # pylint: disable=cell-var-from-loop,invalid-name """ Measurement correction filters. """ from copy import deepcopy import numpy as np import qiskit import scipy.linalg as la from qiskit import QiskitError from qiskit.utils.mitigation.circuits import count_keys from qiskit.tools import parallel_map from scipy.optimize import minimize # pylint: disable=too-many-locals,too-many-branches,too-many-nested-blocks,too-many-statements class MeasurementFilter: """ Measurement error mitigation filter. Produced from a measurement calibration fitter and can be applied to data. """ def __init__(self, cal_matrix: np.matrix, state_labels: list): """ Initialize a measurement error mitigation filter using the cal_matrix from a measurement calibration fitter. Args: cal_matrix: the calibration matrix for applying the correction state_labels: the states for the ordering of the cal matrix """ self._cal_matrix = cal_matrix self._state_labels = state_labels @property def cal_matrix(self): """Return cal_matrix.""" return self._cal_matrix @property def state_labels(self): """return the state label ordering of the cal matrix""" return self._state_labels @state_labels.setter def state_labels(self, new_state_labels): """set the state label ordering of the cal matrix""" self._state_labels = new_state_labels @cal_matrix.setter def cal_matrix(self, new_cal_matrix): """Set cal_matrix.""" self._cal_matrix = new_cal_matrix def apply(self, raw_data, method="least_squares"): """Apply the calibration matrix to results. Args: raw_data (dict or list): The data to be corrected. Can be in a number of forms: Form 1: a counts dictionary from results.get_counts Form 2: a list of counts of `length==len(state_labels)` I have no idea what this is. I'm not supporting it here. --> Form 3: a list of counts of `length==M*len(state_labels)` where M is an integer (e.g. for use with the tomography data) Form 4: a qiskit Result method (str): fitting method. If `None`, then least_squares is used. ``pseudo_inverse``: direct inversion of the A matrix ``least_squares``: constrained to have physical probabilities Returns: dict or list: The corrected data in the same form as `raw_data` Raises: QiskitError: if `raw_data` is not an integer multiple of the number of calibrated states. """ raw_data = deepcopy(raw_data) output_type = None if isinstance(raw_data, qiskit.result.result.Result): output_Result = deepcopy(raw_data) output_type = "result" raw_data = raw_data.get_counts() if isinstance(raw_data, dict): raw_data = [raw_data] elif isinstance(raw_data, list): output_type = "list" elif isinstance(raw_data, dict): raw_data = [raw_data] output_type = "dict" assert output_type unique_data_labels = {key for data_row in raw_data for key in data_row.keys()} if not unique_data_labels.issubset(set(self._state_labels)): raise QiskitError( "Unexpected state label '" + unique_data_labels + "', verify the fitter's state labels correpsond to the input data" ) raw_data_array = np.zeros((len(raw_data), len(self._state_labels)), dtype=float) corrected_data_array = np.zeros( (len(raw_data), len(self._state_labels)), dtype=float ) for expt_idx, data_row in enumerate(raw_data): for stateidx, state in enumerate(self._state_labels): raw_data_array[expt_idx][stateidx] = data_row.get(state, 0) if method == "pseudo_inverse": pinv_cal_mat = la.pinv(self._cal_matrix) # pylint: disable=unused-variable corrected_data = np.einsum("ij,xj->xi", pinv_cal_mat, raw_data_array) elif method == "least_squares": nshots_each_expt = np.sum(raw_data_array, axis=1) for expt_idx, (nshots, raw_data_row) in enumerate( zip(nshots_each_expt, raw_data_array) ): cal_mat = self._cal_matrix nlabels = len(raw_data_row) # pylint: disable=unused-variable def fun(estimated_corrected_data): return np.sum( (raw_data_row - cal_mat.dot(estimated_corrected_data)) ** 2 ) def gradient(estimated_corrected_data): return 2 * ( cal_mat.dot(estimated_corrected_data) - raw_data_row ).dot(cal_mat) cons = { "type": "eq", "fun": lambda x: nshots - np.sum(x), "jac": lambda x: -1 * np.ones_like(x), } bnds = tuple((0, nshots) for x in raw_data_row) res = minimize( fun, raw_data_row, method="SLSQP", constraints=cons, bounds=bnds, tol=1e-6, jac=gradient, ) # def fun(angles): # # for bounding between 0 and 1 # cos2 = np.cos(angles)**2 # # form should constrain so sum always = nshots. # estimated_corrected_data = nshots * \ # (1/nlabels + (nlabels*cos2 - # np.sum(cos2))/(nlabels-1)) # return np.sum( (raw_data_row - # cal_mat.dot(estimated_corrected_data) )**2) # # def gradient(estimated_corrected_data): # return 2 * (cal_mat.dot(estimated_corrected_data) - # raw_data_row).dot(cal_mat) # # bnds = tuple((0, nshots) for x in raw_data_this_idx) # res = minimize(fun, raw_data_row, # method='SLSQP', constraints=cons, # bounds=bnds, tol=1e-6, jac=gradient) corrected_data_array[expt_idx] = res.x else: raise QiskitError("Unrecognized method.") # time_finished_correction = time.time() # convert back into a counts dictionary corrected_dicts = [] for corrected_data_row in corrected_data_array: new_count_dict = {} for stateidx, state in enumerate(self._state_labels): if corrected_data_row[stateidx] != 0: new_count_dict[state] = corrected_data_row[stateidx] corrected_dicts.append(new_count_dict) if output_type == "dict": assert len(corrected_dicts) == 1 # converting back to a single counts dict, to match input provided by user output = corrected_dicts[0] elif output_type == "list": output = corrected_dicts elif output_type == "result": for resultidx, new_counts in enumerate(corrected_dicts): output_Result.results[resultidx].data.counts = new_counts output = output_Result else: raise TypeError() return output class TensoredFilter: """ Tensored measurement error mitigation filter. Produced from a tensored measurement calibration fitter and can be applied to data. """ def __init__(self, cal_matrices: np.matrix, substate_labels_list: list): """ Initialize a tensored measurement error mitigation filter using the cal_matrices from a tensored measurement calibration fitter. Args: cal_matrices: the calibration matrices for applying the correction. substate_labels_list: for each calibration matrix a list of the states (as strings, states in the subspace) """ self._cal_matrices = cal_matrices self._qubit_list_sizes = [] self._indices_list = [] self._substate_labels_list = [] self.substate_labels_list = substate_labels_list @property def cal_matrices(self): """Return cal_matrices.""" return self._cal_matrices @cal_matrices.setter def cal_matrices(self, new_cal_matrices): """Set cal_matrices.""" self._cal_matrices = deepcopy(new_cal_matrices) @property def substate_labels_list(self): """Return _substate_labels_list""" return self._substate_labels_list @substate_labels_list.setter def substate_labels_list(self, new_substate_labels_list): """Return _substate_labels_list""" self._substate_labels_list = new_substate_labels_list # get the number of qubits in each subspace self._qubit_list_sizes = [] for _, substate_label_list in enumerate(self._substate_labels_list): self._qubit_list_sizes.append(int(np.log2(len(substate_label_list)))) # get the indices in the calibration matrix self._indices_list = [] for _, sub_labels in enumerate(self._substate_labels_list): self._indices_list.append({lab: ind for ind, lab in enumerate(sub_labels)}) @property def qubit_list_sizes(self): """Return _qubit_list_sizes.""" return self._qubit_list_sizes @property def nqubits(self): """Return the number of qubits. See also MeasurementFilter.apply()""" return sum(self._qubit_list_sizes) def apply(self, raw_data, method="least_squares"): """ Apply the calibration matrices to results. Args: raw_data (dict or Result): The data to be corrected. Can be in one of two forms: * A counts dictionary from results.get_counts * A Qiskit Result method (str): fitting method. The following methods are supported: * 'pseudo_inverse': direct inversion of the cal matrices. * 'least_squares': constrained to have physical probabilities. * If `None`, 'least_squares' is used. Returns: dict or Result: The corrected data in the same form as raw_data Raises: QiskitError: if raw_data is not in a one of the defined forms. """ all_states = count_keys(self.nqubits) num_of_states = 2**self.nqubits # check forms of raw_data if isinstance(raw_data, dict): # counts dictionary # convert to list raw_data2 = [np.zeros(num_of_states, dtype=float)] for state, count in raw_data.items(): stateidx = int(state, 2) raw_data2[0][stateidx] = count elif isinstance(raw_data, qiskit.result.result.Result): # extract out all the counts, re-call the function with the # counts and push back into the new result new_result = deepcopy(raw_data) new_counts_list = parallel_map( self._apply_correction, [resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method), ) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts return new_result else: raise QiskitError("Unrecognized type for raw_data.") if method == "pseudo_inverse": pinv_cal_matrices = [] for cal_mat in self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat)) # Apply the correction for data_idx, _ in enumerate(raw_data2): if method == "pseudo_inverse": inv_mat_dot_raw = np.zeros([num_of_states], dtype=float) for state1_idx, state1 in enumerate(all_states): for state2_idx, state2 in enumerate(all_states): if raw_data2[data_idx][state2_idx] == 0: continue product = 1.0 end_index = self.nqubits for p_ind, pinv_mat in enumerate(pinv_cal_matrices): start_index = end_index - self._qubit_list_sizes[p_ind] state1_as_int = self._indices_list[p_ind][ state1[start_index:end_index] ] state2_as_int = self._indices_list[p_ind][ state2[start_index:end_index] ] end_index = start_index product *= pinv_mat[state1_as_int][state2_as_int] if product == 0: break inv_mat_dot_raw[state1_idx] += ( product * raw_data2[data_idx][state2_idx] ) raw_data2[data_idx] = inv_mat_dot_raw elif method == "least_squares": def fun(x): mat_dot_x = np.zeros([num_of_states], dtype=float) for state1_idx, state1 in enumerate(all_states): mat_dot_x[state1_idx] = 0.0 for state2_idx, state2 in enumerate(all_states): if x[state2_idx] != 0: product = 1.0 end_index = self.nqubits for c_ind, cal_mat in enumerate(self._cal_matrices): start_index = ( end_index - self._qubit_list_sizes[c_ind] ) state1_as_int = self._indices_list[c_ind][ state1[start_index:end_index] ] state2_as_int = self._indices_list[c_ind][ state2[start_index:end_index] ] end_index = start_index product *= cal_mat[state1_as_int][state2_as_int] if product == 0: break mat_dot_x[state1_idx] += product * x[state2_idx] return sum((raw_data2[data_idx] - mat_dot_x) ** 2) x0 = np.random.rand(num_of_states) x0 = x0 / sum(x0) nshots = sum(raw_data2[data_idx]) cons = {"type": "eq", "fun": lambda x: nshots - sum(x)} bnds = tuple((0, nshots) for x in x0) res = minimize( fun, x0, method="SLSQP", constraints=cons, bounds=bnds, tol=1e-6 ) raw_data2[data_idx] = res.x else: raise QiskitError("Unrecognized method.") # convert back into a counts dictionary new_count_dict = {} for state_idx, state in enumerate(all_states): if raw_data2[0][state_idx] != 0: new_count_dict[state] = raw_data2[0][state_idx] return new_count_dict def _apply_correction(self, resultidx, raw_data, method): """Wrapper to call apply with a counts dictionary.""" new_counts = self.apply(raw_data.get_counts(resultidx), method=method) return resultidx, new_counts
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from crypto.six_state.participant import Participant from qiskit import QuantumCircuit ## The Sender entity in the Six-State implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Sender(Participant): ## Constructor def __init__(self, name='', original_bits_size=0): super().__init__(name, original_bits_size) ## Encode the message (values) using a quantum circuit def encode_quantum_message(self): encoded_message = [] for i in range(len(self.axes)): qc = QuantumCircuit(1, 1) if self.values[i] == 1: qc.x(0) if self.axes[i] == 1: qc.h(0) elif self.axes[i] == 2: qc.append(self.hy, [0]) encoded_message.append(qc) return encoded_message
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ from qiskit import QuantumCircuit, Aer, execute from qiskit.tools.visualization import plot_histogram from IPython.core.display import display from math import pi # Function that returns the state vector (Psi) for the circuit def get_psi(circuit, title): show_bloch=True if show_bloch: from qiskit.visualization import plot_bloch_multivector backend = Aer.get_backend('statevector_simulator') result = execute(circuit, backend).result() psi = result.get_statevector(circuit) print(title) display(qc.draw('mpl')) display(plot_bloch_multivector(psi)) print("Ch 4: More Cheating quantum coin toss") print("-------------------------------------") qc = QuantumCircuit(1, 1) get_psi(qc, title='Qubit in ground state |0>') qc.h(0) get_psi(qc, title='Qubit in super position') qc.ry(pi/8,0) get_psi(qc, title='Qubit pi/8 radians closer to |1>') qc.measure(0, 0) display(qc.draw('mpl')) backend = Aer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1000).result().get_counts(qc) display(plot_histogram(counts))
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) ### added x gate ### qc.x(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### added z gate ### qc.z(1) qc.h(1) return qc
https://github.com/quantumyatra/quantum_computing
quantumyatra
# Useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') q = QuantumRegister(1) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(1) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q) qc.u3(pi/2,pi/2,pi/2,q) qc.draw(output='mpl') job = execute(qc, backend) job.result().get_unitary(qc, decimals=3)
https://github.com/MAI-cyber/QIT
MAI-cyber
# ! pip install numpy # ! pip install qiskit # ! pip install matplotlib from qiskit import QuantumCircuit, Aer ,BasicAer, execute, transpile from qiskit.visualization import plot_bloch_multivector, plot_histogram, plot_state_qsphere from qiskit.quantum_info import Statevector, partial_trace, state_fidelity import matplotlib.pyplot as plt import numpy as np from pprint import pprint from qiskit.providers.aer.noise import NoiseModel, amplitude_damping_error alice_state = Statevector.from_label("+") teleportation_circuit = QuantumCircuit(3, 1) # Making the state alice wants to communicate teleportation_circuit.h(0) teleportation_circuit.barrier() # Entanger circuit teleportation_circuit.h(1) teleportation_circuit.cx(1,2) teleportation_circuit.barrier() # Dis-Entanger circuit teleportation_circuit.cx(0,1) teleportation_circuit.h(0) teleportation_circuit.barrier() # Controlled not gates based on Alice's Results teleportation_circuit.cx(1,2) teleportation_circuit.cz(0,2) teleportation_circuit.barrier() #teleportation_circuit.measure(2,0) teleportation_circuit.snapshot("final", snapshot_type='statevector', qubits=[2]) teleportation_circuit.draw('mpl') from qiskit.providers.aer.noise import NoiseModel, noise_model from qiskit.providers.aer.noise.errors import pauli_error def noisy_simulator(p): noise_model = NoiseModel() # Using the Bit-flip noise channel error_meas = pauli_error([('X',p), ('I', 1 - p)]) noise_model.add_all_qubit_quantum_error(error_meas, "measure") return noise_model # Initlaizing the quantum simulator and decomposing the circuit interms of the basic gates simulator =Aer.get_backend('qasm_simulator') basis_gates = ['rz', 'sx', 'x', 'id' ,"cx"] quantum_circ = transpile(teleportation_circuit, basis_gates=basis_gates) # Making list of noise (probability of failure) under whichwe want to teleport the state # Making a list of fidelity to store the accuracy of our teleportations p_noise = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6] fidelity = [] for p in p_noise: #Simualting the circuit for each value of noise noisy_results = execute(quantum_circ, backend=simulator, shots=10000, noise_model=noisy_simulator(p)).result() # get the state of of the circuit after teleportations circuit has been traversed state = noisy_results.data(0)['snapshots']['statevector']['final'] # encode this state as a statevector state_ac = Statevector(state[0], dims=(2, 2, 2)) # take a partial trace to get the reduced matric rho bob has bob_state = partial_trace(state_ac, [0,1]).to_statevector() # find fidelity of state alice was to communicate and bob has recieved fidelity.append(state_fidelity(alice_state, bob_state)) plt.plot(p_noise, fidelity, 'o-') plt.ylabel("Fidelity") plt.xlabel("Noise (p)")
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate from qiskit.visualization import plot_histogram, plot_bloch_multivector circ = QuantumCircuit(2, 1) circ.reset([0, 1]) circ.x(0) circ.barrier() circ.h([0, 1]) circ.barrier() circ.append(Gate(name="$U_f$", num_qubits=2, params=[]), [0, 1]) circ.barrier() circ.h(1) circ.barrier() circ.measure(1, 0) circ.draw('mpl', reverse_bits=True) # Implementation of f1(x) f1 = QuantumCircuit(2, name='f1') f1.id(0) f1.draw('mpl', reverse_bits=True) # Implementation of f2(x) f2 = QuantumCircuit(2, name='f2') f2.cx(1, 0) f2.id(0) f2.draw('mpl', reverse_bits=True) # Implementation of f3(x) f3 = QuantumCircuit(2, name='f3') f3.cx(1, 0) f3.x(0) f3.draw('mpl', reverse_bits=True) # Implementation of f4(x) f4 = QuantumCircuit(2, name='f4') f4.x(0) f4.draw('mpl', reverse_bits=True) circ = QuantumCircuit(2) circ.x(0) circ.barrier() circ.h([0, 1]) circ.append(f4.to_instruction(), [0, 1]) circ.h(1) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() state = result.get_statevector(circ) plot_bloch_multivector(state) circ = QuantumCircuit(2) circ.x(0) circ.barrier() circ.h([0, 1]) circ.append(f2.to_instruction(), [0, 1]) circ.h(1) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() state = result.get_statevector(circ) plot_bloch_multivector(state) circ = QuantumCircuit(2, 1) circ.x(0) circ.barrier() circ.h([0, 1]) circ.append(f2.to_instruction(), [0, 1]) circ.h(1) circ.measure(1, 0) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=1000).result() counts = result.get_counts(circ) plot_histogram(counts)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test RemoveFinalMeasurements pass""" import unittest from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.circuit.classicalregister import Clbit from qiskit.transpiler.passes import RemoveFinalMeasurements from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestRemoveFinalMeasurements(QiskitTestCase): """Test removing final measurements.""" def test_multi_bit_register_removed_with_clbits(self): """Remove register when all clbits removed.""" def expected_dag(): q0 = QuantumRegister(2, "q0") qc = QuantumCircuit(q0) return circuit_to_dag(qc) q0 = QuantumRegister(2, "q0") c0 = ClassicalRegister(2, "c0") qc = QuantumCircuit(q0, c0) # measure into all clbits of c0 qc.measure(0, 0) qc.measure(1, 1) dag = circuit_to_dag(qc) dag = RemoveFinalMeasurements().run(dag) self.assertFalse(dag.cregs) self.assertFalse(dag.clbits) self.assertEqual(dag, expected_dag()) def test_register_kept_if_measured_clbit_busy(self): """ A register is kept if the measure destination bit is still busy after measure removal. """ def expected_dag(): q0 = QuantumRegister(1, "q0") c0 = ClassicalRegister(1, "c0") qc = QuantumCircuit(q0, c0) qc.x(0).c_if(c0[0], 0) return circuit_to_dag(qc) q0 = QuantumRegister(1, "q0") c0 = ClassicalRegister(1, "c0") qc = QuantumCircuit(q0, c0) # make c0 busy qc.x(0).c_if(c0[0], 0) # measure into c0 qc.measure(0, c0[0]) dag = circuit_to_dag(qc) dag = RemoveFinalMeasurements().run(dag) self.assertListEqual(list(dag.cregs.values()), [c0]) self.assertListEqual(dag.clbits, list(c0)) self.assertEqual(dag, expected_dag()) def test_multi_bit_register_kept_if_not_measured_clbit_busy(self): """ A multi-bit register is kept if it contains a busy bit even if the measure destination bit itself is idle. """ def expected_dag(): q0 = QuantumRegister(1, "q0") c0 = ClassicalRegister(2, "c0") qc = QuantumCircuit(q0, c0) qc.x(q0[0]).c_if(c0[0], 0) return circuit_to_dag(qc) q0 = QuantumRegister(1, "q0") c0 = ClassicalRegister(2, "c0") qc = QuantumCircuit(q0, c0) # make c0[0] busy qc.x(q0[0]).c_if(c0[0], 0) # measure into not busy c0[1] qc.measure(0, c0[1]) dag = circuit_to_dag(qc) dag = RemoveFinalMeasurements().run(dag) # c0 should not be removed because it has busy bit c0[0] self.assertListEqual(list(dag.cregs.values()), [c0]) # note: c0[1] should not be removed even though it is now idle # because it is referenced by creg c0. self.assertListEqual(dag.clbits, list(c0)) self.assertEqual(dag, expected_dag()) def test_overlapping_register_removal(self): """Only registers that become idle directly as a result of final op removal are removed. In this test, a 5-bit creg is implicitly created with its own bits, along with cregs ``c0_lower_3`` and ``c0_upper_3`` which reuse those underlying bits. ``c0_lower_3`` and ``c0_upper_3`` reference only 1 bit in common. A final measure is performed into a bit that exists in ``c0_lower_3`` but not in ``c0_upper_3``, and subsequently is removed. Consequently, both ``c0_lower_3`` and the 5-bit register are removed, because they have become unused as a result of the final measure removal. ``c0_upper_3`` remains, because it was idle beforehand, not as a result of the measure removal, along with all of its bits, including the bit shared with ``c0_lower_3``.""" def expected_dag(): q0 = QuantumRegister(3, "q0") c0 = ClassicalRegister(5, "c0") c0_upper_3 = ClassicalRegister(name="c0_upper_3", bits=c0[2:]) # note c0 is *not* added to circuit! qc = QuantumCircuit(q0, c0_upper_3) return circuit_to_dag(qc) q0 = QuantumRegister(3, "q0") c0 = ClassicalRegister(5, "c0") qc = QuantumCircuit(q0, c0) c0_lower_3 = ClassicalRegister(name="c0_lower_3", bits=c0[:3]) c0_upper_3 = ClassicalRegister(name="c0_upper_3", bits=c0[2:]) # Only qc.clbits[2] is shared between the two. qc.add_register(c0_lower_3) qc.add_register(c0_upper_3) qc.measure(0, c0_lower_3[0]) dag = circuit_to_dag(qc) dag = RemoveFinalMeasurements().run(dag) self.assertListEqual(list(dag.cregs.values()), [c0_upper_3]) self.assertListEqual(dag.clbits, list(c0_upper_3)) self.assertEqual(dag, expected_dag()) def test_multi_bit_register_removed_if_all_bits_idle(self): """A multibit register is removed when all bits are idle.""" def expected_dag(): q0 = QuantumRegister(1, "q0") qc = QuantumCircuit(q0) return circuit_to_dag(qc) q0 = QuantumRegister(1, "q0") c0 = ClassicalRegister(2, "c0") qc = QuantumCircuit(q0, c0) # measure into single bit c0[0] of c0 qc.measure(0, 0) dag = circuit_to_dag(qc) dag = RemoveFinalMeasurements().run(dag) self.assertFalse(dag.cregs) self.assertFalse(dag.clbits) self.assertEqual(dag, expected_dag()) def test_multi_reg_shared_bits_removed(self): """All registers sharing removed bits should be removed.""" def expected_dag(): q0 = QuantumRegister(2, "q0") qc = QuantumCircuit(q0) return circuit_to_dag(qc) q0 = QuantumRegister(2, "q0") c0 = ClassicalRegister(2, "c0") qc = QuantumCircuit(q0, c0) # Create reg with shared bits (same as c0) c1 = ClassicalRegister(name="c1", bits=qc.clbits) qc.add_register(c1) # measure into all clbits of c0 qc.measure(0, c0[0]) qc.measure(1, c0[1]) dag = circuit_to_dag(qc) dag = RemoveFinalMeasurements().run(dag) self.assertFalse(dag.cregs) self.assertFalse(dag.clbits) self.assertEqual(dag, expected_dag()) def test_final_measures_share_dest(self): """Multiple final measurements use the same clbit.""" def expected_dag(): qc = QuantumCircuit(QuantumRegister(2, "q0")) return circuit_to_dag(qc) rq = QuantumRegister(2, "q0") rc = ClassicalRegister(1, "c0") qc = QuantumCircuit(rq, rc) qc.measure(0, 0) qc.measure(1, 0) dag = circuit_to_dag(qc) dag = RemoveFinalMeasurements().run(dag) self.assertEqual(dag, expected_dag()) def test_remove_chained_final_measurements(self): """Remove successive final measurements.""" def expected_dag(): q0 = QuantumRegister(1, "q0") q1 = QuantumRegister(1, "q1") c0 = ClassicalRegister(1, "c0") qc = QuantumCircuit(q0, c0, q1) qc.measure(q0, c0) qc.measure(q0, c0) qc.barrier() qc.h(q1) return circuit_to_dag(qc) q0 = QuantumRegister(1, "q0") q1 = QuantumRegister(1, "q1") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") qc = QuantumCircuit(q0, c0, q1, c1) qc.measure(q0, c0) qc.measure(q0, c0) qc.barrier() qc.h(q1) qc.measure(q1, c1) qc.measure(q0, c1) dag = circuit_to_dag(qc) dag = RemoveFinalMeasurements().run(dag) self.assertEqual(dag, expected_dag()) def test_remove_clbits_without_register(self): """clbits of final measurements not in a register are removed.""" def expected_dag(): q0 = QuantumRegister(1, "q0") qc = QuantumCircuit(q0) return circuit_to_dag(qc) q0 = QuantumRegister(1, "q0") qc = QuantumCircuit(q0) # Add clbit without adding register qc.add_bits([Clbit()]) self.assertFalse(qc.cregs) # Measure to regless clbit qc.measure(0, 0) dag = circuit_to_dag(qc) dag = RemoveFinalMeasurements().run(dag) self.assertFalse(dag.cregs) self.assertFalse(dag.clbits) self.assertEqual(dag, expected_dag()) def test_final_barriers_and_measures_complex(self): """Test complex final barrier and measure removal.""" def expected_dag(): q0 = QuantumRegister(5, "q0") c1 = ClassicalRegister(1, "c1") qc = QuantumCircuit(q0, c1) qc.h(q0[0]) return circuit_to_dag(qc) # ┌───┐┌─┐ ░ ░ ┌─┐ # q0_0: ┤ H ├┤M├─░─────░─┤M├─────────────── # └┬─┬┘└╥┘ ░ ░ └╥┘┌─┐ # q0_1: ─┤M├──╫──░─────░──╫─┤M├──────────── # └╥┘ ║ ░ ░ ░ ║ └╥┘┌─┐ # q0_2: ──╫───╫──░──░──░──╫──╫─┤M├───────── # ║ ║ ░ ░ ░ ║ ║ └╥┘┌─┐ # q0_3: ──╫───╫──░──░──░──╫──╫──╫─┤M├────── # ║ ║ ░ ░ ░ ║ ║ ║ └╥┘┌─┐ ░ # q0_4: ──╫───╫──░─────░──╫──╫──╫──╫─┤M├─░─ # ║ ║ ░ ░ ║ ║ ║ ║ └╥┘ ░ # c0: 1/══╩═══╩═══════════╬══╬══╬══╬══╬════ # 0 0 ║ ║ ║ ║ ║ # ║ ║ ║ ║ ║ # c1: 1/══════════════════╬══╬══╬══╬══╬════ # ║ ║ ║ ║ ║ # meas: 5/════════════════╩══╩══╩══╩══╩════ # 0 1 2 3 4 q0 = QuantumRegister(5, "q0") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") qc = QuantumCircuit(q0, c0, c1) qc.measure(q0[1], c0) qc.h(q0[0]) qc.measure(q0[0], c0[0]) qc.barrier() qc.barrier(q0[2], q0[3]) qc.measure_all() qc.barrier(q0[4]) dag = circuit_to_dag(qc) dag = RemoveFinalMeasurements().run(dag) self.assertEqual(dag, expected_dag()) if __name__ == "__main__": unittest.main()
https://github.com/zapatacomputing/qe-qiskit
zapatacomputing
################################################################################ # © Copyright 2021-2022 Zapata Computing Inc. ################################################################################ import numpy as np import pytest import qiskit import qiskit.circuit.random import sympy from orquestra.quantum.circuits import ( _builtin_gates, _circuit, _gates, _wavefunction_operations, ) from orquestra.integrations.qiskit.conversions import ( export_to_qiskit, import_from_qiskit, ) # --------- gates --------- EQUIVALENT_NON_PARAMETRIC_GATES = [ (_builtin_gates.X, qiskit.circuit.library.XGate()), (_builtin_gates.Y, qiskit.circuit.library.YGate()), (_builtin_gates.Z, qiskit.circuit.library.ZGate()), (_builtin_gates.H, qiskit.circuit.library.HGate()), (_builtin_gates.I, qiskit.circuit.library.IGate()), (_builtin_gates.S, qiskit.circuit.library.SGate()), (_builtin_gates.SX, qiskit.circuit.library.SXGate()), (_builtin_gates.T, qiskit.circuit.library.TGate()), (_builtin_gates.CNOT, qiskit.circuit.library.CXGate()), (_builtin_gates.CZ, qiskit.circuit.library.CZGate()), (_builtin_gates.SWAP, qiskit.circuit.library.SwapGate()), (_builtin_gates.ISWAP, qiskit.circuit.library.iSwapGate()), (_builtin_gates.S.dagger, qiskit.circuit.library.SdgGate()), (_builtin_gates.T.dagger, qiskit.circuit.library.TdgGate()), ] EQUIVALENT_PARAMETRIC_GATES = [ (orquestra_cls(theta), qiskit_cls(theta)) for orquestra_cls, qiskit_cls in [ (_builtin_gates.RX, qiskit.circuit.library.RXGate), (_builtin_gates.RY, qiskit.circuit.library.RYGate), (_builtin_gates.RZ, qiskit.circuit.library.RZGate), (_builtin_gates.PHASE, qiskit.circuit.library.PhaseGate), (_builtin_gates.CPHASE, qiskit.circuit.library.CPhaseGate), (_builtin_gates.XX, qiskit.circuit.library.RXXGate), (_builtin_gates.YY, qiskit.circuit.library.RYYGate), (_builtin_gates.ZZ, qiskit.circuit.library.RZZGate), ] for theta in [0, -1, np.pi / 5, 2 * np.pi] ] TWO_QUBIT_SWAP_MATRIX = np.array( [ [1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1], ] ) def _fix_qubit_ordering(qiskit_matrix): """Import qiskit matrix to Orquestra matrix convention. Qiskit uses different qubit ordering than we do. It causes multi-qubit matrices to look different on first sight.""" if len(qiskit_matrix) == 2: return qiskit_matrix if len(qiskit_matrix) == 4: return TWO_QUBIT_SWAP_MATRIX @ qiskit_matrix @ TWO_QUBIT_SWAP_MATRIX else: raise ValueError(f"Unsupported matrix size: {len(qiskit_matrix)}") class TestGateConversion: @pytest.mark.parametrize( "orquestra_gate,qiskit_gate", [ *EQUIVALENT_NON_PARAMETRIC_GATES, *EQUIVALENT_PARAMETRIC_GATES, ], ) def test_matrices_are_equal(self, orquestra_gate, qiskit_gate): orquestra_matrix = np.array(orquestra_gate.matrix).astype(np.complex128) qiskit_matrix = _fix_qubit_ordering(qiskit_gate.to_matrix()) np.testing.assert_allclose(orquestra_matrix, qiskit_matrix) class TestU3GateConversion: @pytest.mark.parametrize( "theta, phi, lambda_", [ (0, 0, 0), (0, np.pi / 5, 0), (np.pi / 3, 0, 0), (0, 0, np.pi / 7), (42, -20, 30), ], ) def test_matrices_are_equal_up_to_phase_factor(self, theta, phi, lambda_): orquestra_matrix = np.array( _builtin_gates.U3(theta, phi, lambda_).matrix ).astype(np.complex128) qiskit_matrix = qiskit.circuit.library.U3Gate(theta, phi, lambda_).to_matrix() np.testing.assert_allclose(orquestra_matrix, qiskit_matrix, atol=1e-7) class TestCU3GateConversion: @pytest.mark.parametrize( "theta, phi, lambda_", [ (0, 0, 0), (0, np.pi / 5, 0), (np.pi / 3, 0, 0), (0, 0, np.pi / 7), (42, -20, 30), ], ) def test_matrices_are_equal_up_to_phase_factor(self, theta, phi, lambda_): orquestra_matrix = np.array( _builtin_gates.U3(theta, phi, lambda_).controlled(1)(0, 1).lifted_matrix(2) ).astype(np.complex128) qiskit_matrix = ( qiskit.circuit.library.U3Gate(theta, phi, lambda_).control(1).to_matrix() ) # Rearrange the qiskit matrix, such that it matches the endianness of orquestra qiskit_matrix_reversed_control = _fix_qubit_ordering(qiskit_matrix) np.testing.assert_allclose( orquestra_matrix, qiskit_matrix_reversed_control, atol=1e-7 ) # --------- circuits --------- # NOTE: In Qiskit, 0 is the most significant qubit, # whereas in Orquestra, 0 is the least significant qubit. # Thus, we need to flip the indices. # # See more at # https://qiskit.org/documentation/tutorials/circuits/1_getting_started_with_qiskit.html#Visualize-Circuit def _make_qiskit_circuit(n_qubits, commands, n_cbits=0): qc = qiskit.QuantumCircuit(n_qubits, n_cbits) for method_name, method_args in commands: method = getattr(qc, method_name) method(*method_args) return qc SYMPY_THETA = sympy.Symbol("theta") SYMPY_GAMMA = sympy.Symbol("gamma") SYMPY_LAMBDA = sympy.Symbol("lambda_") SYMPY_PARAMETER_VECTOR = [sympy.Symbol("p[0]"), sympy.Symbol("p[1]")] QISKIT_THETA = qiskit.circuit.Parameter("theta") QISKIT_GAMMA = qiskit.circuit.Parameter("gamma") QISKIT_LAMBDA = qiskit.circuit.Parameter("lambda_") QISKIT_PARAMETER_VECTOR = qiskit.circuit.ParameterVector("p", 2) EXAMPLE_PARAM_VALUES = { "gamma": 0.3, "theta": -5, "lambda_": np.pi / 5, "p[0]": -5, "p[1]": 0.3, } EQUIVALENT_NON_PARAMETRIZED_CIRCUITS = [ ( _circuit.Circuit([], 3), _make_qiskit_circuit(3, []), ), ( _circuit.Circuit( [ _builtin_gates.X(0), _builtin_gates.Z(2), ], 6, ), _make_qiskit_circuit( 6, [ ("x", (0,)), ("z", (2,)), ], ), ), ( _circuit.Circuit( [ _builtin_gates.T.dagger(0), ], 6, ), _make_qiskit_circuit( 6, [ ("tdg", (0,)), ], ), ), ( _circuit.Circuit( [ _wavefunction_operations.ResetOperation(0), ], 6, ), _make_qiskit_circuit( 6, [ ("reset", (0,)), ], ), ), ( _circuit.Circuit( [ _builtin_gates.X(0), _wavefunction_operations.ResetOperation(0), ], 6, ), _make_qiskit_circuit( 6, [ ("x", (0,)), ("reset", (0,)), ], ), ), ( _circuit.Circuit( [ _builtin_gates.CNOT(0, 1), ], 4, ), _make_qiskit_circuit( 4, [ ("cnot", (0, 1)), ], ), ), ( _circuit.Circuit( [ _builtin_gates.RX(np.pi)(1), ], 4, ), _make_qiskit_circuit( 4, [ ("rx", (np.pi, 1)), ], ), ), ( _circuit.Circuit( [_builtin_gates.SWAP.controlled(1)(2, 0, 3)], 5, ), _make_qiskit_circuit( 5, [ ("append", (qiskit.circuit.library.SwapGate().control(1), [2, 0, 3])), ], ), ), ( _circuit.Circuit( [_builtin_gates.Y.controlled(2)(4, 5, 2)], 6, ), _make_qiskit_circuit( 6, [ ("append", (qiskit.circuit.library.YGate().control(2), [4, 5, 2])), ], ), ), ( _circuit.Circuit([_builtin_gates.U3(np.pi / 5, np.pi / 2, np.pi / 4)(2)]), _make_qiskit_circuit( 3, [ ( "append", ( qiskit.circuit.library.U3Gate(np.pi / 5, np.pi / 2, np.pi / 4), [2], ), ) ], ), ), ( _circuit.Circuit( [_builtin_gates.U3(np.pi / 5, np.pi / 2, np.pi / 4).controlled(1)(1, 2)] ), _make_qiskit_circuit( 3, [ ( "append", ( qiskit.circuit.library.U3Gate( np.pi / 5, np.pi / 2, np.pi / 4 ).control(1), [1, 2], ), ) ], ), ), ( _circuit.Circuit([_builtin_gates.Delay(1)(0)]), _make_qiskit_circuit(1, [("delay", (1, 0))]), ), ] EQUIVALENT_PARAMETRIZED_CIRCUITS = [ ( _circuit.Circuit( [ _builtin_gates.RX(SYMPY_THETA)(1), ], 4, ), _make_qiskit_circuit( 4, [ ("rx", (QISKIT_THETA, 1)), ], ), ), ( _circuit.Circuit( [ _builtin_gates.RX(SYMPY_THETA * SYMPY_GAMMA)(1), ], 4, ), _make_qiskit_circuit( 4, [ ("rx", (QISKIT_THETA * QISKIT_GAMMA, 1)), ], ), ), ( _circuit.Circuit( [_builtin_gates.U3(SYMPY_THETA, SYMPY_GAMMA, SYMPY_LAMBDA)(3)] ), _make_qiskit_circuit( 4, [ ( "append", ( qiskit.circuit.library.U3Gate( QISKIT_THETA, QISKIT_GAMMA, QISKIT_LAMBDA ), [3], ), ) ], ), ), ( _circuit.Circuit( [ _builtin_gates.U3(SYMPY_THETA, SYMPY_GAMMA, SYMPY_LAMBDA).controlled(1)( 2, 3 ) ] ), _make_qiskit_circuit( 4, [ ( "append", ( qiskit.circuit.library.U3Gate( QISKIT_THETA, QISKIT_GAMMA, QISKIT_LAMBDA ).control(1), [2, 3], ), ) ], ), ), ( _circuit.Circuit( [ _builtin_gates.RX( SYMPY_PARAMETER_VECTOR[0] * SYMPY_PARAMETER_VECTOR[1] )(1), ], 4, ), _make_qiskit_circuit( 4, [ ("rx", (QISKIT_PARAMETER_VECTOR[0] * QISKIT_PARAMETER_VECTOR[1], 1)), ], ), ), ] UNITARY_GATE_DEF = _gates.CustomGateDefinition( "unitary.33c11b461fe67e717e37ac34a568cd1c27a89013703bf5b84194f0732a33a26d", sympy.Matrix([[0, 1], [1, 0]]), tuple(), ) CUSTOM_A2_GATE_DEF = _gates.CustomGateDefinition( "custom.A2.33c11b461fe67e717e37ac34a568cd1c27a89013703bf5b84194f0732a33a26d", sympy.Matrix([[0, 1], [1, 0]]), tuple(), ) EQUIVALENT_CUSTOM_GATE_CIRCUITS = [ ( _circuit.Circuit( operations=[UNITARY_GATE_DEF()(1)], n_qubits=4, ), _make_qiskit_circuit( 4, [ ("unitary", (np.array([[0, 1], [1, 0]]), 1)), ], ), ), ( _circuit.Circuit( operations=[CUSTOM_A2_GATE_DEF()(3)], n_qubits=5, ), _make_qiskit_circuit( 5, [ ("unitary", (np.array([[0, 1], [1, 0]]), 3, "custom.A2")), ], ), ), ( _circuit.Circuit( operations=[UNITARY_GATE_DEF()(1), UNITARY_GATE_DEF()(1)], n_qubits=4, ), _make_qiskit_circuit( 4, [ ("unitary", (np.array([[0, 1], [1, 0]]), 1)), ("unitary", (np.array([[0, 1], [1, 0]]), 1)), ], ), ), ( _circuit.Circuit( operations=[ UNITARY_GATE_DEF()(1), CUSTOM_A2_GATE_DEF()(1), UNITARY_GATE_DEF()(0), ], n_qubits=4, ), _make_qiskit_circuit( 4, [ ("unitary", (np.array([[0, 1], [1, 0]]), 1)), ("unitary", (np.array([[0, 1], [1, 0]]), 1, "custom.A2")), ("unitary", (np.array([[0, 1], [1, 0]]), 0)), ], ), ), ] UNSUPPORTED_CIRCUITS = [ _make_qiskit_circuit(1, [("measure", (0, 0))], n_cbits=1), _make_qiskit_circuit(1, [("break_loop", ())]), ] def _draw_qiskit_circuit(circuit): return qiskit.visualization.circuit_drawer(circuit, output="text") class TestExportingToQiskit: @pytest.mark.parametrize( "orquestra_circuit, qiskit_circuit", EQUIVALENT_NON_PARAMETRIZED_CIRCUITS ) def test_exporting_circuit_gives_equivalent_circuit( self, orquestra_circuit, qiskit_circuit ): converted = export_to_qiskit(orquestra_circuit) assert converted == qiskit_circuit, ( f"Converted circuit:\n{_draw_qiskit_circuit(converted)}\n isn't equal " f"to\n{_draw_qiskit_circuit(qiskit_circuit)}" ) @pytest.mark.parametrize( "orquestra_circuit", [ orquestra_circuit for orquestra_circuit, _ in EQUIVALENT_PARAMETRIZED_CIRCUITS ], ) def test_exporting_parametrized_circuit_doesnt_change_symbol_names( self, orquestra_circuit ): converted = export_to_qiskit(orquestra_circuit) converted_names = sorted(map(str, converted.parameters)) initial_names = sorted(map(str, orquestra_circuit.free_symbols)) assert converted_names == initial_names @pytest.mark.parametrize( "orquestra_circuit, qiskit_circuit", EQUIVALENT_PARAMETRIZED_CIRCUITS ) def test_exporting_and_binding_parametrized_circuit_results_in_equivalent_circuit( self, orquestra_circuit, qiskit_circuit ): # 1. Export converted = export_to_qiskit(orquestra_circuit) # 2. Bind params converted_bound = converted.bind_parameters( {param: EXAMPLE_PARAM_VALUES[str(param)] for param in converted.parameters} ) # 3. Bind the ref ref_bound = qiskit_circuit.bind_parameters( { param: EXAMPLE_PARAM_VALUES[str(param)] for param in qiskit_circuit.parameters } ) assert converted_bound == ref_bound, ( f"Converted circuit:\n{_draw_qiskit_circuit(converted_bound)}\n isn't " f"equal to\n{_draw_qiskit_circuit(ref_bound)}" ) @pytest.mark.parametrize( "orquestra_circuit, qiskit_circuit", EQUIVALENT_PARAMETRIZED_CIRCUITS ) def test_binding_and_exporting_parametrized_circuit_results_in_equivalent_circuit( self, orquestra_circuit, qiskit_circuit ): # 1. Bind params bound = orquestra_circuit.bind( { symbol: EXAMPLE_PARAM_VALUES[str(symbol)] for symbol in orquestra_circuit.free_symbols } ) # 2. Export bound_converted = export_to_qiskit(bound) # 3. Bind the ref ref_bound = qiskit_circuit.bind_parameters( { param: EXAMPLE_PARAM_VALUES[str(param)] for param in qiskit_circuit.parameters } ) assert bound_converted == ref_bound, ( f"Converted circuit:\n{_draw_qiskit_circuit(bound_converted)}\n isn't " f"equal to\n{_draw_qiskit_circuit(ref_bound)}" ) @pytest.mark.parametrize( "orquestra_circuit, qiskit_circuit", EQUIVALENT_CUSTOM_GATE_CIRCUITS ) def test_exporting_circuit_with_custom_gates_gives_equivalent_operator( self, orquestra_circuit, qiskit_circuit ): exported = export_to_qiskit(orquestra_circuit) # We can't compare the circuits directly, because the gate names can differ. # Qiskit allows multiple gate operations with the same label. Orquestra doesn't # allow that, so we append a matrix hash to the name. assert qiskit.quantum_info.Operator(exported) == qiskit.quantum_info.Operator( qiskit_circuit ) class TestImportingFromQiskit: @pytest.mark.parametrize( "orquestra_circuit, qiskit_circuit", EQUIVALENT_NON_PARAMETRIZED_CIRCUITS ) def test_importing_circuit_gives_equivalent_circuit( self, orquestra_circuit, qiskit_circuit ): imported = import_from_qiskit(qiskit_circuit) assert imported == orquestra_circuit @pytest.mark.parametrize( "qiskit_circuit", [q_circuit for _, q_circuit in EQUIVALENT_PARAMETRIZED_CIRCUITS], ) def test_importing_parametrized_circuit_doesnt_change_symbol_names( self, qiskit_circuit ): imported = import_from_qiskit(qiskit_circuit) assert sorted(map(str, imported.free_symbols)) == sorted( map(str, qiskit_circuit.parameters) ) @pytest.mark.parametrize( "orquestra_circuit, qiskit_circuit", EQUIVALENT_PARAMETRIZED_CIRCUITS ) def test_importing_and_binding_parametrized_circuit_results_in_equivalent_circuit( self, orquestra_circuit, qiskit_circuit ): # 1. Import imported = import_from_qiskit(qiskit_circuit) symbols_map = { symbol: EXAMPLE_PARAM_VALUES[str(symbol)] for symbol in imported.free_symbols } # 2. Bind params imported_bound = imported.bind(symbols_map) # 3. Bind the ref ref_bound = orquestra_circuit.bind(symbols_map) assert imported_bound == ref_bound @pytest.mark.parametrize( "orquestra_circuit, qiskit_circuit", EQUIVALENT_PARAMETRIZED_CIRCUITS ) def test_binding_and_importing_parametrized_circuit_results_in_equivalent_circuit( self, orquestra_circuit, qiskit_circuit ): # 1. Bind params bound = qiskit_circuit.bind_parameters( { param: EXAMPLE_PARAM_VALUES[str(param)] for param in qiskit_circuit.parameters } ) # 2. Import bound_imported = import_from_qiskit(bound) # 3. Bind the ref ref_bound = orquestra_circuit.bind( { symbol: EXAMPLE_PARAM_VALUES[str(symbol)] for symbol in orquestra_circuit.free_symbols } ) assert bound_imported == ref_bound @pytest.mark.parametrize( "orquestra_circuit, qiskit_circuit", EQUIVALENT_CUSTOM_GATE_CIRCUITS ) def test_importing_circuit_with_custom_gates_gives_equivalent_circuit( self, orquestra_circuit, qiskit_circuit ): imported = import_from_qiskit(qiskit_circuit) assert imported == orquestra_circuit @pytest.mark.parametrize("unsupported_circuit", UNSUPPORTED_CIRCUITS) def test_operation_not_implemented(self, unsupported_circuit): with pytest.raises(ValueError): import_from_qiskit(unsupported_circuit)
https://github.com/zapatacomputing/qe-qiskit
zapatacomputing
# -*- 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/quantastica/qiskit-forest
quantastica
import unittest import warnings from quantastica.qiskit_forest import ForestBackend from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer from qiskit.compiler import transpile, assemble from numpy import pi class TestForestBackend(unittest.TestCase): def setUp(self): """ Ignore following warning since it seems that there is nothing that we can do about it ResourceWarning: unclosed <socket.socket fd=9, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('127.0.0.1', 50494), raddr=('127.0.0.1', 5000)> """ warnings.filterwarnings(action="ignore", category=ResourceWarning) def tearDown(self): """ Restore warnings back """ warnings.filterwarnings(action="always", category=ResourceWarning) def test_bell_counts_with_seed(self): shots = 1024 qc=TestForestBackend.get_bell_qc() stats1 = TestForestBackend.execute_and_get_stats( ForestBackend.ForestBackend(), qc, shots, seed = 1 ) stats2 = TestForestBackend.execute_and_get_stats( ForestBackend.ForestBackend(), qc, shots, seed = 1 ) stats3 = TestForestBackend.execute_and_get_stats( ForestBackend.ForestBackend(), qc, shots, seed = 2 ) self.assertTrue( stats1['statevector'] is None) self.assertEqual( len(stats1['counts']), 2) self.assertEqual( stats1['totalcounts'], shots) self.assertEqual(stats1['counts'],stats2['counts']) self.assertNotEqual(stats1['counts'],stats3['counts']) def test_bell_counts(self): shots = 256 qc=TestForestBackend.get_bell_qc() stats = TestForestBackend.execute_and_get_stats( ForestBackend.ForestBackend(), qc, shots ) self.assertTrue( stats['statevector'] is None) self.assertEqual( len(stats['counts']), 2) self.assertEqual( stats['totalcounts'], shots) def test_bell_state_vector(self): """ This is test for statevector which means that even with shots > 1 it should execute only one shot """ shots = 256 qc = TestForestBackend.get_bell_qc() stats = TestForestBackend.execute_and_get_stats( ForestBackend.ForestBackend(lattice_name="statevector_simulator"), qc, shots ) self.assertEqual( len(stats['statevector']), 4) self.assertEqual( len(stats['counts']), 1) self.assertEqual( stats['totalcounts'], 1) def test_teleport_state_vector(self): """ This is test for statevector which means that even with shots > 1 it should execute only one shot """ shots = 256 qc = TestForestBackend.get_teleport_qc() """ Let's first run the aer simulation to get statevector and counts so we can compare those results against forest's """ stats_aer = TestForestBackend.execute_and_get_stats( Aer.get_backend('statevector_simulator'), qc, shots ) """ Now execute forest backend """ stats = TestForestBackend.execute_and_get_stats( ForestBackend.ForestBackend(lattice_name="statevector_simulator"), qc, shots ) self.assertEqual(len(stats['counts']), len(stats_aer['counts'])) self.assertEqual(len(stats['statevector']), len(stats_aer['statevector'])) self.assertEqual(stats['totalcounts'], stats_aer['totalcounts']) """ Let's verify that tests are working as expected by running fail case """ stats = TestForestBackend.execute_and_get_stats( ForestBackend.ForestBackend(), qc, shots ) self.assertNotEqual(len(stats['counts']), len(stats_aer['counts'])) self.assertTrue(stats['statevector'] is None) self.assertNotEqual(stats['totalcounts'], stats_aer['totalcounts']) def test_multiple_jobs(self): qc = self.get_bell_qc() backend = ForestBackend.ForestBackend() jobs = [] for i in range(1, 50): jobs.append(execute(qc, backend=backend, shots=1)) for job in jobs: result = job.result() counts = result.get_counts(qc) self.assertEqual(len(counts), 1) def test_multiple_experiments(self): backend = ForestBackend.ForestBackend() qc_list = [ self.get_bell_qc(), self.get_teleport_qc() ] transpiled = transpile(qc_list, backend = backend) qobjs = assemble(transpiled, backend=backend, shots=4096) job_info = backend.run(qobjs) bell_counts = job_info.result().get_counts("Bell") tel_counts = job_info.result().get_counts("Teleport") self.assertEqual(len(bell_counts),2) self.assertEqual(len(tel_counts),4) @staticmethod def execute_and_get_stats(backend, qc, shots, seed = None): job = execute(qc, backend=backend, shots=shots, seed_simulator = seed) job_result = job.result() counts = job_result.get_counts(qc) total_counts = 0 for c in counts: total_counts += counts[c] try: state_vector = job_result.get_statevector(qc) except: state_vector = None ret = dict() ret['counts'] = counts ret['statevector'] = state_vector ret['totalcounts'] = total_counts return ret @staticmethod def get_bell_qc(): qc = QuantumCircuit(name="Bell") q = QuantumRegister(2, 'q') c = ClassicalRegister(2, 'c') qc.add_register(q) qc.add_register(c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) return qc @staticmethod def get_teleport_qc(): qc = QuantumCircuit(name="Teleport") q = QuantumRegister(3, 'q') c0 = ClassicalRegister(1, 'c0') c1 = ClassicalRegister(1, 'c1') qc.add_register(q) qc.add_register(c0) qc.add_register(c1) qc.rx(pi / 4, q[0]) qc.h(q[1]) qc.cx(q[1], q[2]) qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[1], c1[0]) qc.x(q[2]).c_if(c1, 1) qc.measure(q[0], c0[0]) qc.z(q[2]).c_if(c0, 1) return qc if __name__ == '__main__': unittest.main()
https://github.com/usamisaori/qLipschitz
usamisaori
from sklearn import datasets import pennylane as qml import numpy as np from pennylane.optimize import AdamOptimizer import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') X_train, Y_train = datasets.make_circles(n_samples=200, noise=0.06, factor=0.6) X_test, Y_test = datasets.make_circles(n_samples=80, noise=0.06, factor=0.6) print('Training Data:') print(X_train[:10]) print('\nTraining Label:') print(Y_train[:10]) plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train) plt.show() print(f'Total datas: {len(X_train)}') print(f'labels: {list(set(Y_train))}') print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}') print(f'label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}') Z_train = (X_train[:, 0] ** 2 + X_train[:, 1] ** 2) ** 0.5 temp = np.zeros((X_train.shape[0], len(X_train[0]) + 1)) temp[:, :-1] = X_train temp[:, -1] = Z_train X_train2 = temp Z_test = (X_test[:, 0] ** 2 + X_test[:, 1] ** 2) ** 0.5 temp = np.zeros((X_test.shape[0], len(X_test[0]) + 1)) temp[:, :-1] = X_test temp[:, -1] = Z_test X_test2 = temp print('Solved Training Data:') print(X_train2[:10]) def plot3D(X, Y): fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') ax.scatter( X[:, 0], X[:, 1], X[:, 2], zdir='z', s=30, c=Y, depthshade=True ) plt.show() plot3D(X_train2, Y_train) print(f'Total datas: {len(X_train2)}') print(f'labels: {list(set(Y_train))}') print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}') print(f'label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}') qubits_num = 3 layers_num = 2 dev = qml.device("default.qubit", wires=qubits_num) @qml.qnode(dev) def circuit(params, data): angles = [ i * np.pi for i in data ] for i in range(qubits_num): qml.RX(angles[i], wires=i) qml.Rot( *params[0, i], wires=i ) qml.CZ(wires=[1, 0]) qml.CZ(wires=[1, 2]) qml.CZ(wires=[0, 2]) for i in range(qubits_num): qml.Rot( *params[1, i], wires=i ) # PauliZ measure => 1 -> |0> while -1 -> |1> return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2)) import qiskit from qiskit import QuantumCircuit from qiskit import Aer, execute unitary_backend = Aer.get_backend('unitary_simulator') qasm_backend = Aer.get_backend('qasm_simulator') def predict(params, data): qcircuit = QuantumCircuit(3, 3) qubits = qcircuit.qubits for i, d in enumerate(data): qcircuit.rx(d * np.pi, qubits[i]) for i in range(qubits_num): qcircuit.u3(*params[0][i], qubits[i]) qcircuit.cz(qubits[0], qubits[1]) qcircuit.cz(qubits[1], qubits[2]) qcircuit.cz(qubits[0], qubits[2]) for i in range(qubits_num): qcircuit.u3(*params[1][i], qubits[i]) # the measurement qcircuit.measure([0, 1, 2], [0, 1, 2]) # job execution shots = 1000 job_sim = execute(qcircuit, qasm_backend, shots=shots) result_sim = job_sim.result() counts = result_sim.get_counts(qcircuit) p1 = (counts.get('100', 0) + counts.get('111', 0) + counts.get('101', 0) + counts.get('110',0)) / shots if p1 > 0.5: return 1 else: return 0 def cost(weights, datas, labels): loss = 0 for i, data in enumerate(datas): # like [-1, 1, 1] measured = circuit(weights, data) p = measured[0] if labels[i] == 0: loss += (1 - p) ** 2 else: loss += (-1 - p) ** 2 return loss / len(datas) def accuracy(weights, datas, labels): predictions = [ predict(weights, data) for data in datas ] acc = 0 for i, p in enumerate(predictions): if p == labels[i]: acc += 1 return acc / len(predictions) class VQC: def __init__(self): # 3 => U3(theta, phi, lambda) self.params = (0.01 * np.random.randn(layers_num, qubits_num, 3)) self.bestparams = self.params self.bestcost = 10 self.weights = [] self.costs = [] self.accuracies = [] def fit(self, X_train, Y_train, *, epoch=300, stepsize=0.1): self.opt = AdamOptimizer(stepsize) batch_size = 30 for turn in range(epoch): # Update the weights by one optimizer step batch_index = np.random.randint(0, len(X_train), (batch_size,)) X_train_batch = X_train[batch_index] Y_train_batch = Y_train[batch_index] self.params = self.opt.step(lambda v: cost(v, X_train_batch, Y_train_batch), self.params) cost_now = cost(self.params, X_train, Y_train) acc_now = accuracy(self.params, X_train, Y_train) if cost_now < self.bestcost: self.bestcost = cost_now self.bestparams = self.params self.weights.append(self.params) self.costs.append(cost_now) self.accuracies.append(acc_now) print( "Turn: {:5d} | Cost: {:0.7f} | Accuracy: {:0.2f}% ".format( turn + 1, cost_now, acc_now * 100 )) def score(self, X_test, Y_test): predictions = [ predict(self.bestparams, data) for data in X_test ] acc = accuracy(self.bestparams, X_test, Y_test) print("FINAL ACCURACY: {:0.2f}%".format(acc * 100)) def train_params(datas, labels, *, epoch=30): alpha_grid = [0.001, 0.05, 0.1, 0.125, 0.25, 0.35, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3] # alpha_grid = [0.05, 0.15, 0.25, 0.5] # alpha_grid = [0.05, 0.075, 0.1, 0.125, 0.25, 0.5, 0.75, 1] alpha_best = None loss_best = 1000 batch_size = 30 for alpha in alpha_grid: print(f'alpha: {alpha}: ') vqc = VQC() vqc.fit(datas, labels, epoch=epoch, stepsize=alpha) loss = vqc.bestcost print(f' - finished. (loss {loss})\n') if loss < loss_best: loss_best = loss alpha_best = alpha return { 'alpha': alpha_best, 'loss': loss_best } train_params() vqc = VQC() vqc.fit(X_train2, Y_train, epoch=300, stepsize=)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.optimizers import SLSQP from qiskit.circuit.library import TwoLocal num_qubits = 2 ansatz = TwoLocal(num_qubits, "ry", "cz") optimizer = SLSQP(maxiter=1000) ansatz.decompose().draw("mpl", style="iqx") from qiskit.primitives import Estimator estimator = Estimator() from qiskit.algorithms.minimum_eigensolvers import VQE vqe = VQE(estimator, ansatz, optimizer) from qiskit.quantum_info import SparsePauliOp H2_op = SparsePauliOp.from_list([ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156) ]) result = vqe.compute_minimum_eigenvalue(H2_op) print(result) from qiskit.algorithms.optimizers import SPSA estimator = Estimator(options={"shots": 1000}) vqe.estimator = estimator vqe.optimizer = SPSA(maxiter=100) result = vqe.compute_minimum_eigenvalue(operator=H2_op) print(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from qiskit import * import numpy as np from numpy import linalg as la from qiskit.tools.monitor import job_monitor import qiskit.tools.jupyter qc = QuantumCircuit(1) #### your code goes here # z measurement of qubit 0 measure_z = QuantumCircuit(1,1) measure_z.measure(0,0) # x measurement of qubit 0 measure_x = QuantumCircuit(1,1) # your code goes here # y measurement of qubit 0 measure_y = QuantumCircuit(1,1) # your code goes here shots = 2**14 # number of samples used for statistics sim = Aer.get_backend('qasm_simulator') bloch_vector_measure = [] for measure_circuit in [measure_x, measure_y, measure_z]: # run the circuit with a the selected measurement and get the number of samples that output each bit value counts = execute(qc+measure_circuit, sim, shots=shots).result().get_counts() # calculate the probabilities for each bit value probs = {} for output in ['0','1']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 bloch_vector_measure.append( probs['0'] - probs['1'] ) # normalizing the bloch sphere vector bloch_vector = bloch_vector_measure/la.norm(bloch_vector_measure) print('The bloch sphere coordinates are [{0:4.3f}, {1:4.3f}, {2:4.3f}]' .format(*bloch_vector)) from kaleidoscope.interactive import bloch_sphere bloch_sphere(bloch_vector, vectors_annotation=True) from qiskit.visualization import plot_bloch_vector plot_bloch_vector( bloch_vector ) # circuit for the state Tri1 Tri1 = QuantumCircuit(2) # your code goes here # circuit for the state Tri2 Tri2 = QuantumCircuit(2) # your code goes here # circuit for the state Tri3 Tri3 = QuantumCircuit(2) # your code goes here # circuit for the state Sing Sing = QuantumCircuit(2) # your code goes here # <ZZ> measure_ZZ = QuantumCircuit(2) measure_ZZ.measure_all() # <XX> measure_XX = QuantumCircuit(2) # your code goes here # <YY> measure_YY = QuantumCircuit(2) # your code goes here shots = 2**14 # number of samples used for statistics A = 1.47e-6 #unit of A is eV E_sim = [] for state_init in [Tri1,Tri2,Tri3,Sing]: Energy_meas = [] for measure_circuit in [measure_XX, measure_YY, measure_ZZ]: # run the circuit with a the selected measurement and get the number of samples that output each bit value qc = state_init+measure_circuit counts = execute(qc, sim, shots=shots).result().get_counts() # calculate the probabilities for each computational basis probs = {} for output in ['00','01', '10', '11']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] ) E_sim.append(A * np.sum(np.array(Energy_meas))) # Run this cell to print out your results print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_sim[0])) print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_sim[1])) print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_sim[2])) print('Energy expection value of the state Sing : {:.3e} eV'.format(E_sim[3])) # reduced plank constant in (eV) and the speed of light(cgs units) hbar, c = 4.1357e-15, 3e10 # energy difference between the triplets and singlet E_del = abs(E_sim[0] - E_sim[3]) # frequency associated with the energy difference f = E_del/hbar # convert frequency to wavelength in (cm) wavelength = c/f print('The wavelength of the radiation from the transition\ in the hyperfine structure is : {:.1f} cm'.format(wavelength)) provider = IBMQ.load_account() backend = provider.get_backend('ibmq_athens') # run this cell to get the backend information through the widget backend # assign your choice for the initial layout to the list variable `initial_layout`. initial_layout = qc_all = [state_init+measure_circuit for state_init in [Tri1,Tri2,Tri3,Sing] for measure_circuit in [measure_XX, measure_YY, measure_ZZ] ] shots = 8192 job = execute(qc_all, backend, initial_layout=initial_layout, optimization_level=3, shots=shots) print(job.job_id()) job_monitor(job) # getting the results of your job results = job.result() ## To access the results of the completed job #results = backend.retrieve_job('job_id').result() def Energy(results, shots): """Compute the energy levels of the hydrogen ground state. Parameters: results (obj): results, results from executing the circuits for measuring a hamiltonian. shots (int): shots, number of shots used for the circuit execution. Returns: Energy (list): energy values of the four different hydrogen ground states """ E = [] A = 1.47e-6 for ind_state in range(4): Energy_meas = [] for ind_comp in range(3): counts = results.get_counts(ind_state*3+ind_comp) # calculate the probabilities for each computational basis probs = {} for output in ['00','01', '10', '11']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] ) E.append(A * np.sum(np.array(Energy_meas))) return E E = Energy(results, shots) print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E[0])) print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E[1])) print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E[2])) print('Energy expection value of the state Sing : {:.3e} eV'.format(E[3])) from qiskit.ignis.mitigation.measurement import * # your code to create the circuits, meas_calibs, goes here meas_calibs, state_labels = # execute meas_calibs on your choice of the backend job = execute(meas_calibs, backend, shots = shots) print(job.job_id()) job_monitor(job) cal_results = job.result() ## To access the results of the completed job #cal_results = backend.retrieve_job('job_id').result() # your code to obtain the measurement filter object, 'meas_filter', goes here results_new = meas_filter.apply(results) E_new = Energy(results_new, shots) print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_new[0])) print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_new[1])) print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_new[2])) print('Energy expection value of the state Sing : {:.3e} eV'.format(E_new[3])) # results for the energy estimation from the simulation, # execution on a quantum system without error mitigation and # with error mitigation in numpy array format Energy_exact, Energy_exp_orig, Energy_exp_new = np.array(E_sim), np.array(E), np.array(E_new) # Calculate the relative errors of the energy values without error mitigation # and assign to the numpy array variable `Err_rel_orig` of size 4 Err_rel_orig = # Calculate the relative errors of the energy values with error mitigation # and assign to the numpy array variable `Err_rel_new` of size 4 Err_rel_new = np.set_printoptions(precision=3) print('The relative errors of the energy values for four bell basis\ without measurement error mitigation : {}'.format(Err_rel_orig)) np.set_printoptions(precision=3) print('The relative errors of the energy values for four bell basis\ with measurement error mitigation : {}'.format(Err_rel_new))
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Determines a commutation library over the unparameterizable standard gates, i.e. a dictionary for each pair of parameterizable standard gates and all qubit overlaps that maps to either True or False, depending on the present commutation relation. """ import itertools from functools import lru_cache from typing import List from qiskit.circuit.commutation_checker import _get_relative_placement, _order_operations from qiskit.circuit import Gate, CommutationChecker import qiskit.circuit.library.standard_gates as stdg from qiskit.dagcircuit import DAGOpNode @lru_cache(None) def _get_unparameterizable_gates() -> List[Gate]: """Retrieve a list of non-parmaterized gates with up to 3 qubits, using the python inspection module Return: A list of non-parameterized gates to be considered in the commutation library """ # These two gates may require a large runtime in later processing steps # blocked_types = [C3SXGate, C4XGate] gates = list(stdg.get_standard_gate_name_mapping().values()) return [g for g in gates if len(g.params) == 0] def _generate_commutation_dict(considered_gates: List[Gate] = None) -> dict: """Compute the commutation relation of considered gates Args: considered_gates List[Gate]: a list of gates between which the commutation should be determined Return: A dictionary that includes the commutation relation for each considered pair of operations and each relative placement """ commutations = {} cc = CommutationChecker() for gate0 in considered_gates: node0 = DAGOpNode(op=gate0, qargs=list(range(gate0.num_qubits)), cargs=[]) for gate1 in considered_gates: # only consider canonical entries ( ( first_gate, _, _, ), (second_gate, _, _), ) = _order_operations(gate0, None, None, gate1, None, None) if (first_gate, second_gate) != (gate0, gate1) and gate0.name != gate1.name: continue # enumerate all relative gate placements with overlap between gate qubits gate_placements = itertools.permutations( range(gate0.num_qubits + gate1.num_qubits - 1), gate0.num_qubits ) gate_pair_commutation = {} for permutation in gate_placements: permutation_list = list(permutation) gate1_qargs = [] # use idx_non_overlapping qubits to represent qubits on g1 that are not connected to g0 next_non_overlapping_qubit_idx = gate0.num_qubits for i in range(gate1.num_qubits): if i in permutation_list: gate1_qargs.append(permutation_list.index(i)) else: gate1_qargs.append(next_non_overlapping_qubit_idx) next_non_overlapping_qubit_idx += 1 node1 = DAGOpNode(op=gate1, qargs=gate1_qargs, cargs=[]) # replace non-overlapping qubits with None to act as a key in the commutation library relative_placement = _get_relative_placement(node0.qargs, node1.qargs) if not gate0.is_parameterized() and not gate1.is_parameterized(): # if no gate includes parameters, compute commutation relation using # matrix multiplication op1 = node0.op qargs1 = node0.qargs cargs1 = node0.cargs op2 = node1.op qargs2 = node1.qargs cargs2 = node1.cargs commutation_relation = cc.commute( op1, qargs1, cargs1, op2, qargs2, cargs2, max_num_qubits=4 ) else: pass # TODO gate_pair_commutation[relative_placement] = commutation_relation commutations[gate0.name, gate1.name] = gate_pair_commutation return commutations def _simplify_commuting_dict(commuting_dict: dict) -> dict: """Compress some of the commutation library entries Args: commuting_dict (dict): A commutation dictionary Return: commuting_dict (dict): A commutation dictionary with simplified entries """ # Remove relative placement key if commutation is independent of relative placement for ops in commuting_dict.keys(): gates_commutations = set(commuting_dict[ops].values()) if len(gates_commutations) == 1: commuting_dict[ops] = next(iter(gates_commutations)) return commuting_dict def _dump_commuting_dict_as_python( commutations: dict, file_name: str = "../_standard_gates_commutations.py" ): """Write commutation dictionary as python object to ./qiskit/circuit/_standard_gates_commutations.py. Args: commutations (dict): a dictionary that includes the commutation relation for each considered pair of operations """ with open(file_name, "w") as fp: dir_str = "standard_gates_commutations = {\n" for k, v in commutations.items(): if not isinstance(v, dict): dir_str += ' ("{}", "{}"): {},\n'.format(*k, v) else: dir_str += ' ("{}", "{}"): {{\n'.format(*k) for entry_key, entry_val in v.items(): dir_str += " {}: {},\n".format(entry_key, entry_val) dir_str += " },\n" dir_str += "}\n" fp.write(dir_str.replace("'", "")) if __name__ == "__main__": cgates = [ g for g in _get_unparameterizable_gates() if g.name not in ["reset", "measure", "delay"] ] commutation_dict = _generate_commutation_dict(considered_gates=cgates) commutation_dict = _simplify_commuting_dict(commutation_dict) _dump_commuting_dict_as_python(commutation_dict)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_error_map from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() plot_error_map(backend)
https://github.com/Hayatto9217/Qiskit8
Hayatto9217
from qiskit import pulse with pulse.build(name='my_example') as my_program: pass my_program from qiskit.pulse import DriveChannel channel = DriveChannel(0) from qiskit.providers.fake_provider import FakeValencia backend = FakeValencia() with pulse.build(backend=backend, name='backend_aware') as backend_aware_program: channel = pulse.drive_channel(0) print(pulse.num_qubits()) with pulse.build(backend) as delay_5dt: pulse.delay(5, channel) #with pulse.build() as sched: #pulse.play(pulse, channel) from qiskit.pulse import library amp = 1 sigma = 10 num_samples = 128 gaus = pulse.library.Gaussian(num_samples, amp, sigma, name="Parametric Gaus") gaus.draw() import numpy as np times = np.arange(num_samples) gaussian_samples = np.exp(-1/2 *((times - num_samples / 2) ** 2 / sigma**2)) gaus = library.Waveform(gaussian_samples, name="WF Gaus") gaus.draw() gaus = library.gaussian(duration=num_samples, amp=amp, sigma=sigma, name="Lib Gaus") gaus.draw() with pulse.build() as schedule: pulse.play(gaus, channel) schedule.draw() with pulse.build() as schedule: pulse.play([0.001*i for i in range(160)], channel) schedule.draw() with pulse.build(backend) as schedule: pulse.set_frequency(4.5e9, channel) with pulse.build(backend) as schedule: pulse.shift_phase(np.pi, channel) from qiskit.pulse import Acquire, AcquireChannel, MemorySlot with pulse.build(backend) as schedule: pulse.acquire(1200, pulse.acquire_channel(0), MemorySlot(0)) with pulse.build(backend, name='Left align example') as program: with pulse.align_left(): gaussian_pulse = library.gaussian(100, 0.5, 20) pulse.play(gaussian_pulse, pulse.drive_channel(0)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) program.draw() # 上のパルスにはスケジューリングの自由度がないことに注意してください。2 番目の波形は最初の波形の直後に始まります。 with pulse.build(backend, name='example') as program: gaussian_pulse = library.gaussian(100, 0.5, 20) with pulse.align_equispaced(2*gaussian_pulse.duration): pulse.play(gaussian_pulse, pulse.drive_channel(0)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) program.draw() with pulse.build(backend, name='example') as program: with pulse.align_sequential(): gaussian_pulse = library.gaussian(100, 0.5, 20) pulse.play(gaussian_pulse, pulse.drive_channel(0)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) program.draw() with pulse.build(backend, name='Offset example') as program: with pulse.phase.offset(3.14, pulse.drive_channel(0)): pulse.play(gaussian_pulse, pulse.drive_channel(0)) with pulse.frequency_offset(10e6, pulse.drive_channel(0)): pulse.play(gaussian_pulse, pulse.drive_channel(0)) program.draw(9)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
import qiskit from qiskit import * import math import numpy as np def qc_ezz(t): qc = QuantumCircuit(2, name = 'e^(-itZZ)') qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1) return qc def qc_exx(t): qc = QuantumCircuit(2, name = 'e^(-itXX)') qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1]) return qc def qc_eyy(t): qc = QuantumCircuit(2, name = 'e^(-itYY)') qc.sdg([0,1]); qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1]); qc.s([0,1]) return qc def qc_Bj(t): qc = QuantumCircuit(3, name = 'B_j') qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t) qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2]) qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1]) return qc qc_Bj_ = qc_Bj(math.pi/2); qc_Bj_.draw(output='mpl') qc_Bj_.decompose().draw(output='mpl') nshots = 8192 IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') #provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main') device = provider.get_backend('ibmq_jakarta') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.tools.monitor import backend_overview, backend_monitor from qiskit.providers.aer import noise from qiskit.providers.aer.noise import NoiseModel from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter noise_model = NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates coupling_map = device.configuration().coupling_map ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity t = math.pi for j in range(0, 10): # Trotter stepsm_info. # quantum circuit qc = QuantumCircuit(7) qc.x([5, 3]) # prepares the initial state qc_Bj_ = qc_Bj(t/(j+1)) for k in range(0, j+1): qc.append(qc_Bj_, [5, 3, 1]) qstc = state_tomography_circuits(qc, [5, 3, 1]) # simulation job_sim = execute(qstc, backend = simulator, shots = nshots) qstf_sim = StateTomographyFitter(job_sim.result(), qstc) rho_sim = qstf_sim.fit(method = 'lstsq') F_sim = quantum_info.state_fidelity(psi0, rho_sim) # simulation with simulated noise job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) qstf_exp = StateTomographyFitter(job_exp.result(), qstc) rho_exp = qstf_exp.fit(method = 'lstsq') F_exp = quantum_info.state_fidelity(psi0, rho_exp) print('No. passos=', j+1, ',F_sim=', F_sim, ',F_exp=', F_exp) inha visto essa reprovação mas não me dei por conta que n# for error mitigation qr = QuantumRegister(7) qubit_list = [5,3,1] # the qubits on which we shall apply error mitigation meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job_cal = execute(meas_calibs, backend = simulator, shots = nshots, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) meas_fitter = CompleteMeasFitter(job_cal.result(), state_labels) ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1 psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity t = math.pi for j in range(0, 10): # Trotter steps # quantum circuit qc = QuantumCircuit(7) qc.x([5, 3]) # prepares the initial state qc_Bj_ = qc_Bj(t/(j+1)) for k in range(0, j+1): qc.append(qc_Bj_, [5, 3, 1]) qstc = state_tomography_circuits(qc, [5, 3, 1]) # simulation job_sim = execute(qstc, backend = simulator, shots = nshots) qstf_sim = StateTomographyFitter(job_sim.result(), qstc) rho_sim = qstf_sim.fit(method = 'lstsq') F_sim = quantum_info.state_fidelity(psi0, rho_sim) # simulation with simulated noise and error mitigation job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) mitigated_results = meas_fitter.filter.apply(job_exp.result()) qstf_exp = StateTomographyFitter(mitigated_results, qstc) rho_exp = qstf_exp.fit(method = 'lstsq') F_exp = quantum_info.state_fidelity(psi0, rho_exp) print('No. passos=', j+1, ',F_sim=', F_sim, ',F_exp=', F_exp) def qc_Bj_zz(t, th, ph): qc = QuantumCircuit(3, name = 'B_j_zz') qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t) qc.rz(2*th, [1,2]) qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2]) qc.rz(-2*th, [1,2]) qc.rz(2*ph, [0,1]) qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1]) qc.rz(-2*ph, [0,1]) return qc qc_Bj_zz_ = qc_Bj_zz(math.pi, math.pi/3, math.pi/4); qc_Bj_zz_.draw(output='mpl') ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1 psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity t = math.pi j = 6; print('N. of Trotter steps = ', j+1) th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0] ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0] for m in range(0, dim_th): for n in range(0, dim_ph): # quantum circuit qc = QuantumCircuit(7) qc.x([5, 3]) # prepares the initial state qc_Bj_zz_ = qc_Bj_zz(t/(j+1), th[m], ph[n]) for k in range(0, j+1): qc.append(qc_Bj_zz_, [5, 3, 1]) qstc = state_tomography_circuits(qc, [5, 3, 1]) # simulation job_sim = execute(qstc, backend = simulator, shots = nshots) qstf_sim = StateTomographyFitter(job_sim.result(), qstc) rho_sim = qstf_sim.fit(method = 'lstsq') F_sim = quantum_info.state_fidelity(psi0, rho_sim) # simulation with simulated noise and error mitigation job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) mitigated_results = meas_fitter.filter.apply(job_exp.result()) qstf_exp = StateTomographyFitter(mitigated_results, qstc) rho_exp = qstf_exp.fit(method = 'lstsq') F_exp = quantum_info.state_fidelity(psi0, rho_exp) print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp) def qc_Bj_zx(t, th, ph): qc = QuantumCircuit(3, name = 'B_j_zz') qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t) qc.rx(2*th, [1,2]) qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2]) qc.rx(-2*th, [1,2]) qc.rz(2*ph, [0,1]) qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1]) qc.rz(-2*ph, [0,1]) return qc qc_Bj_zx_ = qc_Bj_zx(math.pi, math.pi/3, math.pi/4); qc_Bj_zx_.draw(output='mpl') inha visto essa reprovação mas não me dei por conta que nket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1 psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity t = math.pi j = 6; print('N. of Trotter steps = ', j+1) th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0] ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0] for m in range(0, dim_th): for n in range(0, dim_ph): # quantum circuit qc = QuantumCircuit(7) qc.x([5, 3]) # prepares the initial state qc_Bj_zx_ = qc_Bj_zx(t/(j+1), th[m], ph[n]) for k in range(0, j+1): qc.append(qc_Bj_zx_, [5, 3, 1]) qstc = state_tomography_circuits(qc, [5, 3, 1]) # simulation job_sim = execute(qstc, backend = simulator, shots = nshots) qstf_sim = StateTomographyFitter(job_sim.result(), qstc) rho_sim = qstf_sim.fit(method = 'lstsq') F_sim = quantum_info.state_fidelity(psi0, rho_sim) # simulation with simulated noise and error mitigation job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) mitigated_results = meas_fitter.filter.apply(job_exp.result()) qstf_exp = StateTomographyFitter(mitigated_results, qstc) rho_exp = qstf_exp.fit(method = 'lstsq') F_exp = quantum_info.state_fidelity(psi0, rho_exp) print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp) def qc_Bj_yx(t, th, ph): qc = QuantumCircuit(3, name = 'B_j_zz') qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t) qc.rx(2*th, [1,2]) qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2]) qc.rx(-2*th, [1,2]) qc.barrier() qc.ry(2*ph, [0,1]) qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1]) qc.ry(-2*ph, [0,1]) return qc qc_Bj_yx_ = qc_Bj_yx(math.pi, math.pi/3, math.pi/4); qc_Bj_yx_.draw(output='mpl') https://arxiv.org/abs/2204.07816ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1 psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity t = math.pi j = 6; print('N. of Trotter steps = ', j+1) th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0] ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0] for m in range(0, dim_th): for n in range(0, dim_ph): # quantum circuit qc = QuantumCircuit(7) qc.x([5, 3]) # prepares the initial state qc_Bj_yx_ = qc_Bj_yx(t/(j+1), th[m], ph[n]) for k in range(0, j+1): qc.append(qc_Bj_yx_, [5, 3, 1]) qstc = state_tomography_circuits(qc, [5, 3, 1]) # simulation job_sim = execute(qstc, backend = simulator, shots = nshots) qstf_sim = StateTomographyFitter(job_sim.result(), qstc) rho_sim = qstf_sim.fit(method = 'lstsq') F_sim = quantum_info.state_fidelity(psi0, rho_sim) # simulation with simulated noise and error mitigation0.34 job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) mitigated_results = meas_fitter.filter.apply(job_exp.result()) qstf_exp = StateTomographyFitter(mitigated_results, qstc) rho_exp = qstf_exp.fit(method = 'lstsq') F_exp = quantum_info.state_fidelity(psi0, rho_exp) print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp) noise_model = NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates coupling_map = device.configuration().coupling_map basis_gates print(coupling_map) 553/3
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. # pylint: disable=unused-import """Test Qiskit's QuantumCircuit class.""" import os import tempfile import unittest import numpy as np import qiskit.extensions.simulator from qiskit import BasicAer from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit, Qubit, Clbit from qiskit import execute from qiskit import QiskitError from qiskit.quantum_info import state_fidelity from qiskit.test import QiskitTestCase class TestCircuitRegisters(QiskitTestCase): """QuantumCircuit Registers tests.""" def test_qregs(self): """Test getting quantum registers from circuit. """ qr1 = QuantumRegister(10, "q") self.assertEqual(qr1.name, "q") self.assertEqual(qr1.size, 10) self.assertEqual(type(qr1), QuantumRegister) def test_cregs(self): """Test getting quantum registers from circuit. """ cr1 = ClassicalRegister(10, "c") self.assertEqual(cr1.name, "c") self.assertEqual(cr1.size, 10) self.assertEqual(type(cr1), ClassicalRegister) def test_qarg_negative_size(self): """Test attempt to create a negative size QuantumRegister. """ self.assertRaises(qiskit.exceptions.QiskitError, QuantumRegister, -1) def test_qarg_string_size(self): """Test attempt to create a non-integer size QuantumRegister. """ self.assertRaises(qiskit.exceptions.QiskitError, QuantumRegister, 'string') def test_qarg_numpy_int_size(self): """Test castable to integer size QuantumRegister. """ np_int = np.dtype('int').type(10) qr1 = QuantumRegister(np_int, "q") self.assertEqual(qr1.name, "q") self.assertEqual(qr1.size, 10) self.assertEqual(type(qr1), QuantumRegister) def test_numpy_array_of_registers(self): """Test numpy array of Registers . See https://github.com/Qiskit/qiskit-terra/issues/1898 """ qrs = [QuantumRegister(2, name='q%s' % i) for i in range(5)] qreg_array = np.array([], dtype=object, ndmin=1) qreg_array = np.append(qreg_array, qrs) expected = [qrs[0][0], qrs[0][1], qrs[1][0], qrs[1][1], qrs[2][0], qrs[2][1], qrs[3][0], qrs[3][1], qrs[4][0], qrs[4][1]] self.assertEqual(len(qreg_array), 10) self.assertEqual(qreg_array.tolist(), expected) def test_negative_index(self): """Test indexing from the back """ qr1 = QuantumRegister(10, "q") cr1 = ClassicalRegister(10, "c") self.assertEqual(qr1[-1], qr1[9]) self.assertEqual(qr1[-3:-1], [qr1[7], qr1[8]]) self.assertEqual(len(cr1[0:-2]), 8) def test_reg_equal(self): """Test getting quantum registers from circuit. """ qr1 = QuantumRegister(1, "q") qr2 = QuantumRegister(2, "q") cr1 = ClassicalRegister(1, "q") self.assertEqual(qr1, qr1) self.assertNotEqual(qr1, qr2) self.assertNotEqual(qr1, cr1) def test_qubits(self): """Test qubits() method. """ qr1 = QuantumRegister(1, "q1") cr1 = ClassicalRegister(3, "c1") qr2 = QuantumRegister(2, "q2") qc = QuantumCircuit(qr2, cr1, qr1) qubtis = qc.qubits self.assertEqual(qubtis[0], qr2[0]) self.assertEqual(qubtis[1], qr2[1]) self.assertEqual(qubtis[2], qr1[0]) def test_clbits(self): """Test clbits() method. """ qr1 = QuantumRegister(1, "q1") cr1 = ClassicalRegister(2, "c1") qr2 = QuantumRegister(2, "q2") cr2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(qr2, cr2, qr1, cr1) clbtis = qc.clbits self.assertEqual(clbtis[0], cr2[0]) self.assertEqual(clbtis[1], cr1[0]) self.assertEqual(clbtis[2], cr1[1]) def test_qregs_circuit(self): """Test getting quantum registers from circuit. """ qr1 = QuantumRegister(1) qr2 = QuantumRegister(2) qc = QuantumCircuit(qr1, qr2) q_regs = qc.qregs self.assertEqual(len(q_regs), 2) self.assertEqual(q_regs[0], qr1) self.assertEqual(q_regs[1], qr2) def test_cregs_circuit(self): """Test getting classical registers from circuit. """ cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(2) cr3 = ClassicalRegister(3) qc = QuantumCircuit(cr1, cr2, cr3) c_regs = qc.cregs self.assertEqual(len(c_regs), 3) self.assertEqual(c_regs[0], cr1) self.assertEqual(c_regs[1], cr2) def test_basic_slice(self): """simple slice test""" qr = QuantumRegister(5) cr = ClassicalRegister(5) self.assertEqual(len(qr[0:3]), 3) self.assertEqual(len(cr[0:3]), 3) def test_apply_gate_to_slice(self): """test applying gate to register slice""" sli = slice(0, 9, 2) qr = QuantumRegister(10) cr = ClassicalRegister(10) qc = QuantumCircuit(qr, cr) qc.h(qr[0:9:2]) for i, index in enumerate(range(*sli.indices(sli.stop))): self.assertEqual(qc.data[i][1][0].index, index) def test_apply_barrier_to_slice(self): """test applying barrier to register slice""" n_qubits = 10 qr = QuantumRegister(n_qubits) cr = ClassicalRegister(n_qubits) qc = QuantumCircuit(qr, cr) qc.barrier(qr) # barrier works a little different than normal gates for expansion # test full register self.assertEqual(len(qc.data), 1) self.assertEqual(qc.data[0][0].name, 'barrier') self.assertEqual(len(qc.data[0][1]), n_qubits) for i, bit in enumerate(qc.data[0][1]): self.assertEqual(bit.index, i) # test slice n_qubits = 2 qc = QuantumCircuit(qr, cr) qc.barrier(qr[0:n_qubits]) self.log.info(qc.qasm()) self.assertEqual(len(qc.data), 1) self.assertEqual(qc.data[0][0].name, 'barrier') self.assertEqual(len(qc.data[0][1]), n_qubits) for i in range(n_qubits): self.assertEqual(qc.data[0][1][i].index, i) def test_apply_ccx_to_slice(self): """test applying ccx to register slice""" qcontrol = QuantumRegister(10) qcontrol2 = QuantumRegister(10) qtarget = QuantumRegister(5) qtarget2 = QuantumRegister(10) qc = QuantumCircuit(qcontrol, qtarget) # test slice with skip and full register target qc.ccx(qcontrol[1::2], qcontrol[0::2], qtarget) self.assertEqual(len(qc.data), 5) for i, ictl, (gate, qargs, _) in zip(range(len(qc.data)), range(0, 10, 2), qc.data): self.assertEqual(gate.name, 'ccx') self.assertEqual(len(qargs), 3) self.assertIn(qargs[0].index, [ictl, ictl + 1]) self.assertIn(qargs[1].index, [ictl, ictl + 1]) self.assertEqual(qargs[2].index, i) # test decrementing slice qc = QuantumCircuit(qcontrol, qtarget) qc.ccx(qcontrol[2:0:-1], qcontrol[4:6], qtarget[0:2]) self.assertEqual(len(qc.data), 2) for (gate, qargs, _), ictl1, ictl2, itgt in zip(qc.data, range(2, 0, -1), range(4, 6), range(0, 2)): self.assertEqual(gate.name, 'ccx') self.assertEqual(len(qargs), 3) self.assertEqual(qargs[0].index, ictl1) self.assertEqual(qargs[1].index, ictl2) self.assertEqual(qargs[2].index, itgt) # test register expansion in ccx qc = QuantumCircuit(qcontrol, qcontrol2, qtarget2) qc.ccx(qcontrol, qcontrol2, qtarget2) for i, (gate, qargs, _) in enumerate(qc.data): self.assertEqual(gate.name, 'ccx') self.assertEqual(len(qargs), 3) self.assertEqual(qargs[0].index, i) self.assertEqual(qargs[1].index, i) self.assertEqual(qargs[2].index, i) def test_cswap_on_slice(self): """test applying cswap to register slice""" qr1 = QuantumRegister(10) qr2 = QuantumRegister(5) qc = QuantumCircuit(qr1, qr2) qc.cswap(qr2[3::-1], qr1[1:9:2], qr1[2:9:2]) qc.cswap(qr2[0], qr1[1], qr1[2]) qc.cswap([qr2[0]], [qr1[1]], [qr1[2]]) self.assertRaises(qiskit.exceptions.QiskitError, qc.cswap, qr2[4::-1], qr1[1:9:2], qr1[2:9:2]) def test_apply_ccx_to_empty_slice(self): """test applying ccx to non-register raises""" qr = QuantumRegister(10) cr = ClassicalRegister(10) qc = QuantumCircuit(qr, cr) self.assertRaises(qiskit.exceptions.QiskitError, qc.ccx, qr[2:0], qr[4:2], qr[7:5]) def test_apply_cx_to_non_register(self): """test applying ccx to non-register raises""" qr = QuantumRegister(10) cr = ClassicalRegister(10) qc = QuantumCircuit(qr, cr) self.assertRaises(qiskit.exceptions.QiskitError, qc.cx, qc[0:2], qc[2:4]) def test_apply_ch_to_slice(self): """test applying ch to slice""" qr = QuantumRegister(10) cr = ClassicalRegister(10) # test slice qc = QuantumCircuit(qr, cr) ctl_slice = slice(0, 2) tgt_slice = slice(2, 4) qc.ch(qr[ctl_slice], qr[tgt_slice]) for (gate, qargs, _), ictrl, itgt in zip(qc.data, range(0, 2), range(2, 4)): self.assertEqual(gate.name, 'ch') self.assertEqual(len(qargs), 2) self.assertEqual(qargs[0].index, ictrl) self.assertEqual(qargs[1].index, itgt) # test single qubit args qc = QuantumCircuit(qr, cr) qc.ch(qr[0], qr[1]) self.assertEqual(len(qc.data), 1) op, qargs, _ = qc.data[0] self.assertEqual(op.name, 'ch') self.assertEqual(qargs[0].index, 0) self.assertEqual(qargs[1].index, 1) def test_measure_slice(self): """test measure slice""" qr = QuantumRegister(10) cr = ClassicalRegister(10) cr2 = ClassicalRegister(5) qc = QuantumCircuit(qr, cr) qc.measure(qr[0:2], cr[2:4]) for (gate, qargs, cargs), ictrl, itgt in zip(qc.data, range(0, 2), range(2, 4)): self.assertEqual(gate.name, 'measure') self.assertEqual(len(qargs), 1) self.assertEqual(len(cargs), 1) self.assertEqual(qargs[0].index, ictrl) self.assertEqual(cargs[0].index, itgt) # test single element slice qc = QuantumCircuit(qr, cr) qc.measure(qr[0:1], cr[2:3]) for (gate, qargs, cargs), ictrl, itgt in zip(qc.data, range(0, 1), range(2, 3)): self.assertEqual(gate.name, 'measure') self.assertEqual(len(qargs), 1) self.assertEqual(len(cargs), 1) self.assertEqual(qargs[0].index, ictrl) self.assertEqual(cargs[0].index, itgt) # test tuple qc = QuantumCircuit(qr, cr) qc.measure(qr[0], cr[2]) self.assertEqual(len(qc.data), 1) op, qargs, cargs = qc.data[0] self.assertEqual(op.name, 'measure') self.assertEqual(len(qargs), 1) self.assertEqual(len(cargs), 1) self.assertTrue(isinstance(qargs[0], Qubit)) self.assertTrue(isinstance(cargs[0], Clbit)) self.assertEqual(qargs[0].index, 0) self.assertEqual(cargs[0].index, 2) # test full register qc = QuantumCircuit(qr, cr) qc.measure(qr, cr) for (gate, qargs, cargs), ictrl, itgt in zip(qc.data, range(len(qr)), range(len(cr))): self.assertEqual(gate.name, 'measure') self.assertEqual(len(qargs), 1) self.assertEqual(len(cargs), 1) self.assertEqual(qargs[0].index, ictrl) self.assertEqual(cargs[0].index, itgt) # test mix slice full register qc = QuantumCircuit(qr, cr2) qc.measure(qr[::2], cr2) for (gate, qargs, cargs), ictrl, itgt in zip(qc.data, range(0, 10, 2), range(len(cr2))): self.assertEqual(gate.name, 'measure') self.assertEqual(len(qargs), 1) self.assertEqual(len(cargs), 1) self.assertEqual(qargs[0].index, ictrl) self.assertEqual(cargs[0].index, itgt) def test_measure_slice_raises(self): """test raising exception for strange measures""" qr = QuantumRegister(10) cr = ClassicalRegister(10) qc = QuantumCircuit(qr, cr) with self.assertRaises(QiskitError): qc.measure(qr[0:2], cr[2]) # this is ok qc.measure(qr[0], cr[0:2]) def test_list_indexing(self): """test list indexing""" qr = QuantumRegister(10) cr = QuantumRegister(10) qc = QuantumCircuit(qr, cr) ind = [0, 1, 8, 9] qc.h(qr[ind]) self.assertEqual(len(qc.data), len(ind)) for (gate, qargs, _), index in zip(qc.data, ind): self.assertEqual(gate.name, 'h') self.assertEqual(len(qargs), 1) self.assertEqual(qargs[0].index, index) qc = QuantumCircuit(qr, cr) ind = [0, 1, 8, 9] qc.cx(qr[ind], qr[2:6]) for (gate, qargs, _), ind1, ind2 in zip(qc.data, ind, range(2, 6)): self.assertEqual(gate.name, 'cx') self.assertEqual(len(qargs), 2) self.assertEqual(qargs[0].index, ind1) self.assertEqual(qargs[1].index, ind2) class TestCircuitBit(QiskitTestCase): """QuantumCircuit Registers tests.""" def test_bit_getitem(self): """ Deprecated Bit.__getitem__. """ qubit = QuantumRegister(1, "q")[0] with self.assertWarns(DeprecationWarning): self.assertEqual(qubit[0], qubit.register) self.assertEqual(qubit[1], qubit.index) def test_gate_with_tuples(self): """ Deprecated gate parameters as tuples""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) expected = QuantumCircuit(qr) expected.h(qr[0]) with self.assertWarns(DeprecationWarning): qc.h((qr, 0)) self.assertEqual(qc, expected) def test_gate_with_tuple_list(self): """ Deprecated gate parameters as tuple list""" qr = QuantumRegister(2) qc = QuantumCircuit(qr) expected = QuantumCircuit(qr) expected.h([qr[0], qr[1]]) with self.assertWarns(DeprecationWarning): qc.h([(qr, 0), (qr, 1)]) self.assertEqual(qc, expected)
https://github.com/carstenblank/dc-qiskit-qml
carstenblank
# -*- coding: utf-8 -*- # Copyright 2018 Carsten Blank # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r""" QmlSparseVectorStatePreparation ================================ .. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state.sparsevector._QmlSparseVectorStatePreparation This is the abstract base class that needs to be implemented for any routine that takes a sparse state vector and encodes it into a quantum circuit that produces this quantum state. .. autosummary:: :nosignatures: QmlSparseVectorStatePreparation QmlSparseVectorStatePreparation ################################# .. autoclass:: QmlSparseVectorStatePreparation :members: """ import abc from qiskit import QuantumCircuit from scipy import sparse class QmlSparseVectorStatePreparation(object): @abc.abstractmethod def prepare_state(self, qc, state_vector): # type: (QmlSparseVectorStatePreparation, QuantumCircuit, sparse.dok_matrix) -> QuantumCircuit """ Given a sparse quantum state apply a quantum algorithm (gates) to the given circuit to produce the desired quantum state. :param qc: the quantum circuit to be used :param state_vector: the (complex) state vector of unit length to be prepared :return: the quantum circuit """ pass @abc.abstractmethod def is_classifier_branch(self, branch_value): # type: (QmlSparseVectorStatePreparation, int) -> bool """ The state preparation logic is done in this class, therefore it knows what value the branch measurement must have in order to know if we can get classification numbers. :param branch_value: the branch measurement value :return: True if the branch measurement was 0 """ pass
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw()
https://github.com/yaelbh/qiskit-projectq-provider
yaelbh
# -*- coding: utf-8 -*- # Copyright 2017, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """Generate random circuits.""" import random import numpy from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister def choices(population, weights=None, k=1): """ Replacement for `random.choices()`, which is only available in Python 3.6+. TODO: drop once Python 3.6 is required by the sdk. """ if weights and sum(weights) != 1: # Normalize the weights if needed, as numpy.random.choice requires so. weights = [float(i)/sum(weights) for i in weights] return numpy.random.choice(population, size=k, p=weights) class RandomCircuitGenerator(object): """ Generate random size circuits for profiling. """ def __init__(self, seed=None, max_qubits=5, min_qubits=1, max_depth=100, min_depth=1): """ Args: seed (int): Random number seed. If none, don't seed the generator. max_qubits (int): Maximum number of qubits in a circuit. min_qubits (int): Minimum number of operations in a cirucit. max_depth (int): Maximum number of operations in a circuit. min_depth (int): Minimum number of operations in circuit. """ self.max_depth = max_depth self.max_qubits = max_qubits self.min_depth = min_depth self.min_qubits = min_qubits self.circuit_list = [] self.n_qubit_list = [] self.depth_list = [] self.basis_gates = None self.circuit_name_list = [] if seed is not None: random.seed(a=seed) # specify number of parameters and args for each op # in the standard extension. If type hints (PEP484) are followed # maybe we can guess this. "nregs" are the number of qubits the # operation uses. If nregs=0 then it means either 1 qubit or # 1 register. "nparams" are the number of parameters the operation takes. self.op_signature = { 'barrier': {'nregs': 0, 'nparams': None}, 'ccx': {'nregs': 3, 'nparams': None}, 'ch': {'nregs': 2, 'nparams': None}, 'crz': {'nregs': 2, 'nparams': 1}, 'cswap': {'nregs': 3, 'nparams': None}, 'cu1': {'nregs': 2, 'nparams': 1}, 'cu3': {'nregs': 2, 'nparams': 3}, 'cx': {'nregs': 2, 'nparams': None}, 'cy': {'nregs': 2, 'nparams': None}, 'cz': {'nregs': 2, 'nparams': None}, 'h': {'nregs': 1, 'nparams': None}, 'iden': {'nregs': 1, 'nparams': None}, 'measure': {'nregs': 0, 'nparams': None}, 'reset': {'nregs': 1, 'nparams': None}, 'rx': {'nregs': 1, 'nparams': 1}, 'ry': {'nregs': 1, 'nparams': 1}, 'rz': {'nregs': 1, 'nparams': 1}, 's': {'nregs': 1, 'nparams': None}, 't': {'nregs': 1, 'nparams': None}, 'u1': {'nregs': 1, 'nparams': 1}, 'u2': {'nregs': 1, 'nparams': 2}, 'u3': {'nregs': 1, 'nparams': 3}, 'x': {'nregs': 1, 'nparams': None}, 'y': {'nregs': 1, 'nparams': None}, 'z': {'nregs': 1, 'nparams': None}} def add_circuits(self, n_circuits, do_measure=True, basis=None, basis_weights=None): """Adds circuits to program. Generates a circuit with a random number of operations in `basis`. Also adds a random number of measurements in [1,nQubits] to end of circuit. Args: n_circuits (int): Number of circuits to add. do_measure (bool): Whether to add measurements. basis (list(str) or None): List of op names. If None, basis is randomly chosen with unique ops in (2,7) basis_weights (list(float) or None): List of weights corresponding to indices in `basis`. Raises: AttributeError: if operation is not recognized. """ if basis is None: basis = list(random.sample(self.op_signature.keys(), random.randint(2, 7))) basis_weights = [1./len(basis)] * len(basis) if basis_weights is not None: assert len(basis) == len(basis_weights) uop_basis = basis[:] if basis_weights: uop_basis_weights = basis_weights[:] else: uop_basis_weights = None # remove barrier from uop basis if it is specified if 'barrier' in uop_basis: ind = uop_basis.index('barrier') del uop_basis[ind] if uop_basis_weights: del uop_basis_weights[ind] # remove measure from uop basis if it is specified if 'measure' in uop_basis: ind = uop_basis.index('measure') del uop_basis[ind] if uop_basis_weights: del uop_basis_weights[ind] # self.basis_gates = uop_basis self.basis_gates = basis self.circuit_name_list = [] # TODO: replace choices with random.choices() when python 3.6 is # required. self.n_qubit_list = choices( range(self.min_qubits, self.max_qubits + 1), k=n_circuits) self.depth_list = choices( range(self.min_depth, self.max_depth + 1), k=n_circuits) for i_circuit in range(n_circuits): n_qubits = self.n_qubit_list[i_circuit] if self.min_regs_exceeds_nqubits(uop_basis, n_qubits): # no gate operation from this circuit can fit in the available # number of qubits. continue depth_cnt = self.depth_list[i_circuit] reg_pop = numpy.arange(1, n_qubits+1) register_weights = reg_pop[::-1].astype(float) register_weights /= register_weights.sum() max_registers = numpy.random.choice(reg_pop, p=register_weights) reg_weight = numpy.ones(max_registers) / float(max_registers) reg_sizes = rand_register_sizes(n_qubits, reg_weight) n_registers = len(reg_sizes) circuit = QuantumCircuit() for i_size, size in enumerate(reg_sizes): cr_name = 'cr' + str(i_size) qr_name = 'qr' + str(i_size) creg = ClassicalRegister(size, cr_name) qreg = QuantumRegister(size, qr_name) circuit.add_register(qreg, creg) while depth_cnt > 0: # TODO: replace choices with random.choices() when python 3.6 # is required. op_name = choices(basis, weights=basis_weights)[0] if hasattr(circuit, op_name): operator = getattr(circuit, op_name) else: raise AttributeError('operation \"{0}\"' ' not recognized'.format(op_name)) n_regs = self.op_signature[op_name]['nregs'] n_params = self.op_signature[op_name]['nparams'] if n_regs == 0: # this is a barrier or measure n_regs = random.randint(1, n_qubits) if n_qubits >= n_regs: # warning: assumes op function signature specifies # op parameters before qubits op_args = [] if n_params: op_args = [random.random() for _ in range(n_params)] if op_name == 'measure': # if measure occurs here, assume it's to do a conditional # randomly select a register to measure ireg = random.randint(0, n_registers-1) qreg = circuit.qregs[ireg] creg = circuit.cregs[ireg] for qind in range(qreg.size): operator(qreg[qind], creg[qind]) ifval = random.randint(0, (1 << qreg.size) - 1) # TODO: replace choices with random.choices() when # python 3.6 is required. uop_name = choices(uop_basis, weights=uop_basis_weights)[0] if hasattr(circuit, uop_name): uop = getattr(circuit, uop_name) else: raise AttributeError('operation \"{0}\"' ' not recognized'.format(uop_name)) unregs = self.op_signature[uop_name]['nregs'] unparams = self.op_signature[uop_name]['nparams'] if unregs == 0: # this is a barrier or measure unregs = random.randint(1, n_qubits) if qreg.size >= unregs: qind_list = random.sample(range(qreg.size), unregs) uop_args = [] if unparams: uop_args = [random.random() for _ in range(unparams)] uop_args.extend([qreg[qind] for qind in qind_list]) uop(*uop_args).c_if(creg, ifval) depth_cnt -= 1 elif op_name == 'barrier': ireg = random.randint(0, n_registers-1) qreg = circuit.qregs[ireg] bar_args = [(qreg, mi) for mi in range(qreg.size)] operator(*bar_args) else: # select random register ireg = random.randint(0, n_registers-1) qreg = circuit.qregs[ireg] if qreg.size >= n_regs: qind_list = random.sample(range(qreg.size), n_regs) op_args.extend([qreg[qind] for qind in qind_list]) operator(*op_args) depth_cnt -= 1 else: break nmeasure = random.randint(1, n_qubits) m_list = random.sample(range(nmeasure), nmeasure) if do_measure: for qind in m_list: rind = 0 # register index cumtot = 0 while qind >= cumtot + circuit.qregs[rind].size: cumtot += circuit.qregs[rind].size rind += 1 qrind = int(qind - cumtot) qreg = circuit.qregs[rind] creg = circuit.cregs[rind] circuit.measure(qreg[qrind], creg[qrind]) self.circuit_list.append(circuit) def min_regs_exceeds_nqubits(self, basis, n_qubits): """Check whether the minimum number of qubits used by the operations in basis is between 1 and the number of qubits. Args: basis (list): list of basis names n_qubits (int): number of qubits in circuit Returns: boolean: result of the check. """ return not any((n_qubits >= self.op_signature[opName]['nregs'] > 0 for opName in basis)) def get_circuits(self): """Get random circuits Returns: list: List of QuantumCircuit objects. """ return self.circuit_list def rand_register_sizes(n_registers, pvals): """Return a randomly chosen list of nRegisters summing to nQubits.""" vector = numpy.random.multinomial(n_registers, pvals) return vector[vector.nonzero()]
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw()
https://github.com/intrinsicvardhan/QuantumComputingAlgos
intrinsicvardhan
# Importing everything from qiskit import QuantumCircuit from qiskit import IBMQ, Aer, transpile from qiskit.visualization import plot_histogram def create_bell_pair(): """ Returns: QuantumCircuit: Circuit that produces a Bell pair """ qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): """Encodes a two-bit message on qc using the superdense coding protocol Args: qc (QuantumCircuit): Circuit to encode message on qubit (int): Which qubit to add the gate to msg (str): Two-bit message to send Returns: QuantumCircuit: Circuit that, when decoded, will produce msg Raises: ValueError if msg is wrong length or contains invalid characters """ if len(msg) != 2 or not set(msg).issubset({"0","1"}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc # Charlie creates the entangled pair between Alice and Bob qc = create_bell_pair() # We'll add a barrier for visual separation qc.barrier() # At this point, qubit 0 goes to Alice and qubit 1 goes to Bob # Next, Alice encodes her message onto qubit 1. In this case, # we want to send the message '10'. You can try changing this # value and see how it affects the circuit message = '10' qc = encode_message(qc, 1, message) qc.barrier() # Alice then sends her qubit to Bob. # After receiving qubit 0, Bob applies the recovery protocol: qc = decode_message(qc) # Finally, Bob measures his qubits to read Alice's message qc.measure_all() # Draw our output qc.draw() aer_sim = Aer.get_backend('aer_simulator') result = aer_sim.run(qc).result() counts = result.get_counts(qc) print(counts) plot_histogram(counts) from qiskit import IBMQ from qiskit.providers.ibmq import least_busy shots = 1024 # Load local account information IBMQ.load_account() # Get the least busy backend provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit t_qc = transpile(qc, backend, optimization_level=3) job = backend.run(t_qc) # Monitoring our job from qiskit.tools.monitor import job_monitor job_monitor(job) # Plotting our result result = job.result() plot_histogram(result.get_counts(qc)) correct_results = result.get_counts(qc)[message] accuracy = (correct_results/shots)*100 print(f"Accuracy = {accuracy:.2f}%") import qiskit.tools.jupyter %qiskit_version_table
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_aer.utils import approximate_quantum_error, approximate_noise_model import numpy as np # Import Aer QuantumError functions that will be used from qiskit_aer.noise import amplitude_damping_error, reset_error, pauli_error from qiskit.quantum_info import Kraus gamma = 0.23 error = amplitude_damping_error(gamma) results = approximate_quantum_error(error, operator_string="reset") print(results) p = (1 + gamma - np.sqrt(1 - gamma)) / 2 q = 0 print("") print("Expected results:") print("P(0) = {}".format(1-(p+q))) print("P(1) = {}".format(p)) print("P(2) = {}".format(q)) gamma = 0.23 K0 = np.array([[1,0],[0,np.sqrt(1-gamma)]]) K1 = np.array([[0,np.sqrt(gamma)],[0,0]]) results = approximate_quantum_error(Kraus([K0, K1]), operator_string="reset") print(results) reset_to_0 = Kraus([np.array([[1,0],[0,0]]), np.array([[0,1],[0,0]])]) reset_to_1 = Kraus([np.array([[0,0],[1,0]]), np.array([[0,0],[0,1]])]) reset_kraus = [reset_to_0, reset_to_1] gamma = 0.23 error = amplitude_damping_error(gamma) results = approximate_quantum_error(error, operator_list=reset_kraus) print(results) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/ohadlev77/sat-circuits-engine
ohadlev77
# Copyright 2022-2023 Ohad Lev. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0, # or in the root directory of this package("LICENSE.txt"). # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for `util.py` module.""" import unittest from datetime import datetime from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from sat_circuits_engine.util import flatten_circuit, timestamp class UtilTest(unittest.TestCase): def test_timestamp(self): """Test for the `timestamp` function.""" self.assertEqual(timestamp(datetime(2022, 12, 3, 17, 0, 45, 0)), "D03.12.22_T17.00.45") def test_flatten_circuit(self): """Test for the `flatten_circuit` function.""" bits_1 = 2 bits_2 = 3 qreg_1 = QuantumRegister(bits_1) qreg_2 = QuantumRegister(bits_2) creg_1 = ClassicalRegister(bits_1) creg_2 = ClassicalRegister(bits_2) circuit = QuantumCircuit(qreg_1, qreg_2, creg_1, creg_2) self.assertEqual(circuit.num_qubits, bits_1 + bits_2) self.assertEqual(circuit.num_clbits, bits_1 + bits_2) self.assertEqual(len(circuit.qregs), 2) self.assertEqual(len(circuit.cregs), 2) flat_circuit = flatten_circuit(circuit) self.assertEqual(flat_circuit.num_qubits, bits_1 + bits_2) self.assertEqual(flat_circuit.num_clbits, bits_1 + bits_2) self.assertEqual(len(flat_circuit.qregs), 1) self.assertEqual(len(flat_circuit.cregs), 1) if __name__ == "__main__": unittest.main()