repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
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/Bikramaditya0154/Quantum-Simulation-of-the-ground-states-of-Li-and-Li-2-using-Variational-Quantum-EIgensolver
Bikramaditya0154
from qiskit import Aer from qiskit_nature.drivers import UnitsType, 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.mappers.second_quantization import JordanWignerMapper molecule = Molecule( geometry=[["Li", [0.0, 0.0, 0.0]]], charge=1, multiplicity=1 ) driver = ElectronicStructureMoleculeDriver( molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF ) es_problem = ElectronicStructureProblem(driver) qubit_converter = QubitConverter(JordanWignerMapper()) from qiskit.providers.aer import StatevectorSimulator from qiskit import Aer from qiskit.utils import QuantumInstance from qiskit_nature.algorithms import VQEUCCFactory quantum_instance = QuantumInstance(backend=Aer.get_backend("aer_simulator_statevector")) vqe_solver = VQEUCCFactory(quantum_instance=quantum_instance) from qiskit.algorithms import VQE from qiskit.circuit.library import TwoLocal tl_circuit = TwoLocal( rotation_blocks=["h", "rx"], entanglement_blocks="cz", entanglement="full", reps=2, parameter_prefix="y", ) another_solver = VQE( ansatz=tl_circuit, quantum_instance=QuantumInstance(Aer.get_backend("aer_simulator_statevector")), ) from qiskit_nature.algorithms import GroundStateEigensolver calc = GroundStateEigensolver(qubit_converter, vqe_solver) res = calc.solve(es_problem) print(res)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Quantum Fourier Transform benchmark suite""" # Write the benchmarking functions here. # See "Writing benchmarks" in the asv docs for more information. from qiskit import QiskitError from qiskit.compiler import transpile, assemble from qiskit.providers.aer import QasmSimulator from .tools import quantum_fourier_transform_circuit, \ mixed_unitary_noise_model, reset_noise_model, \ kraus_noise_model, no_noise class QuantumFourierTransformQasmSimulatorBenchSuite: """ Benchmarking times for Quantum Fourier Transform with various noise configurations: - ideal (no noise) - mixed state - reset - kraus and different simulator methods For each noise model, we want to test various configurations of number of qubits The methods defined in this class will be executed by ASV framework as many times as the combination of all parameters exist in `self.params`, for exmaple: self.params = ([1,2,3],[4,5,6]), will run all methdos 9 times: time_method(1,4) time_method(1,5) time_method(1,6) time_method(2,4) time_method(2,5) time_method(2,6) time_method(3,4) time_method(3,5) time_method(3,6) """ def __init__(self): self.timeout = 60 * 20 self.qft_circuits = [] self.backend = QasmSimulator() for num_qubits in (5, 10, 15, 20): circ = quantum_fourier_transform_circuit(num_qubits) circ = transpile(circ, basis_gates=['u1', 'u2', 'u3', 'cx'], optimization_level=0, seed_transpiler=1) qobj = assemble(circ, self.backend, shots=1) self.qft_circuits.append(qobj) self.param_names = ["Quantum Fourier Transform", "Noise Model", "Simulator Method"] # This will run every benchmark for one of the combinations we have: # bench(qft_circuits, None) => bench(qft_circuits, mixed()) => # bench(qft_circuits, reset) => bench(qft_circuits, kraus()) self.params = ( self.qft_circuits, [no_noise(), mixed_unitary_noise_model(), reset_noise_model(), kraus_noise_model()], ['statevector', 'density_matrix', 'stabilizer', 'extended_stabilizer', 'matrix_product_state']) def setup(self, qobj, noise_model_wrapper, simulator_method): """ Setup env before benchmarks start """ def time_quantum_fourier_transform(self, qobj, noise_model_wrapper, simulator_method): """ Benchmark QFT """ backend_options = { 'method': simulator_method, 'noise_model': noise_model_wrapper(), } result = self.backend.run( qobj, noise_model=noise_model_wrapper() ).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status) def peakmem_quantum_fourier_transform(self, qobj, noise_model_wrapper, simulator_method): """ Benchmark QFT """ backend_options = { 'method': simulator_method, 'noise_model': noise_model_wrapper(), } result = self.backend.run( qobj, noise_model=noise_model_wrapper() ).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status)
https://github.com/BoschSamuel/QizGloria
BoschSamuel
# -- coding: utf-8 -- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import torch from torch.autograd import Function import torch.optim as optim from qiskit import QuantumRegister,QuantumCircuit,ClassicalRegister,execute from qiskit.circuit import Parameter from qiskit import Aer import numpy as np from tqdm import tqdm from matplotlib import pyplot as plt from torch.autograd import Function %matplotlib inline np.random.seed = 42 def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QiskitCircuit_QAOA(): def __init__(self,shots): self.beta = Parameter('Beta') self.gamma = Parameter('Gamma') self.shots = shots def create_circuit(): ckt = QuantumCircuit(2, 2) # add mixer part ckt.rx(self.beta, 0) ckt.rx(self.beta, 1) # add H_target part, for each Zi Zj do this ckt.cx(0,1) ckt.rz(-1*self.gamma, 1) ckt.cx(0,1) ckt.measure([0,1],[0,1]) return ckt self.circuit = create_circuit() def energy_expectation(self, counts, shots, i,j, Cij=-1): #calculate expectation for one qubit pair expects = 0 #print(counts) for key in counts.keys(): perc = counts[key]/shots check = Cij*(float(key[i])-1/2)*(float(key[j])-1/2)*perc expects += check return [expects] def bind(self,parameters): [self.beta,self.gamma] = parameters #print(self.circuit.data) self.circuit.data[0][0]._params = to_numbers(parameters)[0:1] self.circuit.data[1][0]._params = to_numbers(parameters)[0:1] self.circuit.data[3][0]._params = to_numbers(parameters)[1:2] return self.circuit def run(self, i): self.bind(i) backend = Aer.get_backend('qasm_simulator') job_sim = execute(self.circuit,backend,shots=self.shots) result_sim = job_sim.result() counts = result_sim.get_counts(self.circuit) #print(counts) return self.energy_expectation(counts, self.shots, 0,1) class TorchCircuit(Function): @staticmethod def forward(ctx, i): if not hasattr(ctx, 'QiskitCirc'): ctx.QiskitCirc = QiskitCircuit_QAOA(shots=10000) #print(i[0]) exp_value = ctx.QiskitCirc.run(i[0]) result = torch.tensor([exp_value]) ctx.save_for_backward(result, i) return result @staticmethod def backward(ctx, grad_output): eps = 0.01 forward_tensor, i = ctx.saved_tensors input_numbers = to_numbers(i[0]) gradient = [] for k in range(len(input_numbers)): input_eps = input_numbers input_eps[k] = input_numbers[k] + eps exp_value = ctx.QiskitCirc.run(torch.tensor(input_eps))[0] result_eps = torch.tensor([exp_value]) gradient_result = (exp_value - forward_tensor[0][0].item())/eps gradient.append(gradient_result) # print(gradient) result = torch.tensor([gradient]) # print(result) #print("test tens size", result.float(), grad_output.float()) return result.float() * grad_output.float() torch.manual_seed(42) # x = torch.tensor([np.pi/4, np.pi/4, np.pi/4], requires_grad=True) x = torch.tensor([[0.3, 0.2]], requires_grad=True) qc = TorchCircuit.apply y1 = qc(x) print(y1) y1.backward() print(x.grad) qc = TorchCircuit.apply def cost(x): target = -0.25 expval = qc(x) return torch.abs(qc(x).sum() - target) ** 2, expval x = torch.tensor([[np.pi/4, np.pi/4]], requires_grad=True) opt = torch.optim.Adam([x], lr=0.1) num_epoch = 100 loss_list = [] expval_list = [] for i in tqdm(range(num_epoch)): # for i in range(num_epoch): opt.zero_grad() loss, expval = cost(x) loss.backward() opt.step() loss_list.append(loss.item()) expval_list.append(expval.item()) # print(loss.item()) plt.plot(loss_list) # print(circuit(phi, theta)) # print(cost(x)) import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import torchvision from torchvision import datasets, transforms batch_size_train = 1 batch_size_test = 1 learning_rate = 0.01 momentum = 0.5 log_interval = 10 torch.backends.cudnn.enabled = False transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor()]) mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) labels = mnist_trainset.targets #get labels labels = labels.numpy() idx1 = np.where(labels == 0) #search all zeros idx2 = np.where(labels == 1) # search all ones idx = np.concatenate((idx1[0][0:10],idx2[0][0:10])) # concatenate their indices #idx = idx2 mnist_trainset.targets = labels[idx] mnist_trainset.data = mnist_trainset.data[idx] print(mnist_trainset) train_loader = torch.utils.data.DataLoader(mnist_trainset, batch_size=batch_size_train, shuffle=True) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 6) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) #x = np.pi*F.tanh(x) #print(x) x = qc(x) # print(x) x = (x+1)/4 x = torch.cat((x, 1-x), -1) return x # return F.softmax(x) network = Net() optimizer = optim.SGD(network.parameters(), lr=learning_rate, momentum=momentum) epochs = 100 for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): # print(batch_idx) optimizer.zero_grad() output = network(data) print(output[0].data, target) loss = F.nll_loss(output, target) # print(output) # print(output[0][1].item(), target.item()) #print(loss) loss.backward() optimizer.step() total_loss.append(loss.item()) print(sum(total_loss)/len(total_loss))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123456 from sklearn.datasets import make_blobs features, labels = make_blobs( n_samples=20, centers=2, center_box=(-1, 1), cluster_std=0.1, random_state=algorithm_globals.random_seed, ) from qiskit import BasicAer from qiskit.utils import QuantumInstance sv_qi = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) from qiskit.circuit.library import ZZFeatureMap from qiskit_machine_learning.kernels import QuantumKernel feature_map = ZZFeatureMap(2) previous_kernel = QuantumKernel(feature_map=feature_map, quantum_instance=sv_qi) from qiskit_machine_learning.algorithms import QSVC qsvc = QSVC(quantum_kernel=previous_kernel) qsvc.fit(features, labels) qsvc.score(features, labels) from qiskit.algorithms.state_fidelities import ComputeUncompute from qiskit.primitives import Sampler fidelity = ComputeUncompute(sampler=Sampler()) from qiskit_machine_learning.kernels import FidelityQuantumKernel feature_map = ZZFeatureMap(2) new_kernel = FidelityQuantumKernel(feature_map=feature_map, fidelity=fidelity) from qiskit_machine_learning.algorithms import QSVC qsvc = QSVC(quantum_kernel=new_kernel) qsvc.fit(features, labels) qsvc.score(features, labels) from qiskit import QuantumCircuit from qiskit.circuit.library import RealAmplitudes num_inputs = 2 feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) circuit = QuantumCircuit(num_inputs) circuit.compose(feature_map, inplace=True) circuit.compose(ansatz, inplace=True) def parity(x): return "{:b}".format(x).count("1") % 2 initial_point = algorithm_globals.random.random(ansatz.num_parameters) from qiskit_machine_learning.neural_networks import CircuitQNN circuit_qnn = CircuitQNN( circuit=circuit, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=2, quantum_instance=sv_qi, ) from qiskit.algorithms.optimizers import COBYLA from qiskit_machine_learning.algorithms import NeuralNetworkClassifier classifier = NeuralNetworkClassifier( neural_network=circuit_qnn, loss="cross_entropy", one_hot=True, optimizer=COBYLA(maxiter=40), initial_point=initial_point, ) classifier.fit(features, labels) classifier.score(features, labels) from qiskit.primitives import Sampler sampler = Sampler() from qiskit_machine_learning.neural_networks import SamplerQNN sampler_qnn = SamplerQNN( circuit=circuit, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=2, sampler=sampler, ) classifier = NeuralNetworkClassifier( neural_network=sampler_qnn, loss="cross_entropy", one_hot=True, optimizer=COBYLA(maxiter=40), initial_point=initial_point, ) classifier.fit(features, labels) classifier.score(features, labels) import numpy as np num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi features = (ub - lb) * np.random.rand(num_samples, 1) + lb labels = np.sin(features[:, 0]) + eps * (2 * np.random.rand(num_samples) - 1) from qiskit.circuit import Parameter num_inputs = 1 feature_map = QuantumCircuit(1) feature_map.ry(Parameter("input"), 0) ansatz = QuantumCircuit(1) ansatz.ry(Parameter("weight"), 0) circuit = QuantumCircuit(num_inputs) circuit.compose(feature_map, inplace=True) circuit.compose(ansatz, inplace=True) initial_point = algorithm_globals.random.random(ansatz.num_parameters) from qiskit.opflow import PauliSumOp, StateFn from qiskit_machine_learning.neural_networks import OpflowQNN observable = PauliSumOp.from_list([("Z", 1)]) operator = StateFn(observable, is_measurement=True) @ StateFn(circuit) opflow_qnn = OpflowQNN( operator=operator, input_params=feature_map.parameters, weight_params=ansatz.parameters, quantum_instance=sv_qi, ) from qiskit.algorithms.optimizers import L_BFGS_B from qiskit_machine_learning.algorithms import NeuralNetworkRegressor regressor = NeuralNetworkRegressor( neural_network=opflow_qnn, optimizer=L_BFGS_B(maxiter=5), initial_point=initial_point, ) regressor.fit(features, labels) regressor.score(features, labels) from qiskit.primitives import Estimator estimator = Estimator() from qiskit_machine_learning.neural_networks import EstimatorQNN estimator_qnn = EstimatorQNN( circuit=circuit, input_params=feature_map.parameters, weight_params=ansatz.parameters, estimator=estimator, ) from qiskit.algorithms.optimizers import L_BFGS_B from qiskit_machine_learning.algorithms import VQR regressor = NeuralNetworkRegressor( neural_network=estimator_qnn, optimizer=L_BFGS_B(maxiter=5), initial_point=initial_point, ) regressor.fit(features, labels) regressor.score(features, labels) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/acfilok96/Quantum-Computation
acfilok96
import qiskit print(qiskit.__version__) from qiskit.aqua.algorithms import Shor from qiskit.aqua import QuantumInstance import numpy as np from qiskit import QuantumCircuit, Aer, execute from qiskit.tools.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend=backend, shots=1024) my_shor = Shor(N=2189,a=4,quantum_instance=quantum_instance) Shor.run(my_shor)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests PassManagerConfig""" from qiskit import QuantumRegister from qiskit.providers.backend import Backend from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeMelbourne, FakeArmonk, FakeHanoi, FakeHanoiV2 from qiskit.providers.basicaer import QasmSimulatorPy from qiskit.transpiler.coupling import CouplingMap from qiskit.transpiler.passmanager_config import PassManagerConfig class TestPassManagerConfig(QiskitTestCase): """Test PassManagerConfig.from_backend().""" def test_config_from_backend(self): """Test from_backend() with a valid backend. `FakeHanoi` is used in this testcase. This backend has `defaults` attribute that contains an instruction schedule map. """ backend = FakeHanoi() config = PassManagerConfig.from_backend(backend) self.assertEqual(config.basis_gates, backend.configuration().basis_gates) self.assertEqual(config.inst_map, backend.defaults().instruction_schedule_map) self.assertEqual( str(config.coupling_map), str(CouplingMap(backend.configuration().coupling_map)) ) def test_config_from_backend_v2(self): """Test from_backend() with a BackendV2 instance.""" backend = FakeHanoiV2() config = PassManagerConfig.from_backend(backend) self.assertEqual(config.basis_gates, backend.operation_names) self.assertEqual(config.inst_map, backend.instruction_schedule_map) self.assertEqual(config.coupling_map.get_edges(), backend.coupling_map.get_edges()) def test_invalid_backend(self): """Test from_backend() with an invalid backend.""" with self.assertRaises(AttributeError): PassManagerConfig.from_backend(Backend()) def test_from_backend_and_user(self): """Test from_backend() with a backend and user options. `FakeMelbourne` is used in this testcase. This backend does not have `defaults` attribute and thus not provide an instruction schedule map. """ qr = QuantumRegister(4, "qr") initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] backend = FakeMelbourne() config = PassManagerConfig.from_backend( backend, basis_gates=["user_gate"], initial_layout=initial_layout ) self.assertEqual(config.basis_gates, ["user_gate"]) self.assertNotEqual(config.basis_gates, backend.configuration().basis_gates) self.assertIsNone(config.inst_map) self.assertEqual( str(config.coupling_map), str(CouplingMap(backend.configuration().coupling_map)) ) self.assertEqual(config.initial_layout, initial_layout) def test_from_backendv1_inst_map_is_none(self): """Test that from_backend() works with backend that has defaults defined as None.""" backend = FakeHanoi() backend.defaults = lambda: None config = PassManagerConfig.from_backend(backend) self.assertIsInstance(config, PassManagerConfig) self.assertIsNone(config.inst_map) def test_simulator_backend_v1(self): """Test that from_backend() works with backendv1 simulator.""" backend = QasmSimulatorPy() config = PassManagerConfig.from_backend(backend) self.assertIsInstance(config, PassManagerConfig) self.assertIsNone(config.inst_map) self.assertIsNone(config.coupling_map) def test_invalid_user_option(self): """Test from_backend() with an invalid user option.""" with self.assertRaises(TypeError): PassManagerConfig.from_backend(FakeMelbourne(), invalid_option=None) def test_str(self): """Test string output.""" pm_config = PassManagerConfig.from_backend(FakeArmonk()) # For testing remove instruction schedule map it's str output is non-deterministic # based on hash seed pm_config.inst_map = None str_out = str(pm_config) expected = """Pass Manager Config: initial_layout: None basis_gates: ['id', 'rz', 'sx', 'x'] inst_map: None coupling_map: None layout_method: None routing_method: None translation_method: None scheduling_method: None instruction_durations: id(0,): 7.111111111111111e-08 s rz(0,): 0.0 s sx(0,): 7.111111111111111e-08 s x(0,): 7.111111111111111e-08 s measure(0,): 4.977777777777777e-06 s backend_properties: {'backend_name': 'ibmq_armonk', 'backend_version': '2.4.3', 'gates': [{'gate': 'id', 'name': 'id0', 'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)), 'name': 'gate_error', 'unit': '', 'value': 0.00019769550670970334}, {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'gate_length', 'unit': 'ns', 'value': 71.11111111111111}], 'qubits': [0]}, {'gate': 'rz', 'name': 'rz0', 'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'gate_error', 'unit': '', 'value': 0}, {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'gate_length', 'unit': 'ns', 'value': 0}], 'qubits': [0]}, {'gate': 'sx', 'name': 'sx0', 'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)), 'name': 'gate_error', 'unit': '', 'value': 0.00019769550670970334}, {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'gate_length', 'unit': 'ns', 'value': 71.11111111111111}], 'qubits': [0]}, {'gate': 'x', 'name': 'x0', 'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)), 'name': 'gate_error', 'unit': '', 'value': 0.00019769550670970334}, {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'gate_length', 'unit': 'ns', 'value': 71.11111111111111}], 'qubits': [0]}], 'general': [], 'last_update_date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'qubits': [[{'date': datetime.datetime(2021, 3, 15, 0, 36, 17, tzinfo=tzoffset(None, -14400)), 'name': 'T1', 'unit': 'us', 'value': 182.6611165336624}, {'date': datetime.datetime(2021, 3, 14, 0, 33, 45, tzinfo=tzoffset(None, -18000)), 'name': 'T2', 'unit': 'us', 'value': 237.8589220110257}, {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'frequency', 'unit': 'GHz', 'value': 4.971852852405576}, {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'anharmonicity', 'unit': 'GHz', 'value': -0.34719293148282626}, {'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)), 'name': 'readout_error', 'unit': '', 'value': 0.02400000000000002}, {'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)), 'name': 'prob_meas0_prep1', 'unit': '', 'value': 0.0234}, {'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)), 'name': 'prob_meas1_prep0', 'unit': '', 'value': 0.024599999999999955}, {'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)), 'name': 'readout_length', 'unit': 'ns', 'value': 4977.777777777777}]]} approximation_degree: None seed_transpiler: None timing_constraints: None unitary_synthesis_method: default unitary_synthesis_plugin_config: None target: None """ self.assertEqual(str_out, expected)
https://github.com/sjana01/QiskitNotebooks
sjana01
import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Set a seed for the random number generator so we get the same random numbers each time np.random.seed(42) # Create fake x-data x = np.arange(10) # Create fake y-data a = 4.5 b = 0.5 c = 20 y = a * np.exp(-b * x) + c y = y + np.random.normal(loc=0, scale=0.3, size=len(x)) # Add noise def plot_sc(x,y): fig, ax = plt.subplots() ax.scatter(x, y, c="green") ax.set_xlabel("X") ax.set_ylabel("y") #ax.legend() plt.show() plot_sc(x,y) # Set a seed for the random number generator so we get the same random numbers each time np.random.seed(6354) # Create fake x-data x1 = np.arange(10) # Create fake y-data a = 4.5 b = 0.5 c = 0 #set c=0 y1 = a * np.exp(b * x) y1 = y1 + np.random.normal(loc=0, scale=10, size=len(x)) # Add noise plot_sc(x1,y1) # Fit a polynomial of degree 1 (a linear function) to the data p = np.polyfit(x1, np.log(y1), 1) # Convert the polynomial back into an exponential a = np.exp(p[1]) b = p[0] x1_fit = np.linspace(np.min(x1), np.max(x1), 100) y1_fit = a*np.exp(b * x1_fit) ax = plt.axes() ax.scatter(x1, y1, label='Raw data') ax.plot(x1_fit, y1_fit, 'k', label='Fitted curve') ax.set_title('Using polyfit() to fit an exponential function') ax.set_ylabel('y') ax.set_ylim(0, 500) ax.set_xlabel('X') ax.legend() # Fit a weighted polynomial of degree 1 (a linear function) to the data p = np.polyfit(x1, np.log(y1), 1, w=np.sqrt(y1)) # Convert the polynomial back into an exponential a = np.exp(p[1]) b = p[0] x1_fit_wt = np.linspace(np.min(x1), np.max(x1), 100) y1_fit_wt = a * np.exp(b * x1_fit_wt) # Plot ax = plt.axes() ax.scatter(x1, y1, label='Raw data') ax.plot(x1_fit, y1_fit, 'k', label='Fitted curve, unweighted') ax.plot(x1_fit_wt, y1_fit_wt, 'k--', label='Fitted curve, weighted') ax.set_title('Using polyfit() to fit an exponential function') ax.set_ylabel('y') ax.set_ylim(0, 500) ax.set_xlabel('X') ax.legend() # Set a seed for the random number generator so we get the same random numbers each time np.random.seed(6354) # Create fake x-data x2 = np.arange(10) # Create fake y-data a = 4.5 b = 0.5 c = 50 y2 = a * np.exp(b * x) + c y2 = y2 + np.random.normal(loc=0, scale=10, size=len(x)) # Add noise plot_sc(x2,y2) # Have an initial guess as to what the values of the parameters are a0 = 5 b0 = 0.6 c0 = 40 from scipy.optimize import curve_fit # Fit the function a * np.exp(b * t) + c to x and y popt, pcov = curve_fit(lambda t, a, b, c: a * np.exp(b * t) + c, x2, y2, p0=(a0,b0,c0), maxfev=5000) # Create the fitted curve x2_fit = np.linspace(np.min(x2), np.max(x2), 100) y2_fit = popt[0] * np.exp(popt[1] * x2_fit) + popt[2] ax = plt.axes() ax.scatter(x2, y2, label='Raw data') ax.plot(x2_fit, y2_fit, 'k', label='Fitted curve') ax.set_title('Using curve_fit() to fit an exponential function') ax.set_ylabel('y') ax.set_ylim(0, 500) ax.set_xlabel('X') ax.legend() print(popt) # Set a seed for the random number generator so we get the same random numbers each time np.random.seed(64) # Create fake x-data x3 = np.arange(10) # Create fake y-data a = 4.5 b = - 0.5 c = 10 y3 = a * np.exp(b * x) + c y3 = y3 + np.random.normal(loc=0, scale=0.1, size=len(x3)) # Add noise plot_sc(x3,y3) # Have an initial guess as to what the values of the parameters are a0 = 5 b0 = - 0.6 c0 = 12 # Fit the function a * np.exp(b * t) + c to x and y popt, pcov = curve_fit(lambda t, a, b, c: a * np.exp(b * t) + c, x3, y3, p0=(a0,b0,c0), maxfev=5000) # Create the fitted curve x3_fit = np.linspace(np.min(x3), np.max(x3), 100) y3_fit = popt[0] * np.exp(popt[1] * x3_fit) + popt[2] ax = plt.axes() ax.scatter(x3, y3, label='Raw data') ax.plot(x3_fit, y3_fit, 'k', label='Fitted curve') ax.set_title('Fitting an negative exponential function') ax.set_ylabel('y') ax.set_ylim(9.5, 15.5) ax.set_xlabel('X') ax.legend() popt def func(x,a,b,c): return a * np.exp(b * x) + c from lmfit import Model model = Model(func) model.independent_vars model.param_names params = model.make_params(a=5.0, b=-0.6, c=12) result = model.fit(y3, params, x=x3) print(result.fit_report()) y4 = np.array([146., 94., 79.,62., 41.]) x4 = np.array([375, 470, 528, 625,880]) def fun(x, alpha1, alpha2, A, B): return A*x**(-alpha1) uncertainty = abs(0.16 + np.random.normal(size=x.size, scale=0.05)) uncertainty from lmfit import minimize, Parameters def residual(params, x, data): alpha1 = params['alpha1'] A = params['A'] model = A*x**(-alpha1) return (data-model) params = Parameters() params.add('alpha1', value=1.0, min=0.8, max=10.0) params.add('A', value=100.0, min=100.0, max=1.0e10) out = minimize(residual, params, args=(x4, y4)) out.params x4_fit = np.linspace(np.min(x4), np.max(x4), 100) y4_fit = 15423.092*x4_fit**(-1.40000000) + 1.0000e+29*x4_fit**(-13.0000000) ax = plt.axes() ax.scatter(x4, y4, label='Raw data') ax.plot(x4_fit, y4_fit, 'k', label='Fitted curve') ax.set_title('Fitting an power curve') ax.set_ylabel('y') ax.set_xlabel('X') ax.legend() y4_B = 1.0000e+10*x4_fit**(-10.0000000) ax = plt.axes() ax.scatter(x4, y4, label='Raw data') ax.plot(x4_fit, y4_fit, 'k', label='Fitted curve') ax.plot(x4_fit, y4_B, 'k--', label='Fit 2nd Component') ax.set_title('Fitting an power curve') ax.set_ylabel('y') ax.set_xlabel('X') ax.legend() y4 = np.array([146., 94., 79.,62., 41.]) x4 = np.array([375., 470., 528., 625.,880.]) from scipy.optimize import differential_evolution def func(parameters, *data): #we have 3 parameters which will be passed as parameters and #"experimental" x,y which will be passed as data a1,a2,A1,A2 = parameters x,y = data result = 0 for i in range(len(x)): result += (A1*x[i]**(-a1) + A2*x[i]**(-a2) - y[i])**2 return result**0.5 bounds = [(0.8, 1.4), (1.5,15.0), (1000.0, 1.0e10), (1000.0, 1.0e30)] #packing "experimental" data into args args = (x4,y4) result = differential_evolution(func, bounds, args=args) result.x def func1(parameters, *data): #we have 3 parameters which will be passed as parameters and #"experimental" x,y which will be passed as data a1,A1= parameters x,y = data result = 0 for i in range(len(x)): result += (A1*x[i]**(-a1) -y4[i])**2 return result bounds = [(0.5, 10), (100.0, 1.0e10)] #packing "experimental" data into args args = (x4,y4) result = differential_evolution(func1, bounds, args=args) result.x alpha1 = [optimizer(bounds)[0] for i in range(20)] alpha2 = [optimizer(bounds)[1] for i in range(20)] min(alpha2), max(alpha2) x4_fit = np.linspace(np.min(x4), np.max(x4), 100) alpha1 = result.x[0] alpha2 = result.x[1] A = result.x[2] B = result.x[3] y4_A = A*x4_fit**(-alpha1) y4_B = B*x4_fit**(-alpha2) ax = plt.axes() # ax.scatter(x4, y4, label='Raw data') ax.plot(x4_fit, y4_A, 'k', label='Fit curve 1st Component') ax.plot(x4_fit, y4_B, 'k--', label='Fit curve 2nd Component') ax.set_title('Fitting an power curve') ax.set_ylabel('y') ax.set_xlabel('X') ax.legend() y4_fit = result.x[1]*x4_fit**(-result.x[0]) ax = plt.axes() ax.scatter(x4, y4, label='Raw data') ax.plot(x4_fit, y4_fit, 'k', label='Fit curve 1st Component') #ax.plot(x4_fit, y4_B, 'k--', label='Fit curve 2nd Component') ax.set_title('Fitting an power curve') ax.set_ylabel('y') ax.set_xlabel('X') ax.legend()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit.quantum_info import Operator from qiskit.circuit.library.standard_gates import XGate, YGate, ZGate class FiveQubitCode: def __init__(self): # Initialize Registers self.code = QuantumRegister(5, name="code") self.syndrm = QuantumRegister(4, name="syndrome") # Build Circuit Components self.encoder_ckt = self.build_encoder() self.syndrome_ckt = self.build_syndrome() self.correction_ckt = self.build_correction() self.decoder_ckt = self.encoder_ckt.mirror() # Build Noisy Channel self.noise_ckt = QuantumCircuit(self.code, self.syndrm) for i in range(5): self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[i]], label='noise') # Compose Full Circuit circ = QuantumCircuit(self.code, self.syndrm) circ.barrier() self.circuit = self.encoder_ckt + circ + self.noise_ckt + circ + self.syndrome_ckt self.circuit = self.circuit + circ + self.correction_ckt + circ + self.decoder_ckt def build_encoder(self): # Build Encoder Circuit circ = QuantumCircuit(self.code, self.syndrm, name="Encoder Circuit") circ.z(self.code[4]) circ.h(self.code[4]) circ.z(self.code[4]) circ.cx(self.code[4], self.code[3]) circ.h(self.code[4]) circ.h(self.code[3]) circ.cx(self.code[4], self.code[2]) circ.cx(self.code[3], self.code[2]) circ.h(self.code[2]) circ.cx(self.code[4], self.code[1]) circ.cx(self.code[2], self.code[1]) circ.h(self.code[1]) circ.h(self.code[4]) circ.cx(self.code[4], self.code[0]) circ.cx(self.code[3], self.code[0]) circ.cx(self.code[2], self.code[0]) circ.h(self.code[3]) circ.h(self.code[4]) return circ def build_syndrome(self): # Build Syndrome Circuit circ = QuantumCircuit(self.code, self.syndrm, name="Syndrome Circuit") circ.h(self.syndrm) circ.barrier() circ.cz(self.syndrm[0], self.code[4]) circ.cx(self.syndrm[0], self.code[3]) circ.cx(self.syndrm[0], self.code[2]) circ.cz(self.syndrm[0], self.code[1]) circ.cx(self.syndrm[1], self.code[4]) circ.cx(self.syndrm[1], self.code[3]) circ.cz(self.syndrm[1], self.code[2]) circ.cz(self.syndrm[1], self.code[0]) circ.cx(self.syndrm[2], self.code[4]) circ.cz(self.syndrm[2], self.code[3]) circ.cz(self.syndrm[2], self.code[1]) circ.cx(self.syndrm[2], self.code[0]) circ.cz(self.syndrm[3], self.code[4]) circ.cz(self.syndrm[3], self.code[2]) circ.cx(self.syndrm[3], self.code[1]) circ.cx(self.syndrm[3], self.code[0]) circ.barrier() circ.h(self.syndrm) return circ def build_correction(self): # Build Correction Circuit circ = QuantumCircuit(self.code, self.syndrm) circ.append(XGate().control(4, ctrl_state='0010'), [self.syndrm[i] for i in range(4)] + [self.code[0]]) circ.append(YGate().control(4, ctrl_state='1110'), [self.syndrm[i] for i in range(4)] + [self.code[0]]) circ.append(ZGate().control(4, ctrl_state='1100'), [self.syndrm[i] for i in range(4)] + [self.code[0]]) circ.append(XGate().control(4, ctrl_state='0101'), [self.syndrm[i] for i in range(4)] + [self.code[1]]) circ.append(YGate().control(4, ctrl_state='1101'), [self.syndrm[i] for i in range(4)] + [self.code[1]]) circ.append(ZGate().control(4, ctrl_state='1000'), [self.syndrm[i] for i in range(4)] + [self.code[1]]) circ.append(XGate().control(4, ctrl_state='1010'), [self.syndrm[i] for i in range(4)] + [self.code[2]]) circ.append(YGate().control(4, ctrl_state='1011'), [self.syndrm[i] for i in range(4)] + [self.code[2]]) circ.append(ZGate().control(4, ctrl_state='0001'), [self.syndrm[i] for i in range(4)] + [self.code[2]]) circ.append(XGate().control(4, ctrl_state='0100'), [self.syndrm[i] for i in range(4)] + [self.code[3]]) circ.append(YGate().control(4, ctrl_state='0111'), [self.syndrm[i] for i in range(4)] + [self.code[3]]) circ.append(ZGate().control(4, ctrl_state='0011'), [self.syndrm[i] for i in range(4)] + [self.code[3]]) circ.append(XGate().control(4, ctrl_state='1001'), [self.syndrm[i] for i in range(4)] + [self.code[4]]) circ.append(YGate().control(4, ctrl_state='1111'), [self.syndrm[i] for i in range(4)] + [self.code[4]]) circ.append(ZGate().control(4, ctrl_state='0110'), [self.syndrm[i] for i in range(4)] + [self.code[4]]) return circ def visualize(self): # Draw Circuits self.encoder_ckt.draw('mpl', reverse_bits=True).suptitle('Encoder Circuit', fontsize=16) self.syndrome_ckt.draw('mpl', reverse_bits=True).suptitle('Syndrome Circuit', fontsize=16) self.correction_ckt.draw('mpl', reverse_bits=True).suptitle('Error Correction', fontsize=16) self.decoder_ckt.draw('mpl', reverse_bits=True).suptitle('Decoder Circuit', fontsize=16) self.circuit.draw('mpl', reverse_bits=True, style={'fontsize': 4}) \ .suptitle('Five Qubit Error Correction', fontsize=16) plt.show()
https://github.com/Cryoris/gradient-reverse-mode
Cryoris
"""A classification example where we we only have asymptotically 1/4th of parameterized gates.""" import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library import ZFeatureMap, RealAmplitudes from qiskit.circuit.parametertable import ParameterTable from qiskit.opflow import H from .benchmark import Benchmark class Classification(QuantumCircuit): """UCCSD with the same API as Qiskit's circuit library.""" def __init__(self, num_qubits, reps=3): self._reps = reps super().__init__(num_qubits) self._build() @property def reps(self): """Get the number of repetitions of the circuit.""" return self._reps @reps.setter def reps(self, value): """Set the number of repetitions. Rebuilds the circuit.""" self._reps = value self._build() # rebuild def assign_parameters(self, params, inplace=False): """Assign parameters.""" if isinstance(params, (list, np.ndarray)): params = dict(zip(self._params[:], params)) return super().assign_parameters(params, inplace=inplace) @property def ordered_parameters(self): return list(self._parameter_table.keys()) def _build(self): # wipe current state self._data = [] self._parameter_table = ParameterTable() # get UCCSD circuit featmap = ZFeatureMap(self.num_qubits, reps=self.reps) ansatz = RealAmplitudes(self.num_qubits, reps=self.reps, entanglement='circular') # store the parameters in a list for assigning them self._params = ansatz.ordered_parameters # set the data circuit with some input data featmap.assign_parameters(np.random.random(featmap.num_parameters), inplace=True) # combine the circuit self.compose(featmap, inplace=True) self.compose(ansatz, inplace=True) def run_featuremap(): circuit = Classification(4) benchmark = Benchmark(2 ** np.arange(2, 8), H, 24) benchmark.run_benchmark(circuit, 'free') benchmark.plot(show=True)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() qc = QuantumCircuit(2, 1) qc.h(0) qc.x(1) qc.cp(np.pi/4, 0, 1) qc.h(0) qc.measure([0], [0]) qc.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.72" # Two Hydrogen atoms, 0.72 Angstrom apart ) molecule = driver.run() from qiskit_nature.second_q.mappers import QubitConverter, ParityMapper qubit_converter = QubitConverter(ParityMapper()) hamiltonian = qubit_converter.convert(molecule.second_q_ops()[0]) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver sol = NumPyMinimumEigensolver().compute_minimum_eigenvalue(hamiltonian) real_solution = molecule.interpret(sol) real_solution.groundenergy from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" from qiskit.algorithms.minimum_eigensolvers import VQE # Use RealAmplitudes circuit to create trial states from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=2, reps=2) # Search for better states using SPSA algorithm from qiskit.algorithms.optimizers import SPSA optimizer = SPSA(150) # Set a starting point for reproduceability import numpy as np np.random.seed(6) initial_point = np.random.uniform(-np.pi, np.pi, 12) # Create an object to store intermediate results from dataclasses import dataclass @dataclass class VQELog: values: list parameters: list def update(self, count, parameters, mean, _metadata): self.values.append(mean) self.parameters.append(parameters) print(f"Running circuit {count} of ~350", end="\r", flush=True) log = VQELog([],[]) # Main calculation with Session(service=service, backend=backend) as session: options = Options() options.optimization_level = 3 vqe = VQE(Estimator(session=session, options=options), ansatz, optimizer, callback=log.update, initial_point=initial_point) result = vqe.compute_minimum_eigenvalue(hamiltonian) print("Experiment complete.".ljust(30)) print(f"Raw result: {result.optimal_value}") if 'simulator' not in backend: # Run once with ZNE error mitigation options.resilience_level = 2 vqe = VQE(Estimator(session=session, options=options), ansatz, SPSA(1), initial_point=result.optimal_point) result = vqe.compute_minimum_eigenvalue(hamiltonian) print(f"Mitigated result: {result.optimal_value}") import matplotlib.pyplot as plt plt.rcParams["font.size"] = 14 # Plot energy and reference value plt.figure(figsize=(12, 6)) plt.plot(log.values, label="Estimator VQE") plt.axhline(y=real_solution.groundenergy, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy") plt.show() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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 hadamard gate to first qubit, then x gate to second qc.h(0) qc.x(1) #Draw the circuit # qc.draw() qc.draw('mpl') #Get the backend for the circuit to display unitary matrix backend = Aer.get_backend('unitary_simulator') #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_unitary() #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{UnitaryMatrix} = ") #import qiskit_textbook and display the statevector #from qiskit_textbook.tools import array_to_latex #array_to_latex(out, pretext = "\\text{Statevector} = ") #plot the result as a bloch sphere visualization plot_bloch_multivector(out)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import Aer from qiskit.transpiler import PassManager from qiskit_aqua import Operator, QuantumInstance from qiskit_aqua.algorithms.adaptive import VQE from qiskit_aqua.algorithms.classical import ExactEigensolver from qiskit_aqua.components.optimizers import L_BFGS_B from qiskit_aqua.components.variational_forms import RY from qiskit_chemistry import FermionicOperator from qiskit_chemistry.drivers import PyQuanteDriver, UnitsType, BasisType # using driver to get fermionic Hamiltonian # PyQuante example driver = PyQuanteDriver(atoms='H .0 .0 .0; H .0 .0 0.735', units=UnitsType.ANGSTROM, charge=0, multiplicity=1, basis=BasisType.BSTO3G) molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals # convert from fermionic hamiltonian to qubit hamiltonian ferOp = FermionicOperator(h1=h1, h2=h2) qubitOp_jw = ferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001) qubitOp_pa = ferOp.mapping(map_type='PARITY', threshold=0.00000001) qubitOp_bi = ferOp.mapping(map_type='BRAVYI_KITAEV', threshold=0.00000001) # print out qubit hamiltonian in Pauli terms and exact solution qubitOp_jw.to_matrix() qubitOp_jw.chop(10**-10) print(qubitOp_jw.print_operators()) # Using exact eigensolver to get the smallest eigenvalue exact_eigensolver = ExactEigensolver(qubitOp_jw, k=1) ret = exact_eigensolver.run() print('The exact ground state energy is: {}'.format(ret['energy'])) # setup VQE # setup optimizer, use L_BFGS_B optimizer for example lbfgs = L_BFGS_B(maxfun=1000, factr=10, iprint=10) # setup variational form generator (generate trial circuits for VQE) var_form = RY(qubitOp_jw.num_qubits, 5, entangler_map = {0: [1], 1:[2], 2:[3]}) # setup VQE with operator, variational form, and optimizer vqe_algorithm = VQE(qubitOp_jw, var_form, lbfgs, 'matrix') backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, pass_manager=PassManager()) results = vqe_algorithm.run(quantum_instance) print("Minimum value: {}".format(results['eigvals'][0])) print("Parameters: {}".format(results['opt_params']))
https://github.com/bibscore/qiskit_kindergarten
bibscore
from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble from qiskit.tools.monitor import job_monitor import matplotlib as mpl # import basic plot tools from qiskit.visualization import plot_histogram, plot_bloch_multivector import numpy as np from numpy import pi qft_circuit = QuantumCircuit(3) qft_circuit.clear() #input state= 5 qft_circuit.x(0) qft_circuit.x(2) qft_circuit.h(0) qft_circuit.cp(pi/2,0,1) qft_circuit.cp(pi/4,0,2) qft_circuit.h(1) qft_circuit.cp(pi/2,1,2) qft_circuit.h(2) #qft_circuit.swap(0,2) qft_circuit.draw('mpl') #output is the bloch sphere representation in the fourier basis sim = Aer.get_backend("aer_simulator") qft_circuit_init = qft_circuit.copy() qft_circuit_init.save_statevector() statevector = sim.run(qft_circuit_init).result().get_statevector() plot_bloch_multivector(statevector) IBMQ.save_account('') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 2 and not b.configuration().simulator and b.status().operational==True)) print(backend) t_qc = transpile(qft_circuit, backend, optimization_level=3)#transpile=assembling the circuit and everything job = backend.run(t_qc)#backend means device job_monitor(job)
https://github.com/benkoehlL/Qiskit_Playground
benkoehlL
''' This program creates a .tex file of several classical logic gates ''' from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit import os import shutil logic_folder = os.getcwd() LaTex_folder_logic_gates = str(os.getcwd())+'/Latex_quantum_gates/logic_gates/' if not os.path.exists(LaTex_folder_logic_gates): os.makedirs(LaTex_folder_logic_gates) else: shutil.rmtree(LaTex_folder_logic_gates) os.makedirs(LaTex_folder_logic_gates) print(LaTex_folder_logic_gates) ## NOT gate q = QuantumRegister(1, name='q') c = ClassicalRegister(1, name='c') qc = QuantumCircuit(q,c) qc.x(q[0]) qc.measure(q[0],c[0]) LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit f_name = 'NOT_gate.tex' with open(LaTex_folder_logic_gates+f_name, 'w') as f: f.write(LaTex_code) ## AND gate q = QuantumRegister(3, name='q') qubit_state = '0' c = ClassicalRegister(1, name='c') qc = QuantumCircuit(q,c) qc.reset(q[2]) qc.ccx(q[0], q[1], q[2]) qc.measure(q[2], c[0]) LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit f_name = 'AND_gate.tex' with open(LaTex_folder_logic_gates+f_name, 'w') as f: f.write(LaTex_code) ## OR gate q = QuantumRegister(3, name='q') c = ClassicalRegister(1, name='c') qc = QuantumCircuit(q,c) qc.reset(q[2]) qc.ccx(q[0], q[1], q[2]) qc.cx(q[0],q[2]) qc.cx(q[1],q[2]) qc.measure(q[2],c[0]) LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit f_name = 'OR_gate.tex' with open(LaTex_folder_logic_gates+f_name, 'w') as f: f.write(LaTex_code) ## XOR gate q = QuantumRegister(3, name='q') c = ClassicalRegister(1, name='c') qc = QuantumCircuit(q,c) qc.reset(q[2]) qc.cx(q[0],q[2]) qc.cx(q[1],q[2]) qc.measure(q[2],c[0]) LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit f_name = 'XOR_gate.tex' with open(LaTex_folder_logic_gates+f_name, 'w') as f: f.write(LaTex_code) ## NOR gate q = QuantumRegister(3, name='q') c = ClassicalRegister(1, name='c') qc = QuantumCircuit(q,c) qc.reset(q[2]) qc.ccx(q[0], q[1], q[2]) qc.cx(q[0],q[2]) qc.cx(q[1],q[2]) qc.x(q[2]) qc.measure(q[2],c[0]) LaTex_code = qc.draw(output='latex_source', justify=None) # draw the circuit f_name = 'NOR_gate.tex' with open(LaTex_folder_logic_gates+f_name, 'w') as f: f.write(LaTex_code)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import transpile from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() qc = QuantumCircuit(2, 1) qc.h(0) qc.x(1) qc.cp(np.pi/4, 0, 1) qc.h(0) qc.measure([0], [0]) qc_basis = transpile(qc, backend) qc_basis.draw(output='mpl')
https://github.com/C2QA/bosonic-qiskit
C2QA
import math import qiskit from c2qa.circuit import CVCircuit from c2qa.kraus import PhotonLossNoisePass from c2qa.parameterized_unitary_gate import ParameterizedUnitaryGate def discretize_circuits( circuit: CVCircuit, segments_per_gate: int = 10, keep_state: bool = True, qubit:qiskit.circuit.quantumcircuit.QubitSpecifier = None, cbit: qiskit.circuit.quantumcircuit.QubitSpecifier = None, sequential_subcircuit: bool = False,): """ Discretize gates into a circuit into segments where each segment ends an indiviudal circuit. Useful for incrementally applying noise or animating the circuit. Args: circuit (CVCircuit): circuit to simulate and plot segments_per_gate (int, optional): Number of segments to split each gate into. Defaults to 10. keep_state (bool, optional): True if each gate segments builds on the previous gegment's state vector. False if each segment starts over from the beginning of the circuit. If True, it requires sequential simulation of each segment. qubit ([QubitSpecifier]): Qubit to measure, if performing Hadamard measure for use with cat states. Defaults to None. cbit ([QubitSpecifier]): Classical bit to measure into, if performing Hadamard measure for use with cat states. Defaults to None. sequential_subcircuit (bool, optional): boolean flag to animate subcircuits as one gate (False) or as sequential gates (True). Defautls to False. Returns: [list]: List of discretized Qiskit circuit """ sim_circuits = [] # Each segment will have its own circuit to simulate # base_circuit is copied each gate iteration to build circuit segments to simulate base_circuit = circuit.copy() base_circuit.data.clear() # Is this safe -- could we copy without data? for inst, qargs, cargs in circuit.data: # TODO - get qubit & cbit for measure instead of using parameters # qubit = xxx # cbit = yyy segments = __to_segments(inst, segments_per_gate, keep_state, sequential_subcircuit) for segment in segments: sim_circuit = base_circuit.copy() sim_circuit.append(instruction=segment, qargs=qargs, cargs=cargs) if qubit and cbit: # sim_circuit.barrier() sim_circuit.h(qubit) sim_circuit.measure(qubit, cbit) sim_circuits.append(sim_circuit) # Start with current circuit for the next segment base_circuit = sim_circuit return sim_circuits def discretize_single_circuit( circuit: CVCircuit, segments_per_gate: int = 10, epsilon: float = None, sequential_subcircuit: bool = False, statevector_per_segment: bool = False, statevector_label: str = "segment_", noise_passes = None ): """ Discretize gates into a circuit into segments within a single output circuit. Useful for incrementally applying noise or animating the circuit. Args: circuit (CVCircuit): circuit to simulate and plot segments_per_gate (int, optional): Number of segments to split each gate into. Defaults to 10. epsilon (float, optional): float value used to discretize, must specify along with kappa kappa (float, optional): float phton loss rate to determine discretization sice, must specify along with epsilon sequential_subcircuit (bool, optional): boolean flag to animate subcircuits as one gate (False) or as sequential gates (True). Defaults to False. statevector_per_segment (bool, optional): boolean flag to save a statevector per gate segment. True will call Qiskit save_statevector after each segment is simulated, creating statevectors labeled "segment_*" that can used after simulation. Defaults to False. statevector_label (str, optional): String prefix to use for the statevector saved after each segment noise_passes (list of Qiskit noise passes, optional): noise passes to apply Returns: discretized Qiskit circuit """ # discretized is a copy of the circuit as a whole. Each gate segment be added to simulate discretized = circuit.copy() discretized.data.clear() # Is this safe -- could we copy without data? if noise_passes: if not isinstance(noise_passes, list): noise_passes = [noise_passes] segment_count = 0 for inst, qargs, cargs in circuit.data: num_segments = segments_per_gate qargs_indices = [qubit._index for qubit in qargs] # FIXME -- is there a public API to get the qubit's index in Qiskit v1.0+? if noise_passes and not (isinstance(inst, qiskit.circuit.instruction.Instruction) and inst.name == "initialize"): # Don't discretize instructions initializing system state: noise_pass = None for current in noise_passes: if isinstance(current, PhotonLossNoisePass) and current.applies_to_instruction(inst, qargs_indices): noise_pass = current break if epsilon is not None and noise_pass is not None: # FIXME - which of the qumodes' loss rates and QumodeRegister's cutoff should we use? photon_loss_rate = noise_pass.photon_loss_rates_sec[0] num_segments = math.ceil((photon_loss_rate * noise_pass.duration_to_sec(inst) * circuit.get_qmr_cutoff(0)) / epsilon) segments = __to_segments(inst=inst, segments_per_gate=num_segments, keep_state=True, sequential_subcircuit=sequential_subcircuit) for segment in segments: discretized.append(instruction=segment, qargs=qargs, cargs=cargs) if statevector_per_segment: discretized.save_statevector(label=f"{statevector_label}{segment_count}") segment_count += 1 return discretized, segment_count def __to_segments(inst: qiskit.circuit.instruction.Instruction, segments_per_gate: int, keep_state: bool, sequential_subcircuit: bool): """Split the instruction into segments_per_gate segments""" if isinstance(inst, ParameterizedUnitaryGate): # print(f"Discretizing ParameterizedUnitaryGate {inst.name}") segments = __discretize_parameterized(inst, segments_per_gate, keep_state) # FIXME -- how to identify a gate that was made with QuantumCircuit.to_gate()? elif isinstance(inst.definition, qiskit.QuantumCircuit) and inst.name != "initialize" and inst.label != "cv_gate_from_matrix" and len(inst.decompositions) == 0: # Don't animate subcircuits initializing system state # print(f"Discretizing QuantumCircuit {inst.name}") segments = __discretize_subcircuit(inst.definition, segments_per_gate, keep_state, sequential_subcircuit) elif isinstance(inst, qiskit.circuit.instruction.Instruction) and inst.name != "initialize" and inst.label != "cv_gate_from_matrix" and len(inst.params) > 0: # Don't animate instructions initializing system state # print(f"Discretizing Instruction {inst.name}") segments = __discretize_instruction(inst, segments_per_gate, keep_state) else: # Else just "discretize" the instruction as a single segment # print(f"NOT discretizing {inst.name}") segments = [inst] return segments def __discretize_parameterized(inst: qiskit.circuit.instruction.Instruction, segments_per_gate: int, keep_state: bool, discretized_param_indices: list = []): """Split ParameterizedUnitaryGate into multiple segments""" segments = [] for index in range(1, segments_per_gate + 1): params = inst.calculate_segment_params( current_step=index, total_steps=segments_per_gate, keep_state=keep_state, ) duration, unit = inst.calculate_segment_duration( current_step=index, total_steps=segments_per_gate, keep_state=keep_state, ) # print(f"Discretized params {params} duration {duration} unit {unit}") segments.append( ParameterizedUnitaryGate( inst.op_func, params=params, cutoffs=inst.cutoffs, num_qubits=inst.num_qubits, label=inst.label, duration=duration, unit=unit, ) ) return segments def __discretize_subcircuit(subcircuit: qiskit.QuantumCircuit, segments_per_gate: int, keep_state: bool, sequential_subcircuit: bool): """Create a list of circuits where the entire subcircuit is converted into segments (vs a single instruction).""" segments = [] sub_segments = [] for inst, qargs, cargs in subcircuit.data: sub_segments.append((__to_segments(inst, segments_per_gate, keep_state, sequential_subcircuit), qargs, cargs)) if sequential_subcircuit: # Sequentially animate each gate within the subcircuit subcircuit_copy = subcircuit.copy() subcircuit_copy.data.clear() # Is this safe -- could we copy without data? for sub_segment in sub_segments: gates, gate_qargs, gate_cargs = sub_segment for gate in gates: subcircuit_copy.append(gate, gate_qargs, gate_cargs) segments.append(subcircuit) else: # Animate the subcircuit as one gate for segment in range(segments_per_gate): subcircuit_copy = subcircuit.copy() subcircuit_copy.data.clear() # Is this safe -- could we copy without data? for sub_segment, qargs, cargs in sub_segments: subcircuit_copy.append(sub_segment[segment], qargs, cargs) segments.append(subcircuit_copy) return segments def __discretize_instruction(inst: qiskit.circuit.instruction.Instruction, segments_per_gate: int, keep_state: bool): """Split Qiskit Instruction into multiple segments""" segments = [] for index in range(1, segments_per_gate + 1): params = inst.calculate_segment_params( current_step=index, total_steps=segments_per_gate, keep_state=keep_state, ) duration, unit = inst.calculate_segment_duration( current_step=index, total_steps=segments_per_gate, keep_state=keep_state, ) segments.append( qiskit.circuit.instruction.Instruction( name=inst.name, num_qubits=inst.num_qubits, num_clbits = inst.num_clbits, params=params, duration=duration, unit=unit, label=inst.label, ) ) return segments
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# If you introduce a list with less colors than bars, the color of the bars will # alternate following the sequence from the list. import numpy as np from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0, 1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) matrix = DensityMatrix(qc) plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
https://github.com/usamisaori/Grover
usamisaori
import qiskit from qiskit import QuantumCircuit from qiskit.visualization import plot_histogram import math import numpy as np from qiskit import execute, Aer simulator = Aer.get_backend('qasm_simulator') import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') state_0 = np.array([1, 0]) state_1 = np.array([0, 1]) from functools import reduce Dag = lambda matrix: matrix.conj().T Kron = lambda *matrices: reduce(np.kron, matrices) def getMeasurements(n): psi_0 = np.array([1.0, 0.0]) psi_1 = np.array([0.0, 1.0]) I = np.eye(2) M_0 = psi_0.reshape([2, 1]) @ psi_0.reshape([1, 2]).conj() M_1 = psi_1.reshape([2, 1]) @ psi_1.reshape([1, 2]).conj() M = [M_0, M_1] measurements = [] for i in range(2 ** n): binnum = bin(i)[2:].rjust(n, '0') temp = [] indices = map(lambda x: int(x), list(binnum)) for index in indices: temp.append(M[index]) measurements.append( Kron(*temp) ) return measurements def measure(M, state): return Dag(state) @ Dag(M) @ M @ state initState = Kron( state_0, state_0, state_0, state_0, state_0, state_0, state_0, state_0, state_0 ) H = np.array([[1,1], [1,-1]]) / (np.sqrt(2)) H_8 = Kron(H, H, H, H, H, H, H, H) H_9 = Kron(H, H, H, H, H, H, H, H, H) N = 2 ** 9 def createTargetState(n): states = [] s = bin(n)[2:].rjust(9, "0") for i in list(s): if i == '0': states.append(state_0) else: states.append(state_1) return Kron(*states) def createTargetStates(p): n = math.floor(p * N) state = createTargetState(0) for i in range(1, n): state = state + createTargetState(i) return state / (np.sqrt(n)) target_states = [ [createTargetStates(0.05), 0.05], # 0.05 [createTargetStates(0.1), 0.1], # 0.1 [createTargetStates(0.15), 0.15], # 0.15 [createTargetStates(0.2), 0.2], # 0.2 [createTargetStates(0.25), 0.25], # 0.25 [createTargetStates(0.3), 0.3], # 0.3 [createTargetStates(0.35), 0.35], # 0.35 [createTargetStates(0.4), 0.4], # 0.4 [createTargetStates(0.45), 0.45], # 0.45 [createTargetStates(0.5), 0.5], # 0.5 [createTargetStates(0.55), 0.55], # 0.55 [createTargetStates(0.6), 0.6], # 0.6 [createTargetStates(0.65), 0.65], # 0.65 [createTargetStates(0.7), 0.7], # 0.7 [createTargetStates(0.75), 0.75], # 0.75 [createTargetStates(0.8), 0.8], # 0.8 [createTargetStates(0.85), 0.85], # 0.85 [createTargetStates(0.9), 0.9], # 0.9 [createTargetStates(0.95), 0.95], # 0.95 [createTargetStates(1), 1] # 1 ] def createOriginalOracle(target_state): O = np.eye(N) - 2 * ( Dag(target_state).reshape(N, 1) @ target_state.reshape(1, N) ) return O def createOriginalDiffuser(): R = 2 * ( Dag(initState).reshape(N, 1) @ initState.reshape(1, N) ) - np.eye(N) return H_9 @ R @ Dag(H_9) def createHalfPIOracle(target_state): alpha = np.pi / 2 alpha_phase = np.exp(alpha * 1j) # Oracle = I - (1 - e^(αi))|target><target| O = np.eye(N) - (1 - alpha_phase) * \ ( Dag(target_state).reshape(N, 1) @ target_state.reshape(1, N) ) return O def createHalfPIDiffuser(): beta = -np.pi / 2 beta_phase = np.exp(beta * 1j) # R = (1 - e^(βi))|0><0| + e^(βi)I R = (1 - beta_phase) * ( Dag(initState).reshape(N, 1) @ initState.reshape(1, N) ) + beta_phase * np.eye(N) return H_9 @ R @ Dag(H_9) def createOneTenthPIOracle(target_state): alpha = np.pi / 10 alpha_phase = np.exp(alpha * 1j) # Oracle = I - (1 - e^(αi))|target><target| O = np.eye(N) - (1 - alpha_phase) * \ ( Dag(target_state).reshape(N, 1) @ target_state.reshape(1, N) ) return O def createOneTenthPIDiffuser(): beta = -np.pi / 10 beta_phase = np.exp(beta * 1j) # R = (1 - e^(βi))|0><0| + e^(βi)I R = (1 - beta_phase) * ( Dag(initState).reshape(N, 1) @ initState.reshape(1, N) ) + beta_phase * np.eye(N) return H_9 @ R @ Dag(H_9) def createYouneOracle(n): O = np.eye(N) for i in range(n): O[i][i] = 0 O[i][i + N // 2] = 1 O[i + N // 2][i + N // 2] = 0 O[i + N // 2][i] = 1 return O def createYouneDiffuser(): R = (2 * Dag(initState).reshape(N, 1) @ initState.reshape(1, N) - np.eye(N)) return Kron(np.eye(2), H_8) @ R @ Dag(Kron(np.eye(2), H_8)) measurements = getMeasurements(9) # test: one grover iteration x_o = [] y_o = [] for target_state, p in target_states: n = math.floor(p * N) O = createOriginalOracle(target_state) diff = createOriginalDiffuser() final_state = diff @ O @ H_9 @ initState probability = 0.0 for i in range(N): if i < n: probability = probability + measure(measurements[i], final_state) # print(f'p={p}, probability={probability}') x_o.append(p) y_o.append(probability) plt.title("Original Grover - apply one iterator") plt.scatter(x_o, y_o, color="#66CCCC") # test: best probability x_o_best = [] y_o_best = [] for target_state, p in target_states: n = math.floor(p * N) O = createOriginalOracle(target_state) diff = createOriginalDiffuser() final_state = H_9 @ initState theta = math.degrees( math.asin(math.sqrt(p)) ) k_tilde = math.floor( 180 / (4 * theta) - 0.5 ) for i in range(k_tilde): final_state = diff @ O @ final_state probability = 0.0 for i in range(N): if i < n: probability = probability + measure(measurements[i], final_state) final_state = diff @ O @ final_state probability2 = 0.0 for i in range(N): if i < n: probability2 = probability2 + measure(measurements[i], final_state) # print(f'p={p}, probability={probability}') x_o_best.append(p) y_o_best.append(max(probability, probability2)) plt.title("Original Grover - best Probability") x = np.arange(-0,1,0.01) y = 1 - x plt.plot(x, y, ls='--', color="#FFCC00") plt.ylim(0, 1.05) plt.scatter(x_o_best, y_o_best, color="#66CCCC") # test: one grover iteration x_half_pi = [] y_half_pi= [] for target_state, p in target_states: n = math.floor(p * N) O = createHalfPIOracle(target_state) diff = createHalfPIDiffuser() final_state = diff @ O @ H_9 @ initState probability = 0.0 for i in range(N): if i < n: probability = probability + measure(measurements[i], final_state) # print(f'p={p}, probability={probability}') x_half_pi.append(p) y_half_pi.append(probability) plt.title("pi/2 Grover - apply one iterator") plt.scatter(x_half_pi, y_half_pi, color="#66CCCC") # one grover iteration - pi/2 vs origin fig, ax = plt.subplots() plt.title("Apply one iteration") plt.axvline(1/3, linestyle='--', color="#FFCCCC", label="t/N = 1/3") plt.axhline(0.925, linestyle='--', color="#FFCC00", label="P=0.925") plt.scatter(x_o, y_o, color="#66CCCC", label="Original Grover") plt.scatter(x_half_pi, y_half_pi, color="#FF6666", label="pi/2 phase based Grover") ax.legend() # test: one grover iteration x_ot_pi = [] y_ot_pi= [] for target_state, p in target_states: n = math.floor(p * N) O = createOneTenthPIOracle(target_state) diff = createOneTenthPIDiffuser() final_state = diff @ O @ H_9 @ initState probability = 0.0 for i in range(N): if i < n: probability = probability + measure(measurements[i], final_state) # print(f'p={p}, probability={probability}') x_ot_pi.append(p) y_ot_pi.append(probability) plt.title("0.1pi Grover - apply one iteration") plt.scatter(x_ot_pi, y_ot_pi, color="#66CCCC") # test: best probability x_ot_best = [] y_ot_best = [] diff = createOneTenthPIDiffuser() for target_state, p in target_states: n = math.floor(p * N) O = createOneTenthPIOracle(target_state) # diff = createOneTenthPIDiffuser() final_state = H_9 @ initState p_best = 0.0 k_tilde = math.floor( 5 * np.sqrt(N) ) for i in range(k_tilde): final_state = diff @ O @ final_state probability = 0.0 for i in range(N): if i < n: probability = probability + measure(measurements[i], final_state) p_best = max(p_best, probability) # print(f'p={p}, probability={probability}') x_ot_best.append(p) y_ot_best.append(p_best) plt.title("0.1pi Grover - best Probability") plt.ylim(0, 1) plt.scatter(x_ot_best, y_ot_best, color="#66CCCC") # best probability - 0.1pi vs origin fig, ax = plt.subplots() plt.title("Best Probability") x = np.arange(-0,1,0.01) y = 1 - x plt.plot(x, y, ls='--', color="#FFCC00") plt.ylim(0, 1.05) plt.scatter(x_o_best, y_o_best, color="#66CCCC", label="Original Grover") plt.scatter(x_ot_best, y_ot_best, color="#FF6666", label="0.1pi phase based Grover") ax.legend() # test: best probability x_y_best = [] y_y_best = [] for _, p in target_states: n = math.floor(p * (N // 2)) O = createYouneOracle(n) diff = createYouneDiffuser() final_state = Kron( np.eye(2), H_8) @ initState p_best = 0.0 k_tilde = math.floor(np.pi / (2 * np.sqrt(2)) * np.sqrt((N // 2) / n)) for i in range(k_tilde): final_state = diff @ O @ final_state probability = 0.0 for i in range(N // 2): if i < n: probability = probability + measure(measurements[i], final_state) + measure(measurements[i + N // 2], final_state) # print(f'p={p}, probability={probability}') x_y_best.append(p) y_y_best.append(probability) fig, ax = plt.subplots() plt.title("Best Probability") x = np.arange(-0, 1, 0.01) y = 1 - x plt.plot(x, y, ls='--', color="#FFCC00") plt.axhline(0.8472, linestyle='--', color="#99CCFF", label="P=0.8472") plt.axvline(0.308, linestyle='--', color="#FFCCCC", label="P=0.308") plt.ylim(0, 1.05) plt.scatter(x_y_best, y_y_best, color="#FF6666", label="Youne") plt.scatter(x_o_best, y_o_best, color="#66CCCC", label="Original Grover") ax.legend()
https://github.com/Axect/QuantumAlgorithms
Axect
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt def circuit(alice): e = QuantumRegister(2, name='e') a = QuantumRegister(1, name='a') b = QuantumRegister(1, name='b') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(e, a, b, c, name='circuit') # Initialize Target qubit qc.initialize(alice / np.linalg.norm(alice), e) qc.barrier() # Create Bell pair qc.h(a) qc.cx(a, b) qc.barrier() # Write target qubit to Bell pair qc.cz(e[0], a) qc.cx(e[1], a) qc.barrier() # Decoding qc.cx(a, b) qc.h(a) qc.measure(a, c[1]) qc.measure(b, c[0]) backend = Aer.get_backend('qasm_simulator') return qc, execute(qc, backend).result().get_counts() qc, counts = circuit([1,0,0,1]) qc.draw(output='mpl', style='iqx') plot_histogram(counts)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ import logging import functools import numpy as np from qiskit import ClassicalRegister, QuantumCircuit from qiskit.aqua.algorithms.adaptive.vq_algorithm import VQAlgorithm from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.utils.backend_utils import is_aer_statevector_backend from qiskit.aqua.utils import find_regs_by_name logger = logging.getLogger(__name__) class VQE(VQAlgorithm): """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ CONFIGURATION = { 'name': 'VQE', 'description': 'VQE Algorithm', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'vqe_schema', 'type': 'object', 'properties': { 'operator_mode': { 'type': 'string', 'default': 'matrix', 'oneOf': [ {'enum': ['matrix', 'paulis', 'grouped_paulis']} ] }, 'initial_point': { 'type': ['array', 'null'], "items": { "type": "number" }, 'default': None }, 'max_evals_grouped': { 'type': 'integer', 'default': 1 } }, 'additionalProperties': False }, 'problems': ['energy', 'ising'], 'depends': [ {'pluggable_type': 'optimizer', 'default': { 'name': 'L_BFGS_B' } }, {'pluggable_type': 'variational_form', 'default': { 'name': 'RYRZ' } }, ], } def __init__(self, operator, var_form, optimizer, operator_mode='matrix', initial_point=None, max_evals_grouped=1, aux_operators=None, callback=None): """Constructor. Args: operator (Operator): Qubit operator operator_mode (str): operator mode, used for eval of operator var_form (VariationalForm): parametrized variational form. optimizer (Optimizer): the classical optimization algorithm. initial_point (numpy.ndarray): optimizer initial point. max_evals_grouped (int): max number of evaluations performed simultaneously aux_operators (list of Operator): Auxiliary operators to be evaluated at each eigenvalue callback (Callable): a callback that can access the intermediate data during the optimization. Internally, four arguments are provided as follows the index of evaluation, parameters of variational form, evaluated mean, evaluated standard devation. """ self.validate(locals()) super().__init__(var_form=var_form, optimizer=optimizer, cost_fn=self._energy_evaluation, initial_point=initial_point) self._optimizer.set_max_evals_grouped(max_evals_grouped) self._callback = callback if initial_point is None: self._initial_point = var_form.preferred_init_points self._operator = operator self._operator_mode = operator_mode self._eval_count = 0 if aux_operators is None: self._aux_operators = [] else: self._aux_operators = [aux_operators] if not isinstance(aux_operators, list) else aux_operators logger.info(self.print_settings()) @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance. Args: params (dict): parameters dictionary algo_input (EnergyInput): EnergyInput instance Returns: VQE: vqe object """ if algo_input is None: raise AquaError("EnergyInput instance is required.") operator = algo_input.qubit_op vqe_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) operator_mode = vqe_params.get('operator_mode') initial_point = vqe_params.get('initial_point') max_evals_grouped = vqe_params.get('max_evals_grouped') # Set up variational form, we need to add computed num qubits # Pass all parameters so that Variational Form can create its dependents var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM) var_form_params['num_qubits'] = operator.num_qubits var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM, var_form_params['name']).init_params(params) # Set up optimizer opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER) optimizer = get_pluggable_class(PluggableType.OPTIMIZER, opt_params['name']).init_params(params) return cls(operator, var_form, optimizer, operator_mode=operator_mode, initial_point=initial_point, max_evals_grouped=max_evals_grouped, aux_operators=algo_input.aux_ops) @property def setting(self): """Prepare the setting of VQE as a string.""" ret = "Algorithm: {}\n".format(self._configuration['name']) params = "" for key, value in self.__dict__.items(): if key != "_configuration" and key[0] == "_": if "initial_point" in key and value is None: params += "-- {}: {}\n".format(key[1:], "Random seed") else: params += "-- {}: {}\n".format(key[1:], value) ret += "{}".format(params) return ret def print_settings(self): """ Preparing the setting of VQE into a string. Returns: str: the formatted setting of VQE """ ret = "\n" ret += "==================== Setting of {} ============================\n".format(self.configuration['name']) ret += "{}".format(self.setting) ret += "===============================================================\n" ret += "{}".format(self._var_form.setting) ret += "===============================================================\n" ret += "{}".format(self._optimizer.setting) ret += "===============================================================\n" return ret def construct_circuit(self, parameter, backend=None, use_simulator_operator_mode=False): """Generate the circuits. Args: parameters (numpy.ndarray): parameters for variational form. backend (qiskit.BaseBackend): backend object. use_simulator_operator_mode (bool): is backend from AerProvider, if True and mode is paulis, single circuit is generated. Returns: [QuantumCircuit]: the generated circuits with Hamiltonian. """ input_circuit = self._var_form.construct_circuit(parameter) if backend is None: warning_msg = "Circuits used in VQE depends on the backend type, " from qiskit import BasicAer if self._operator_mode == 'matrix': temp_backend_name = 'statevector_simulator' else: temp_backend_name = 'qasm_simulator' backend = BasicAer.get_backend(temp_backend_name) warning_msg += "since operator_mode is '{}', '{}' backend is used.".format( self._operator_mode, temp_backend_name) logger.warning(warning_msg) circuit = self._operator.construct_evaluation_circuit(self._operator_mode, input_circuit, backend, use_simulator_operator_mode) return circuit def _eval_aux_ops(self, threshold=1e-12, params=None): if params is None: params = self.optimal_params wavefn_circuit = self._var_form.construct_circuit(params) circuits = [] values = [] params = [] for operator in self._aux_operators: if not operator.is_empty(): temp_circuit = QuantumCircuit() + wavefn_circuit circuit = operator.construct_evaluation_circuit(self._operator_mode, temp_circuit, self._quantum_instance.backend, self._use_simulator_operator_mode) params.append(operator.aer_paulis) else: circuit = None circuits.append(circuit) if len(circuits) > 0: to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, [c for c in circuits if c is not None]) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': params, 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for operator, circuit in zip(self._aux_operators, circuits): if circuit is None: mean, std = 0.0, 0.0 else: mean, std = operator.evaluate_with_result(self._operator_mode, circuit, self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean = mean.real if abs(mean.real) > threshold else 0.0 std = std.real if abs(std.real) > threshold else 0.0 values.append((mean, std)) if len(values) > 0: aux_op_vals = np.empty([1, len(self._aux_operators), 2]) aux_op_vals[0, :] = np.asarray(values) self._ret['aux_ops'] = aux_op_vals def _run(self): """ Run the algorithm to compute the minimum eigenvalue. Returns: Dictionary of results """ if not self._quantum_instance.is_statevector and self._operator_mode == 'matrix': logger.warning('Qasm simulation does not work on {} mode, changing ' 'the operator_mode to "paulis"'.format(self._operator_mode)) self._operator_mode = 'paulis' self._use_simulator_operator_mode = \ is_aer_statevector_backend(self._quantum_instance.backend) \ and self._operator_mode != 'matrix' self._quantum_instance.circuit_summary = True self._eval_count = 0 self._ret = self.find_minimum(initial_point=self.initial_point, var_form=self.var_form, cost_fn=self._energy_evaluation, optimizer=self.optimizer) if self._ret['num_optimizer_evals'] is not None and self._eval_count >= self._ret['num_optimizer_evals']: self._eval_count = self._ret['num_optimizer_evals'] self._eval_time = self._ret['eval_time'] logger.info('Optimization complete in {} seconds.\nFound opt_params {} in {} evals'.format( self._eval_time, self._ret['opt_params'], self._eval_count)) self._ret['eval_count'] = self._eval_count self._ret['energy'] = self.get_optimal_cost() self._ret['eigvals'] = np.asarray([self.get_optimal_cost()]) self._ret['eigvecs'] = np.asarray([self.get_optimal_vector()]) self._eval_aux_ops() return self._ret # This is the objective function to be passed to the optimizer that is uses for evaluation def _energy_evaluation(self, parameters): """ Evaluate energy at given parameters for the variational form. Args: parameters (numpy.ndarray): parameters for variational form. Returns: float or list of float: energy of the hamiltonian of each parameter. """ num_parameter_sets = len(parameters) // self._var_form.num_parameters circuits = [] parameter_sets = np.split(parameters, num_parameter_sets) mean_energy = [] std_energy = [] for idx in range(len(parameter_sets)): parameter = parameter_sets[idx] circuit = self.construct_circuit(parameter, self._quantum_instance.backend, self._use_simulator_operator_mode) circuits.append(circuit) to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, circuits) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': [self._operator.aer_paulis], 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for idx in range(len(parameter_sets)): mean, std = self._operator.evaluate_with_result( self._operator_mode, circuits[idx], self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean_energy.append(np.real(mean)) std_energy.append(np.real(std)) self._eval_count += 1 if self._callback is not None: self._callback(self._eval_count, parameter_sets[idx], np.real(mean), np.real(std)) logger.info('Energy evaluation {} returned {}'.format(self._eval_count, np.real(mean))) return mean_energy if len(mean_energy) > 1 else mean_energy[0] def get_optimal_cost(self): if 'opt_params' not in self._ret: raise AquaError("Cannot return optimal cost before running the algorithm to find optimal params.") return self._ret['min_val'] def get_optimal_circuit(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal circuit before running the algorithm to find optimal params.") return self._var_form.construct_circuit(self._ret['opt_params']) def get_optimal_vector(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal vector before running the algorithm to find optimal params.") qc = self.get_optimal_circuit() if self._quantum_instance.is_statevector: ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_statevector(qc, decimals=16) else: c = ClassicalRegister(qc.width(), name='c') q = find_regs_by_name(qc, 'q') qc.add_register(c) qc.barrier(q) qc.measure(q, c) ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_counts(qc) return self._ret['min_vector'] @property def optimal_params(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal params before running the algorithm.") return self._ret['opt_params']
https://github.com/GroenteLepel/qiskit-quantum-knn
GroenteLepel
"""Construction of a QkNN QuantumCircuit.""" import logging, warnings from typing import List, Union import numpy as np import qiskit as qk import qiskit.extensions.quantum_initializer as qi import qiskit.circuit as qcirc import qiskit.circuit.instruction as qinst import qiskit_quantum_knn.qknn.quantumgates as gates logger = logging.getLogger(__name__) def create_qknn(state_to_classify: Union[List, np.ndarray], classified_states: Union[List, np.ndarray], add_measurement: bool = False) -> qk.QuantumCircuit: """ Construct one QkNN QuantumCircuit. This method creates a circuit to perform distance measurements using quantum fidelity as distance metric :afham2020:`Afham et al. (2020)`. It initialises one register with a state to classify, and uses an Oracle to act as QRAM to hold the training data. This Oracle writes all training data in superposition to a register. After that, a swap-test circuit :buhrman2020:`Buhrman et al. (2020)` is created to perform the fidelity measurement. Example: Creating a circuit with simple data. .. jupyter-execute:: from qiskit_quantum_knn.qknn.qknn_construction import create_qknn test_data = [1, 0] train_data = [ [1, 0], [0, 1] ] circuit = create_qknn(test_data, train_data, add_measurement=True) print(circuit.draw()) Args: state_to_classify (numpy.ndarray): array of dimension N complex values describing the state to classify via KNN. classified_states (numpy.ndarray): array containing M training samples of dimension N. add_measurement (bool): controls if measurements must be added to the classical registers. Returns: QuantumCircuit: the constructed circuit. """ oracle = create_oracle(classified_states) return construct_circuit( state_to_classify, oracle, add_measurement ) def construct_circuit(state_to_classify: np.ndarray, oracle: qinst.Instruction, add_measurement: bool) -> qk.QuantumCircuit: r"""Setup for a QkNN QuantumCircuit. Constructs the QkNN QuantumCircuit according to the stepwise "instructions" in :afham2020:`Afham et al. (2020)`. These instructions are\: 1. Initialisation: creates the registers and applies the unclassified datum :math:`\psi` (see :py:func:`initialise_qknn`); 2. State transformation: applies :math:`H`-gates and the Oracle :math:`\mathcal{W}` to the circuit, and applies the :math:`SWAP`-test (see :py:func:`state_transformation`); 3. Adding measurments: add the measurement gates to the control and computational basis (see :py:func:`add_measurements`). Args: state_to_classify (numpy.ndarray): array of dimension N complex values describing the state to classify via KNN. oracle (qiskit Instruction): oracle :math:`\mathcal{W}` for applying training data. add_measurement (bool): controls if measurements must be added to the classical registers. Raises: ValueError: If the number of data points in :attr:`state_to_classify` is more than 2. ValueError: If the length of the vectors in the :attr:`classified_states` and/or test data are not a positive power of 2. Returns: QuantumCircuit: constructed circuit. """ if len(np.array(state_to_classify).shape) != 1: raise ValueError( f"Please only one data point to classify. Number of data points " f"provided is: {np.array(state_to_classify).shape[0]}. " ) # get the dimensions of the state to classify state_dimension = len(state_to_classify) # get the number of qubits for the registers containing the state to # classify and the number of train samples n = np.log2(state_dimension) # n qubits for describing states m = oracle.num_qubits - n # n qubits for computational basis # Check if param is a power of 2 if (n == 0 or not n.is_integer()) and (m == 0 or not m.is_integer()): raise ValueError( "Desired statevector length not a positive power of 2." ) # step 1: initialise (creates registers, sets qubits to |0> or the # state to classify qknn_circ = initialise_qknn(n, m, state_to_classify) # step 2: state trans. (applies oracle) qknn_circ = state_transformation(qknn_circ, oracle) # step 3: adds the measurement gates if add_measurement: qknn_circ = add_measurements(qknn_circ) logger.debug(f"Final circuit:\n{qknn_circ.draw(fold=90)}") return qknn_circ # noinspection PyTypeChecker def create_oracle(train_data: Union[List, np.ndarray]) -> qinst.Instruction: r"""Create an Oracle to perform as QRAM. The oracle works as follows\: .. math:: \mathcal{W}|i\rangle |0\rangle = |i\rangle |\phi_i\rangle where the equation is from :afham2020:`Afham et al. (2020)`. This oracle acts as QRAM, which holds the training dataset :math:`\Phi` to assign to the register for performing a swap test. It is located in the center of the quantum circuit (see :py:func:`create_qknn`). Notes: The Oracle works with controlled initializers which check the state of the computational basis. The computational basis is described by :math:`|i\rangle`, where :math:`i` is any real number, which is then described by qubits in binary. To check the the state of the computational basis, a network of :math:`X`-gates is created to bring the computational basis systematically into all possible states. If all qubits in the register are :math:`|1\rangle`, the datum is assigned via the initialize. Where to apply the :math:`X`-gates is determined by :py:func:`where_to_apply_x`. Example: Creating a simple oracle for dataset with 4 points. .. jupyter-execute:: from qiskit_quantum_knn.qknn.qknn_construction import create_oracle train_data = [ [1, 0], [1, 0], [0, 1], [0, 1] ] oracle = create_oracle(train_data) print(oracle.definition.draw()) Args: train_data (array-like): List of vectors with dimension ``len(r_train)`` to initialize ``r_train`` to. Returns: circuit.instruction.Instruction: Instruction of the Oracle. """ # get shape of training data train_shape = np.shape(train_data) # check if training data is two dimensional if len(train_shape) != 2: raise ValueError("Provided training data not 2-dimensional. Provide" "a matrix of shape n_samples x dim") # get the log2 values of the number of samples # m from training data and dimension of vectors n m, n = np.log2(train_shape) # check if m should be ceiled. if not m.is_integer(): warnings.warn("Number of training states not a positive power of 2," "adding extra qubit to comply.") m = np.ceil(m) # create quantum registers r_train = qk.QuantumRegister(n, name='train_states') r_comp_basis = qk.QuantumRegister(m, name='comp_basis') # initialize the list containing the controlled inits, which will assign # each training state i to r_train (so should be as long as number of # samples) controlled_inits = [qcirc.ControlledGate] * train_shape[0] # create an empty circuit with the registers oracle_circ = qk.QuantumCircuit( r_train, r_comp_basis, name='oracle' ) # create all the controlled inits for each vector in train data for i, train_state in enumerate(train_data): controlled_inits[i] = \ gates.controlled_initialize( r_train, train_state, num_ctrl_qubits=r_comp_basis.size, name="phi_{}".format(i) ) # apply all the x-gates and controlled inits to the circuit # define the length of the binary string which will translate |i> bin_number_length = r_comp_basis.size where_x = where_to_apply_x(bin_number_length) for i, (c_init, x_idx) in enumerate(zip(controlled_inits, where_x)): # represent i in binary number with length bin_number_length, so # leading zeros are included logger.debug(f"applying x-gates to: {x_idx}") # apply the x-gates oracle_circ.x(r_comp_basis[x_idx]) # apply the controlled init oracle_circ.append(c_init, r_comp_basis[:] + r_train[:]) logger.debug(f"Created oracle as:\n{oracle_circ.draw()}") return oracle_circ.to_instruction() def where_to_apply_x(bin_number_length: int) -> List: r""" Create an array to apply :math:`X`-gates systematically to create all possible register combinations. This method returns the indices on where to apply :math:`X`-gates on a quantum register with ``n`` qubits to generate all possible binary numbers on that register. Example: Suppose we have a register with 2 qubits. We want to make sure we check all possible states this register can be in, such that a data point can be assigned. A register with 2 qubits can be in 4 states: .. math:: |0\rangle = |00\rangle, |1\rangle = |01\rangle, |2\rangle = |10\rangle, |3\rangle = |11\rangle So to apply :math:`\phi_1`, the register must be in state :math:`|01\rangle`, and we need to apply the :math:`X`-gate only to the first qubit. The state becomes :math:`|11\rangle` and the controlled initialise will trigger. Because the algorithm will check for all states in succession, this can be reduced to prevent double placements of :math:`X`-gates, and it determines where to place the :math:`X`-gates via: .. math:: |i-1\rangle XOR |i\rangle A full list of all these configurations is created by this method\: .. jupyter-execute:: from qiskit_quantum_knn.qknn.qknn_construction import where_to_apply_x num_qubits = 2 where_to_apply_x(num_qubits) Args: bin_number_length (int): the length of the highest binary value (or the number of qubits). Returns: List: All possible combinations. A length ``2**bin_number_length`` of the indices of the qubits where the :math:`X`-gate must be applied to. """ powers_of_two = 2 ** np.arange(bin_number_length) indices = \ [ [ ind for ind, v in enumerate(powers_of_two) if v & (pos ^ (pos - 1)) == v ] for pos in range(2 ** bin_number_length) ] return indices def initialise_qknn(log2_dim: int, log2_n_samps: int, test_state: np.ndarray) -> qk.QuantumCircuit: r"""Creates the registers and applies the unclassified datum :math:`\psi`. Coincides with Step 1: the "initialisation" section in :afham2020:`Afham et al. (2020)`. Initialises a QuantumCircuit with 1 + 2n + m qubits (n: log2_dimension, m: log2_samples) for a QkNN network, where qubits 1 till n are initialised in some state psi ( state_to_classify). Example: Set up the scaffolds for a QkNN :class:`QuantumCircuit`. .. jupyter-execute:: from qiskit_quantum_knn.qknn.qknn_construction import initialise_qknn n_dim_qubits = 1 n_samps_qubits = 1 test_state = [0, 1] init_circ = initialise_qknn(n_dim_qubits, n_samps_qubits, test_state) print(init_circ.draw()) Args: log2_dim (int): int, log2 value of the dimension of the test and train states. log2_n_samps (int): int, log2 value of the number of training samples M. test_state (numpy.ndarray): 2 ** log2_dimension complex values to initialise the r_1 test state in (psi). Returns: QuantumCircuit: The initialised circuit. """ if len(test_state) != 2 ** log2_dim: raise ValueError( "Dimensionality of test state or provided dimension not correct;" " test state dim is {0:d}, and dimension given is {1:d}".format( len(test_state), 2 ** log2_dim ) ) # register for control qubit r_0 = qk.QuantumRegister(1, name='control') # register for test state r_1 = qk.QuantumRegister(log2_dim, name='state_to_classify') # register for train state r_2 = qk.QuantumRegister(log2_dim, name='train_states') # register for computational basis r_3 = qk.QuantumRegister(log2_n_samps, name='comp_basis') # classical register for measuring the control and computational basis c_0 = qk.ClassicalRegister(r_0.size, name='meas_control') c_1 = qk.ClassicalRegister(r_3.size, name="meas_comp_basis") init_circ = qk.QuantumCircuit(r_0, r_1, r_2, r_3, c_0, c_1) init = qi.Isometry(test_state, 0, 0) init.name = "init test state" init_circ.append(init, r_1) init_circ.barrier() logger.debug(f"Initialised circuit as:\n{init_circ.draw()}") return init_circ def state_transformation(qknn_circ: qk.QuantumCircuit, oracle: qinst.Instruction) -> qk.QuantumCircuit: r"""applies :math:`H`-gates and the Oracle :math:`\mathcal{W}` to the circuit, and applies the :math:`SWAP`-test. Coincides with Step 2: the "state transformation" section from :afham2020:`Afham et al. (2020)`. Applies Hadamard gates and Quantum Oracle to bring :math:`r_1, r_2, r_3, r_4` in the desired states. Note: This needs the :class:`QuantumCircuit` created by :py:func:`initialise_qknn` as a parameter in order to function properly. Example: Apply the oracle and test data in a :class:`QuantumCircuit`. .. jupyter-execute:: from qiskit_quantum_knn.qknn.qknn_construction import create_oracle, \ initialise_qknn, state_transformation n_dim_qubits = 1 # must be log(len(test_state)) n_samps_qubits = 1 # must be log(len(train_data)) test_state = [0, 1] train_data = [ [1, 0], [0, 1] ] oracle = create_oracle(train_data) init_circ = initialise_qknn(n_dim_qubits, n_samps_qubits, test_state) state_circ = state_transformation(init_circ, oracle) print(state_circ.draw()) Args: qknn_circ (QuantumCircuit): has been initialised according to initialise_qknn(). oracle (qiskit Instruction): oracle W|i>|0> = W|i>|phi_i> for applying training data. Returns: QuantumCircuit: the transformed :class:`QuantumCircuit`. """ # initialising registers for readability [control, test_register, train_register, comp_basis] = qknn_circ.qregs # perform equation 13 from Afham; Afham, Afrad; Goyal, Sandeep K. (2020). qknn_circ.h(control) qknn_circ.h(comp_basis) # perform equation 15 # append to circuit qknn_circ.append(oracle, train_register[:] + comp_basis[:]) # controlled swap for psi_bit, phi_bit in zip(test_register, train_register): qknn_circ.cswap(control, psi_bit, phi_bit) # final Hadamard gate qknn_circ.h(control) # barrier to round it of qknn_circ.barrier() logger.info(f"transformed registers to circuit:\n{qknn_circ.draw()}") return qknn_circ def add_measurements(qknn_circ: qk.QuantumCircuit) -> qk.QuantumCircuit: """Adds measurement gates to the control and computational basis. Performs the third and final step of the building of the QkNN circuit by adding measurements to the control qubit and the computational basis. Note: This needs the :class:`QuantumCircuit` created by :py:func:`state_transformation` as a parameter in order to function properly. Example: .. jupyter-execute:: from qiskit_quantum_knn.qknn.qknn_construction import create_oracle, \ initialise_qknn, state_transformation, add_measurements n_dim_qubits = 1 # must be log(len(test_state)) n_samps_qubits = 1 # must be log(len(train_data)) test_state = [0, 1] train_data = [ [1, 0], [0, 1] ] oracle = create_oracle(train_data) init_circ = initialise_qknn(n_dim_qubits, n_samps_qubits, test_state) state_circ = state_transformation(init_circ, oracle) final_circ = add_measurements(state_circ) print(final_circ.draw()) Args: qknn_circ (qk.QuantumCircuit): has been build up by first applying initialise_qknn() and state_transformation(). Returns: QuantumCircuit: the :class:`QuantumCircuit` with measurements applied. """ comp_basis_creg = qknn_circ.cregs[-1] comp_basis_qreg = qknn_circ.qregs[-1] qknn_circ.measure(qknn_circ.qregs[0], qknn_circ.cregs[0]) for qbit, cbit in zip(comp_basis_qreg, reversed(comp_basis_creg)): qknn_circ.measure(qbit, cbit) logger.debug("Added measurements.") return qknn_circ
https://github.com/AnikenC/JaxifiedQiskit
AnikenC
# All Imports import numpy as np import matplotlib.pyplot as plt import sympy as sym import qiskit from qiskit import pulse from qiskit_dynamics import Solver, DynamicsBackend from qiskit_dynamics.pulse import InstructionToSignals from qiskit_dynamics.array import Array from qiskit.quantum_info import Statevector, DensityMatrix, Operator from qiskit.circuit.parameter import Parameter import jax import jax.numpy as jnp from jax import jit, vmap, block_until_ready, config import chex from typing import Optional, Union Array.set_default_backend('jax') config.update('jax_enable_x64', True) config.update('jax_platform_name', 'cpu') # Constructing a Two Qutrit Hamiltonian dim = 3 v0 = 4.86e9 anharm0 = -0.32e9 r0 = 0.22e9 v1 = 4.97e9 anharm1 = -0.32e9 r1 = 0.26e9 J = 0.002e9 a = np.diag(np.sqrt(np.arange(1, dim)), 1) adag = np.diag(np.sqrt(np.arange(1, dim)), -1) N = np.diag(np.arange(dim)) ident = np.eye(dim, dtype=complex) full_ident = np.eye(dim**2, dtype=complex) N0 = np.kron(ident, N) N1 = np.kron(N, ident) a0 = np.kron(ident, a) a1 = np.kron(a, ident) a0dag = np.kron(ident, adag) a1dag = np.kron(adag, ident) static_ham0 = 2 * np.pi * v0 * N0 + np.pi * anharm0 * N0 * (N0 - full_ident) static_ham1 = 2 * np.pi * v1 * N1 + np.pi * anharm1 * N1 * (N1 - full_ident) static_ham_full = static_ham0 + static_ham1 + 2 * np.pi * J * ((a0 + a0dag) @ (a1 + a1dag)) drive_op0 = 2 * np.pi * r0 * (a0 + a0dag) drive_op1 = 2 * np.pi * r1 * (a1 + a1dag) # Default Solver Options y0 = Array(Statevector(np.ones(9))) t_linspace = np.linspace(0.0, 400e-9, 11) t_span = np.array([t_linspace[0], t_linspace[-1]]) dt = 1/4.5e9 atol = 1e-2 rtol = 1e-4 ham_ops = [drive_op0, drive_op1, drive_op0, drive_op1] ham_chans = ["d0", "d1", "u0", "u1"] chan_freqs = {"d0": v0, "d1": v1, "u0": v1, "u1": v0} solver = Solver( static_hamiltonian=static_ham_full, hamiltonian_operators=ham_ops, rotating_frame=static_ham_full, hamiltonian_channels=ham_chans, channel_carrier_freqs=chan_freqs, dt=dt, ) # Constructing a custom function that takes as input a parameter vector and returns the simulated state def standard_func(params): amp, sigma, freq = params # Here we use a Drag Pulse as defined in qiskit pulse as its already a Scalable Symbolic Pulse special_pulse = pulse.Drag( duration=320, amp=amp, sigma=sigma, beta=0.1, angle=0.1, limit_amplitude=False ) with pulse.build(default_alignment='sequential') as sched: d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) u0 = pulse.ControlChannel(0) u1 = pulse.ControlChannel(1) pulse.shift_frequency(freq, d0) pulse.play(special_pulse, d0) pulse.shift_frequency(freq, d1) pulse.play(special_pulse, d1) pulse.shift_frequency(freq, u0) pulse.play(special_pulse, u0) pulse.shift_frequency(freq, u1) pulse.play(special_pulse, u1) return sched def evolve_func(inp_y0, params, obs): sched = standard_func(params) converter = InstructionToSignals(dt, carriers=chan_freqs, channels=ham_chans) signals = converter.get_signals(sched) results = solver.solve( t_span=t_span, y0=inp_y0 / jnp.linalg.norm(inp_y0), t_eval=t_linspace, signals=signals, rtol=rtol, atol=atol, convert_results=False, method='jax_odeint' ) state_vec = results.y.data[-1] evolved_vec = jnp.dot(obs, state_vec) / jnp.linalg.norm(state_vec) probs_vec = jnp.abs(evolved_vec)**2 probs_vec = jnp.clip(probs_vec, a_min=0.0, a_max=1.0) return probs_vec fast_evolve_func = jit(vmap(evolve_func)) batchsize = 400 amp_vals = jnp.linspace(0.5, 0.99, batchsize, dtype=jnp.float64).reshape(-1, 1) sigma_vals = jnp.linspace(20, 80, batchsize, dtype=jnp.int8).reshape(-1, 1) freq_vals = jnp.linspace(-0.5, 0.5, batchsize, dtype=jnp.float64).reshape(-1, 1) * 1e6 batch_params = jnp.concatenate((amp_vals, sigma_vals, freq_vals), axis=-1) batch_y0 = jnp.tile(np.ones(9), (batchsize, 1)) batch_obs = jnp.tile(N0, (batchsize, 1, 1)) print(f"Batched Params Shape: {batch_params.shape}") res = fast_evolve_func(batch_y0, batch_params, batch_obs) print(res) print(res.shape) # Timing the fast jit + vmap batched simulation %timeit fast_evolve_func(batch_y0, batch_params, batch_obs).block_until_ready() # Timing a standard simulation without jitting or vmapping %timeit evolve_func(batch_y0[200], batch_params[200], batch_obs[200])
https://github.com/hephaex/Quantum-Computing-Awesome-List
hephaex
import qiskit qiskit.__qiskit_version__ from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram qc_ha = QuantumCircuit(4,2) # encode inputs in qubits 0 and 1 qc_ha.x(0) # For a=0, remove the this line. For a=1, leave it. qc_ha.x(1) # For b=0, remove the this line. For b=1, leave it. qc_ha.barrier() # use cnots to write the XOR of the inputs on qubit 2 qc_ha.cx(0,2) qc_ha.cx(1,2) # use ccx to write the AND of the inputs on qubit 3 qc_ha.ccx(0,1,3) qc_ha.barrier() # extract outputs qc_ha.measure(2,0) # extract XOR value qc_ha.measure(3,1) # extract AND value qc_ha.draw() counts = execute(qc_ha, Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the EchoRZXWeylDecomposition pass""" import unittest from math import pi import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import ( EchoRZXWeylDecomposition, ) from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeParis import qiskit.quantum_info as qi from qiskit.quantum_info.synthesis.two_qubit_decompose import ( TwoQubitWeylDecomposition, ) class TestEchoRZXWeylDecomposition(QiskitTestCase): """Tests the EchoRZXWeylDecomposition pass.""" def setUp(self): super().setUp() self.backend = FakeParis() self.inst_map = self.backend.defaults().instruction_schedule_map def assertRZXgates(self, unitary_circuit, after): """Check the number of rzx gates""" alpha = TwoQubitWeylDecomposition(unitary_circuit).a beta = TwoQubitWeylDecomposition(unitary_circuit).b gamma = TwoQubitWeylDecomposition(unitary_circuit).c expected_rzx_number = 0 if not alpha == 0: expected_rzx_number += 2 if not beta == 0: expected_rzx_number += 2 if not gamma == 0: expected_rzx_number += 2 circuit_rzx_number = QuantumCircuit.count_ops(after)["rzx"] self.assertEqual(expected_rzx_number, circuit_rzx_number) @staticmethod def count_gate_number(gate, circuit): """Count the number of a specific gate type in a circuit""" if gate not in QuantumCircuit.count_ops(circuit): gate_number = 0 else: gate_number = QuantumCircuit.count_ops(circuit)[gate] return gate_number def test_rzx_number_native_weyl_decomposition(self): """Check the number of RZX gates for a hardware-native cx""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) unitary_circuit = qi.Operator(circuit).data after = EchoRZXWeylDecomposition(self.inst_map)(circuit) unitary_after = qi.Operator(after).data self.assertTrue(np.allclose(unitary_circuit, unitary_after)) # check whether the after circuit has the correct number of rzx gates. self.assertRZXgates(unitary_circuit, after) def test_h_number_non_native_weyl_decomposition_1(self): """Check the number of added Hadamard gates for a native and non-native rzz gate""" theta = pi / 11 qr = QuantumRegister(2, "qr") # rzz gate in native direction circuit = QuantumCircuit(qr) circuit.rzz(theta, qr[0], qr[1]) # rzz gate in non-native direction circuit_non_native = QuantumCircuit(qr) circuit_non_native.rzz(theta, qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = EchoRZXWeylDecomposition(self.inst_map) after = dag_to_circuit(pass_.run(dag)) dag_non_native = circuit_to_dag(circuit_non_native) pass_ = EchoRZXWeylDecomposition(self.inst_map) after_non_native = dag_to_circuit(pass_.run(dag_non_native)) circuit_rzx_number = self.count_gate_number("rzx", after) circuit_h_number = self.count_gate_number("h", after) circuit_non_native_h_number = self.count_gate_number("h", after_non_native) # for each pair of rzx gates four hadamard gates have to be added in # the case of a non-hardware-native directed gate. self.assertEqual( (circuit_rzx_number / 2) * 4, circuit_non_native_h_number - circuit_h_number ) def test_h_number_non_native_weyl_decomposition_2(self): """Check the number of added Hadamard gates for a swap gate""" qr = QuantumRegister(2, "qr") # swap gate in native direction. circuit = QuantumCircuit(qr) circuit.swap(qr[0], qr[1]) # swap gate in non-native direction. circuit_non_native = QuantumCircuit(qr) circuit_non_native.swap(qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = EchoRZXWeylDecomposition(self.inst_map) after = dag_to_circuit(pass_.run(dag)) dag_non_native = circuit_to_dag(circuit_non_native) pass_ = EchoRZXWeylDecomposition(self.inst_map) after_non_native = dag_to_circuit(pass_.run(dag_non_native)) circuit_rzx_number = self.count_gate_number("rzx", after) circuit_h_number = self.count_gate_number("h", after) circuit_non_native_h_number = self.count_gate_number("h", after_non_native) # for each pair of rzx gates four hadamard gates have to be added in # the case of a non-hardware-native directed gate. self.assertEqual( (circuit_rzx_number / 2) * 4, circuit_non_native_h_number - circuit_h_number ) def test_weyl_decomposition_gate_angles(self): """Check the number and angles of the RZX gates for different gates""" thetas = [pi / 9, 2.1, -0.2] qr = QuantumRegister(2, "qr") circuit_rxx = QuantumCircuit(qr) circuit_rxx.rxx(thetas[0], qr[1], qr[0]) circuit_ryy = QuantumCircuit(qr) circuit_ryy.ryy(thetas[1], qr[0], qr[1]) circuit_rzz = QuantumCircuit(qr) circuit_rzz.rzz(thetas[2], qr[1], qr[0]) circuits = [circuit_rxx, circuit_ryy, circuit_rzz] for circuit in circuits: unitary_circuit = qi.Operator(circuit).data dag = circuit_to_dag(circuit) pass_ = EchoRZXWeylDecomposition(self.inst_map) after = dag_to_circuit(pass_.run(dag)) dag_after = circuit_to_dag(after) unitary_after = qi.Operator(after).data # check whether the unitaries are equivalent. self.assertTrue(np.allclose(unitary_circuit, unitary_after)) # check whether the after circuit has the correct number of rzx gates. self.assertRZXgates(unitary_circuit, after) alpha = TwoQubitWeylDecomposition(unitary_circuit).a rzx_angles = [] for node in dag_after.two_qubit_ops(): if node.name == "rzx": rzx_angle = node.op.params[0] # check whether the absolute values of the RZX gate angles # are equivalent to the corresponding Weyl parameter. self.assertAlmostEqual(np.abs(rzx_angle), alpha) rzx_angles.append(rzx_angle) # check whether the angles of every RZX gate pair of an echoed RZX gate # have opposite signs. for idx in range(1, len(rzx_angles), 2): self.assertAlmostEqual(rzx_angles[idx - 1], -rzx_angles[idx]) def test_weyl_unitaries_random_circuit(self): """Weyl decomposition for a random two-qubit circuit.""" theta = pi / 9 epsilon = 5 delta = -1 eta = 0.2 qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) # random two-qubit circuit. circuit.rzx(theta, 0, 1) circuit.rzz(epsilon, 0, 1) circuit.rz(eta, 0) circuit.swap(1, 0) circuit.h(0) circuit.rzz(delta, 1, 0) circuit.swap(0, 1) circuit.cx(1, 0) circuit.swap(0, 1) circuit.h(1) circuit.rxx(theta, 0, 1) circuit.ryy(theta, 1, 0) circuit.ecr(0, 1) unitary_circuit = qi.Operator(circuit).data dag = circuit_to_dag(circuit) pass_ = EchoRZXWeylDecomposition(self.inst_map) after = dag_to_circuit(pass_.run(dag)) unitary_after = qi.Operator(after).data self.assertTrue(np.allclose(unitary_circuit, unitary_after)) if __name__ == "__main__": unittest.main()
https://github.com/kad99kev/MacHacks-QuantumVRP
kad99kev
import sys import numpy as np from matplotlib import pyplot as plt from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, visualization from random import randint def to_binary(N,n_bit): Nbin = np.zeros(n_bit, dtype=bool) for i in range(1,n_bit+1): bit_state = (N % (2**i) != 0) if bit_state: N -= 2**(i-1) Nbin[n_bit-i] = bit_state return Nbin def modular_multiplication(qc,a,N): """ applies the unitary operator that implements modular multiplication function x -> a*x(modN) Only works for the particular case x -> 7*x(mod15)! """ for i in range(0,3): qc.x(i) qc.cx(2,1) qc.cx(1,2) qc.cx(2,1) qc.cx(1,0) qc.cx(0,1) qc.cx(1,0) qc.cx(3,0) qc.cx(0,1) qc.cx(1,0) def quantum_period(a, N, n_bit): # Quantum part print(" Searching the period for N =", N, "and a =", a) qr = QuantumRegister(n_bit) cr = ClassicalRegister(n_bit) qc = QuantumCircuit(qr,cr) simulator = Aer.get_backend('qasm_simulator') s0 = randint(1, N-1) # Chooses random int sbin = to_binary(s0,n_bit) # Turns to binary print("\n Starting at \n s =", s0, "=", "{0:b}".format(s0), "(bin)") # Quantum register is initialized with s (in binary) for i in range(0,n_bit): if sbin[n_bit-i-1]: qc.x(i) s = s0 r=-1 # makes while loop run at least 2 times # Applies modular multiplication transformation until we come back to initial number s while s != s0 or r <= 0: r+=1 # sets up circuit structure qc.measure(qr, cr) modular_multiplication(qc,a,N) qc.draw('mpl') # runs circuit and processes data job = execute(qc,simulator, shots=10) result_counts = job.result().get_counts(qc) result_histogram_key = list(result_counts)[0] # https://qiskit.org/documentation/stubs/qiskit.result.Result.get_counts.html#qiskit.result.Result.get_counts s = int(result_histogram_key, 2) print(" ", result_counts) plt.show() print("\n Found period r =", r) return r if __name__ == '__main__': a = 7 N = 15 n_bit=5 r = quantum_period(a, N, n_bit)
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# 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. """ A set of subroutines that are used by the VQE_forged_entanglement class, which is defined in the vqe_forged_entanglement module """ import inspect import warnings import re from typing import Iterable, Dict, Tuple import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import optimizers from qiskit.algorithms.optimizers import SPSA from qiskit.algorithms.optimizers.spsa import powerseries from qiskit_nature import QiskitNatureError from .generic_execution_subroutines import compute_pauli_means_and_cov_for_one_basis from .log import Log from .prepare_bitstring import prepare_bitstring from .pseudorichardson import richardson_extrapolate from .legacy.weighted_pauli_operator import WeightedPauliOperator Matrix = Iterable[Iterable[float]] # pylint: disable=too-many-locals,too-many-arguments,too-many-branches,invalid-name def make_stateprep_circuits( bitstrings: Iterable[Iterable[int]], no_bs0_circuits: bool = True, suffix: str = "" ): """Builds the circuits preparing states |b_n> and |phi^p_nm> as defined in <https://arxiv.org/abs/2104.10220>. Also returns a list of tuples which describe any superposition terms which carry a coefficient. Assumes that the operator amplitudes are real, thus does not construct superposition states with odd p. """ # If empty, just return if len(bitstrings) == 0: return [], [], [] # If the spin-up and spin-down spin orbitals are together a 2*N qubit system, # the bitstring should be N bits long. bitstrings = np.asarray(bitstrings) tensor_prep_circuits = [ prepare_bitstring(bs, name="bs" + suffix + str(bs_idx)) for bs_idx, bs in enumerate(bitstrings) ] if no_bs0_circuits: # Drops the HF bitstring, which is assumed to be first, # since hops in our ansatz are chosen to leave it unchanged! (IMPORTANT) tensor_prep_circuits = tensor_prep_circuits[1:] superpos_prep_circuits = [] hybrid_superpos_coeffs = {} for bs1_idx, bs1 in enumerate(bitstrings): for bs2_relative_idx, bs2 in enumerate(bitstrings[bs1_idx + 1 :]): diffs = np.where(bs1 != bs2)[0] # TODO implement p -> -p as needed for problems with complex amplitudes # pylint: disable=fixme if len(diffs) > 0: i = diffs[0] if bs1[i]: x = bs2 y = bs1 # pylint: disable=unused-variable else: x = bs1 y = bs2 # pylint: disable=unused-variable S = np.delete(diffs, 0) qcirc = prepare_bitstring(np.concatenate((x[:i], [0], x[i + 1 :]))) qcirc.h(i) psi_xplus, psi_xmin = [ qcirc.copy( name=f"bs{suffix}{bs1_idx}bs{suffix}{bs1_idx+1+bs2_relative_idx}{name}" ) for name in ["xplus", "xmin"] ] psi_xmin.z(i) for psi in [psi_xplus, psi_xmin]: for target in S: psi.cx(i, target) superpos_prep_circuits.append(psi) # If the two bitstrings are equivalent -- bn==bm else: qcirc = prepare_bitstring(bs1) psi_xplus, psi_xmin = [ qcirc.copy( name=f"bs{suffix}{bs1_idx}bs{suffix}{bs1_idx+1+bs2_relative_idx}{name}" ) for name in ["xplus", "xmin"] ] hybrid_superpos_coeffs[ (suffix, str(bs1_idx), str(bs1_idx + 1 + bs2_relative_idx)) ] = True superpos_prep_circuits += [psi_xplus, psi_xmin] return tensor_prep_circuits, superpos_prep_circuits, hybrid_superpos_coeffs def prepare_circuits_to_execute( params: Iterable[float], stateprep_circuits: Iterable[QuantumCircuit], op_for_generating_circuits: WeightedPauliOperator, var_form: QuantumCircuit, statevector_mode: bool, ): """Given a set of variational parameters and list of 6qb state-preps, this function returns all (unique) circuits that must be run to evaluate those samples. """ # If circuits are empty, just return if len(stateprep_circuits) == 0: return [] circuits_to_execute = [] # Generate the requisite circuits: # pylint: disable=unidiomatic-typecheck param_bindings = dict(zip(var_form.parameters, params)) u_circuit = var_form.bind_parameters(param_bindings) for prep_circ in [qc.copy() for qc in stateprep_circuits]: circuit_name_prefix = str(params) + "_" + str(prep_circ.name) + "_" wavefn_circuit = prep_circ.compose(u_circuit) if statevector_mode: circuits_to_execute.append( wavefn_circuit.copy(name=circuit_name_prefix + "psi") ) else: circuits_this_stateprep = ( op_for_generating_circuits.construct_evaluation_circuit( wave_function=wavefn_circuit.copy(), statevector_mode=statevector_mode, # <-- False, here. use_simulator_snapshot_mode=False, circuit_name_prefix=circuit_name_prefix, ) ) circuits_to_execute += circuits_this_stateprep return circuits_to_execute # pylint: disable=unbalanced-tuple-unpacking def eval_forged_op_with_result( result, w_ij_tensor_states: Matrix, w_ab_superpos_states: Matrix, params: Iterable[float], bitstrings_s_u: np.ndarray, op_for_generating_tensor_circuits: WeightedPauliOperator, op_for_generating_superpos_circuits: WeightedPauliOperator, richardson_stretch_factors: Iterable[float], statevector_mode: bool, hf_value: float, add_this_to_mean_values_displayed: float, bitstrings_s_v: np.ndarray = None, hybrid_superpos_coeffs: Dict[Tuple[int, int, str], bool] = None, no_bs0_circuits: bool = True, verbose: bool = False, ): """Evaluates the forged operator. Extracts necessary expectation values from the result object, then combines those pieces to compute the configuration-interaction Hamiltonian (Hamiltonian in the basis of determinants/bitstrings). For reference, also computes mean value obtained without Richardson """ if bitstrings_s_v is None: bitstrings_s_v = [] tensor_state_prefixes_u = [f"bsu{idx}" for idx in range(len(bitstrings_s_u))] tensor_state_prefixes_v = [] if len(bitstrings_s_v) > 0: tensor_state_prefixes_v = [f"bsv{idx}" for idx in range(len(bitstrings_s_v))] tensor_state_prefixes = tensor_state_prefixes_u + tensor_state_prefixes_v tensor_expvals = _get_pauli_expectations_from_result( result, params, tensor_state_prefixes, op_for_generating_tensor_circuits, richardson_stretch_factors=richardson_stretch_factors, hybrid_superpos_coeffs=hybrid_superpos_coeffs, statevector_mode=statevector_mode, no_bs0_circuits=no_bs0_circuits, ) tensor_expvals_extrap = richardson_extrapolate( tensor_expvals, richardson_stretch_factors, axis=2 ) superpos_state_prefixes_u = [] superpos_state_prefixes_v = [] lin_combos = ["xplus", "xmin"] # ,'yplus','ymin'] # num_bitstrings is the number of bitstring combos we have num_bitstrings = len(bitstrings_s_u) for x in range(num_bitstrings): for y in range(num_bitstrings): if x == y: continue bsu_string = f"bsu{min(x,y)}bsu{max(x,y)}" superpos_state_prefixes_u += [ bsu_string + lin_combo for lin_combo in lin_combos ] # Determine whether we are handling the two subsystems separately asymmetric_bitstrings = False if len(bitstrings_s_v) > 0: asymmetric_bitstrings = True bsv_string = f"bsv{min(x,y)}bsv{max(x,y)}" superpos_state_prefixes_v += [ bsv_string + lin_combo for lin_combo in lin_combos ] superpos_state_prefixes = superpos_state_prefixes_u + superpos_state_prefixes_v superpos_expvals = _get_pauli_expectations_from_result( result, params, superpos_state_prefixes, op_for_generating_superpos_circuits, hybrid_superpos_coeffs=hybrid_superpos_coeffs, richardson_stretch_factors=richardson_stretch_factors, statevector_mode=statevector_mode, no_bs0_circuits=no_bs0_circuits, ) superpos_expvals_extrap = richardson_extrapolate( superpos_expvals, richardson_stretch_factors, axis=2 ) forged_op_results_w_and_wo_extrapolation = [] for (tensor_expvals_real, superpos_expvals_real) in [ [tensor_expvals_extrap, superpos_expvals_extrap], [tensor_expvals[:, :, 0], superpos_expvals[:, :, 0]], ]: h_schmidt = compute_h_schmidt( tensor_expvals_real, superpos_expvals_real, w_ij_tensor_states, w_ab_superpos_states, asymmetric_bitstrings, ) if no_bs0_circuits: # IMPORTANT: ASSUMING HOPGATES CHOSEN S.T. HF BITSTRING # (FIRST BITSTRING) IS UNAFFECTED, ALLOWING CORRESPONDING # ENERGY TO BE FIXED AT HF VALUE CALCULATED BY QISKIT/PYSCF. h_schmidt[0, 0] = hf_value - add_this_to_mean_values_displayed # Update Schmidt coefficients to minimize operator (presumably energy): if verbose: Log.log( "Operator as Schmidt matrix: (diagonals have been shifted by given offset", add_this_to_mean_values_displayed, ")", ) Log.log( h_schmidt + np.eye(len(h_schmidt)) * add_this_to_mean_values_displayed ) evals, evecs = np.linalg.eigh(h_schmidt) schmidts = evecs[:, 0] op_mean = evals[0] op_std = None forged_op_results_w_and_wo_extrapolation.append([op_mean, op_std, schmidts]) ( forged_op_results_extrap, forged_op_results_raw, ) = forged_op_results_w_and_wo_extrapolation # pylint: disable=unbalanced-tuple-unpacking return forged_op_results_extrap, forged_op_results_raw def _get_pauli_expectations_from_result( result, params, stateprep_strings, op_for_generating_circuits, statevector_mode, hybrid_superpos_coeffs=None, richardson_stretch_factors=None, no_bs0_circuits=True, ): """Returns array containing ordered expectation values of Pauli strings evaluated for the various wavefunctions. Axes are [stateprep_idx, Pauli_idx, richardson_stretch_factor_idx, mean_or_variance] """ if richardson_stretch_factors is None: richardson_stretch_factors = [1] if not op_for_generating_circuits: return np.empty((0, 0, len(richardson_stretch_factors), 2)) params_string = str(params) + "_" if statevector_mode: op_matrices = np.asarray( [op.to_matrix() for op in [p[1] for p in op_for_generating_circuits.paulis]] ) pauli_vals = np.zeros( ( len(stateprep_strings), len(op_for_generating_circuits._paulis), # pylint: disable=protected-access len(richardson_stretch_factors), 2, ) ) pauli_names_temp = [p[1].to_label() for p in op_for_generating_circuits.paulis] for prep_idx, prep_string in enumerate(stateprep_strings): suffix = prep_string[2] if suffix not in ["u", "v"]: raise ValueError(f"Invalid stateprep circuit name: {prep_string}") bitstring_pair = [0, 0] tensor_circuit = True num_bs_terms = prep_string.count("bs") if (num_bs_terms > 2) or (num_bs_terms == 0): raise ValueError(f"Invalid stateprep circuit name: {prep_string}") elif num_bs_terms == 2: tensor_circuit = False prep_string_digits = [ int(float(s)) for s in re.findall(r"-?\d+\.?\d*", prep_string) ] bitstring_pair = [prep_string_digits[0], prep_string_digits[1]] if no_bs0_circuits and (prep_string == "bsu0" or prep_string == "bsv0"): # IMPORTANT: ASSUMING HOPGATES CHOSEN S.T. # HF BITSTRING (FIRST BITSTRING) IS UNAFFECTED, # ALLOWING CORRESPONDING ENERGY TO BE FIXED AT H # F VALUE CALCULATED BY QISKIT/PYSCF. pauli_vals[prep_idx, :, :, :] = np.nan continue circuit_prefix_prefix = "".join([params_string, prep_string]) for rich_idx, stretch_factor in enumerate(richardson_stretch_factors): circuit_name_prefix = "".join( [circuit_prefix_prefix, f"_richardson{stretch_factor:.2f}", "_"] ) if statevector_mode: psi = result.get_statevector(circuit_name_prefix + "psi") pauli_vals_temp = np.real( np.einsum("i,Mij,j->M", np.conj(psi), op_matrices, psi) ) else: pauli_vals_temp, _ = _eval_each_pauli_with_result( tpbgwpo=op_for_generating_circuits, result=result, statevector_mode=statevector_mode, use_simulator_snapshot_mode=False, circuit_name_prefix=circuit_name_prefix, ) pauli_vals_alphabetical = [ x[1] for x in sorted(list(zip(pauli_names_temp, pauli_vals_temp))) ] if not np.all(np.isreal(pauli_vals_alphabetical)): warnings.warn( "Computed Pauli expectation value has nonzero " "imaginary part which will be discarded." ) pauli_vals[prep_idx, :, rich_idx, 0] = np.real(pauli_vals_alphabetical) key = (suffix, str(bitstring_pair[0]), str(bitstring_pair[1])) if key in hybrid_superpos_coeffs.keys(): if prep_string[-4:] == "xmin": pauli_vals[prep_idx] *= 0 elif prep_string[-5:] == "xplus": pass else: raise ValueError(f"Invalid circuit name: {prep_string}") elif not tensor_circuit: pauli_vals[prep_idx] *= 1 / 2 return pauli_vals # pylint: disable=protected-access def _eval_each_pauli_with_result( tpbgwpo, result, statevector_mode, use_simulator_snapshot_mode=False, circuit_name_prefix="", ): """Ignores the weights of each pauli operator.""" if tpbgwpo.is_empty(): raise QiskitNatureError("Operator is empty, check the operator.") if statevector_mode or use_simulator_snapshot_mode: raise NotImplementedError() num_paulis = len(tpbgwpo._paulis) means = np.zeros(num_paulis) cov = np.zeros((num_paulis, num_paulis)) for basis, p_indices in tpbgwpo._basis: counts = result.get_counts(circuit_name_prefix + basis.to_label()) paulis = [tpbgwpo._paulis[idx] for idx in p_indices] paulis = [p[1] for p in paulis] ## DISCARDING THE WEIGHTS means_this_basis, cov_this_basis = compute_pauli_means_and_cov_for_one_basis( paulis, counts ) for p_idx, p_mean in zip(p_indices, means_this_basis): means[p_idx] = p_mean cov[np.ix_(p_indices, p_indices)] = cov_this_basis return means, cov def compute_h_schmidt( tensor_expvals, superpos_expvals, w_ij_tensor_weights, w_ab_superpos_weights, asymmetric_bitstrings, ): """Computes the schmidt decomposition of the Hamiltonian. TODO checkthis. # pylint: disable=fixme Pauli val arrays contain expectation values <x|P|x> and their standard deviations. Axes are [x_idx, P_idx, mean_or_variance] Coefficients w_ij/w_ab: Axes: [index of Pauli string for eta, index of Pauli string for tau]. asymmetric_bitstrings: A boolean which signifies whether the U and V subsystems have different ansatze. """ # Number of tensor stateprep circuits num_tensor_terms = int(np.shape(tensor_expvals)[0]) if asymmetric_bitstrings: num_tensor_terms = int( num_tensor_terms / 2 ) # num_tensor_terms should always be even here tensor_exp_vals_u = tensor_expvals[:num_tensor_terms, :, 0] tensor_exp_vals_v = tensor_expvals[num_tensor_terms:, :, 0] else: # Use the same expectation values for both subsystem calculations tensor_exp_vals_u = tensor_expvals[:, :, 0] tensor_exp_vals_v = tensor_expvals[:, :, 0] # Calculate the schmidt summation over the U and V subsystems and diagonalize the values h_schmidt_diagonal = np.einsum( "ij,xi,xj->x", w_ij_tensor_weights, tensor_exp_vals_u, tensor_exp_vals_v, ) h_schmidt = np.diag(h_schmidt_diagonal) # If including the +/-Y superpositions (omitted at time of writing # since they typically have 0 net contribution) would change this to 4 instead of 2. num_lin_combos = 2 num_superpos_terms = int(np.shape(superpos_expvals)[0]) if asymmetric_bitstrings: num_superpos_terms = int( num_superpos_terms / 2 ) # num_superpos_terms should always be even here pvss_u = superpos_expvals[:num_superpos_terms, :, 0] pvss_v = superpos_expvals[num_superpos_terms:, :, 0] else: pvss_u = superpos_expvals[:, :, 0] pvss_v = superpos_expvals[:, :, 0] # Calculate delta for U subsystem p_plus_x_u = pvss_u[0::num_lin_combos, :] p_minus_x_u = pvss_u[1::num_lin_combos, :] p_delta_x_u = p_plus_x_u - p_minus_x_u # Calculate delta for V subsystem if asymmetric_bitstrings: p_plus_x_v = pvss_v[0::num_lin_combos, :] p_minus_x_v = pvss_v[1::num_lin_combos, :] p_delta_x_v = p_plus_x_v - p_minus_x_v else: p_delta_x_v = p_delta_x_u h_schmidt_off_diagonals = np.einsum( "ab,xa,xb->x", w_ab_superpos_weights, p_delta_x_u, p_delta_x_v ) superpos_state_indices = [ (x, y) for x in range(h_schmidt.shape[0]) for y in range(h_schmidt.shape[0]) if x != y ] for element, indices in zip(h_schmidt_off_diagonals, superpos_state_indices): h_schmidt[indices] = element return h_schmidt # , H_schmidt_vars) def get_optimizer_instance(config): """Returns optimizer instance based on config.""" # Addressing some special cases for compatibility with various Qiskit optimizers: if config.optimizer_name == "adaptive_SPSA": optimizer = SPSA else: optimizer = getattr(optimizers, config.optimizer_name) optimizer_config = {} optimizer_arg_names = inspect.signature(optimizer).parameters.keys() iter_kw = [kw for kw in ["maxiter", "max_trials"] if kw in optimizer_arg_names][0] optimizer_config[iter_kw] = config.maxiter if "skip_calibration" in optimizer_arg_names: optimizer_config["skip_calibration"] = config.skip_any_optimizer_cal if "last_avg" in optimizer_arg_names: optimizer_config["last_avg"] = config.spsa_last_average if "tol" in optimizer_arg_names: optimizer_config["tol"] = config.optimizer_tol if "c0" in optimizer_arg_names: optimizer_config["c0"] = config.spsa_c0 if "c1" in optimizer_arg_names: optimizer_config["c1"] = config.spsa_c1 if "learning_rate" in optimizer_arg_names: optimizer_config["learning_rate"] = lambda: powerseries( config.spsa_c0, 0.602, 0 ) if "perturbation" in optimizer_arg_names: optimizer_config["perturbation"] = lambda: powerseries(config.spsa_c1, 0.101, 0) if config.initial_spsa_iteration_idx: if "int_iter" in optimizer_arg_names: optimizer_config["int_iter"] = config.initial_spsa_iteration_idx if "bootstrap_trials" in optimizer_arg_names: optimizer_config["bootstrap_trials"] = config.bootstrap_trials Log.log(optimizer_config) optimizer_instance = optimizer(**optimizer_config) return optimizer_instance
https://github.com/abbarreto/qiskit3
abbarreto
https://github.com/vindem/quantumMD
vindem
from qiskit.algorithms.minimum_eigen_solvers import VQE import numpy as np from qiskit.opflow import MatrixOp from CSWAPCircuit import CSWAPCircuit from qiskit.providers import JobStatus from qiskit import IBMQ import time from qiskit import IBMQ, Aer from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options from qiskit.primitives import Estimator from qiskit.providers.aer.noise import NoiseModel from qiskit_aqt_provider import AQTProvider from qiskit_aqt_provider.primitives import AQTEstimator from qiskit.quantum_info import Operator from scipy.optimize import minimize from config import Config from qiskit.algorithms.optimizers import COBYLA import math from qiskit.transpiler import PassManager from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime.transpiler.passes.scheduling import ALAPScheduleAnalysis, PadDynamicalDecoupling from qiskit.circuit.library import XGate from qiskit.circuit.library import * from JobPersistenceManager import JobPersistenceManager callback_dict = { "prev_vector": None, "iters": 0, "cost_history": [], } def setup_backend_for_task(task_name): task_setup = Config.execution_setup['execution_setup'][task_name][0] match task_setup['provider']: case 'Aer': return Aer.get_backend('aer_simulator') case 'AQT': provider = AQTProvider(task_setup['token']) backend = provider.get_backend(name=task_setup['name']) return backend case 'IBM': IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-research-2', group='vienna-uni-tech-1', project='main') backend = provider.get_backend(name=task_setup['name']) return backend case _: raise Exception("Unknown Provider!") def build_callback(ansatz, hamiltonian, estimator, callback_dict): """Return callback function that uses Estimator instance, and stores intermediate values into a dictionary. Parameters: ansatz (QuantumCircuit): Parameterized ansatz circuit hamiltonian (SparsePauliOp): Operator representation of Hamiltonian estimator (Estimator): Estimator primitive instance callback_dict (dict): Mutable dict for storing values Returns: Callable: Callback function object """ def callback(current_vector): """Callback function storing previous solution vector, computing the intermediate cost value, and displaying number of completed iterations and average time per iteration. Values are stored in pre-defined 'callback_dict' dictionary. Parameters: current_vector (ndarray): Current vector of parameters returned by optimizer """ # Keep track of the number of iterations callback_dict["iters"] += 1 # Set the prev_vector to the latest one callback_dict["prev_vector"] = current_vector # Compute the value of the cost function at the current vector # This adds an additional function evaluation current_cost = ( estimator.run(ansatz, hamiltonian, parameter_values=current_vector).result().values[0] ) callback_dict["cost_history"].append(current_cost) # Print to screen on single line print( "Iters. done: {} [Current cost: {}]".format(callback_dict["iters"], current_cost), end="\r", flush=True, ) return callback def calculate_distance_quantum(A, B): print("Starting SWAPTEST.") distance_configuration = Config.execution_setup['execution_setup']['dist_calc'][0] print("Target machine: "+distance_configuration['name']+ ", " + distance_configuration['type']) #IBMQ.load_account() #provider = IBMQ.get_provider(hub='ibm-q-research-2', group='vienna-uni-tech-1', project='main') #backend = Aer.get_backend('aer_simulator') #noise_model = NoiseModel.from_backend(provider.backend.ibmq_quito) #backend = provider.get_backend("ibex", workspace="hpqc") backend = setup_backend_for_task('dist_calc') cswap_circuit = CSWAPCircuit(backend, 200) quantum_ED = cswap_circuit.execute_swap_test(A, B) arr = np.array(quantum_ED) #print(arr.shape) return arr def calc_eigval_quantum(bpm, filename): print("Starting VQE.") eigenvalue_configuration = Config.execution_setup['execution_setup']['eigenvalues'][0] print("Target machine: " + eigenvalue_configuration['name'] + ", " + eigenvalue_configuration['type']) qubit_op = Operator(-bpm) #backend = Aer.get_backend('aer_simulator') backend = setup_backend_for_task('eigenvalues') #vqe = VQE(qubit_op, variational_form, optimizer=optimizer) def cost_function(params, ansatz, hamiltonian, estimator): try: if eigenvalue_configuration['persistence']: persistence_manager = JobPersistenceManager() job = estimator.run(ansatz, hamiltonian, parameter_values=params) if eigenvalue_configuration['persistence']: persistence_manager.add_id(job.job_id()) result = job.result() except TimeoutError: if eigenvalue_configuration['persistence']: job_ids = persistence_manager.active_jobs() for job_id in job_ids: restored_job = AQTJob.restore(job_id, access_token=eigenvalue_configuration['token']) result = restored_job.result() energy = result.values[0] return energy improved_ansatz = globals()[eigenvalue_configuration['ansatz']](int(math.log2(bpm.shape[0]))) num_params = improved_ansatz.num_parameters #x0 = - (np.max(qubit_op) - np.min(qubit_op)) * np.random.random(num_params) * 10.0 #x0 = np.max(np.real(qubit_op)) * np.random.random(num_params) x0 = [0] * num_params #x0 = np.random.random(num_params) #print("x0" + str(x0)) options = Options() #options.transpilation.skip_transpilation = True options.execution.shots = 200 options.optimization_level = 3 options.resilience_level = 3 #estimator = Estimator(options=options) #callback = build_callback(improved_ansatz, qubit_op, estimator, callback_dict) if eigenvalue_configuration['provider'] == 'AQT': from qiskit_aqt_provider.aqt_job import AQTJob estimator = AQTEstimator(backend=backend) elif eigenvalue_configuration['provider'] == 'IBM': estimator = Estimator(options={"optimization_level":3, "resilience_level": 3}) else: estimator = Estimator(options={"optimization_level": 3, "resilience_level": 3}) start = time.time() res = minimize( cost_function, x0, args=(improved_ansatz, qubit_op, estimator), method=eigenvalue_configuration['optimizer'], options={"maxiter": eigenvalue_configuration['opt_iters'], "tol":0.1} ) end = time.time() #print("FINAL: "+ str(np.real(-res.fun))) return [-(np.real(res.fun)), end - start]
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import io import math import os import pathlib import pickle import shutil import tempfile import unittest import ddt import qiskit.qasm2 from qiskit import qpy from qiskit.circuit import ( ClassicalRegister, Gate, Parameter, QuantumCircuit, QuantumRegister, Qubit, library as lib, ) from qiskit.test import QiskitTestCase from . import gate_builder class TestEmpty(QiskitTestCase): def test_allows_empty(self): self.assertEqual(qiskit.qasm2.loads(""), QuantumCircuit()) class TestVersion(QiskitTestCase): def test_complete_version(self): program = "OPENQASM 2.0;" parsed = qiskit.qasm2.loads(program) self.assertEqual(parsed, QuantumCircuit()) def test_incomplete_version(self): program = "OPENQASM 2;" parsed = qiskit.qasm2.loads(program) self.assertEqual(parsed, QuantumCircuit()) def test_after_comment(self): program = """ // hello, world OPENQASM 2.0; qreg q[2]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) class TestRegisters(QiskitTestCase): def test_qreg(self): program = "qreg q1[2]; qreg q2[1]; qreg q3[4];" parsed = qiskit.qasm2.loads(program) regs = [QuantumRegister(2, "q1"), QuantumRegister(1, "q2"), QuantumRegister(4, "q3")] self.assertEqual(list(parsed.qregs), regs) self.assertEqual(list(parsed.cregs), []) def test_creg(self): program = "creg c1[2]; creg c2[1]; creg c3[4];" parsed = qiskit.qasm2.loads(program) regs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2"), ClassicalRegister(4, "c3")] self.assertEqual(list(parsed.cregs), regs) self.assertEqual(list(parsed.qregs), []) def test_interleaved_registers(self): program = "qreg q1[3]; creg c1[2]; qreg q2[1]; creg c2[1];" parsed = qiskit.qasm2.loads(program) qregs = [QuantumRegister(3, "q1"), QuantumRegister(1, "q2")] cregs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2")] self.assertEqual(list(parsed.qregs), qregs) self.assertEqual(list(parsed.cregs), cregs) def test_registers_after_gate(self): program = "qreg before[2]; CX before[0], before[1]; qreg after[2]; CX after[0], after[1];" parsed = qiskit.qasm2.loads(program) before = QuantumRegister(2, "before") after = QuantumRegister(2, "after") qc = QuantumCircuit(before, after) qc.cx(before[0], before[1]) qc.cx(after[0], after[1]) self.assertEqual(parsed, qc) def test_empty_registers(self): program = "qreg q[0]; creg c[0];" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "q"), ClassicalRegister(0, "c")) self.assertEqual(parsed, qc) @ddt.ddt class TestGateApplication(QiskitTestCase): def test_builtin_single(self): program = """ qreg q[2]; U(0, 0, 0) q[0]; CX q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.u(0, 0, 0, 0) qc.cx(0, 1) self.assertEqual(parsed, qc) def test_builtin_1q_broadcast(self): program = "qreg q[2]; U(0, 0, 0) q;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.u(0, 0, 0, 0) qc.u(0, 0, 0, 1) self.assertEqual(parsed, qc) def test_builtin_2q_broadcast(self): program = """ qreg q1[2]; qreg q2[2]; CX q1[0], q2; barrier; CX q1, q2[1]; barrier; CX q1, q2; """ parsed = qiskit.qasm2.loads(program) q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[0]) qc.cx(q1[0], q2[1]) qc.barrier() qc.cx(q1[0], q2[1]) qc.cx(q1[1], q2[1]) qc.barrier() qc.cx(q1[0], q2[0]) qc.cx(q1[1], q2[1]) self.assertEqual(parsed, qc) def test_3q_broadcast(self): program = """ include "qelib1.inc"; qreg q1[2]; qreg q2[2]; qreg q3[2]; ccx q1, q2[0], q3[1]; ccx q1[1], q2, q3[0]; ccx q1[0], q2[1], q3; barrier; ccx q1, q2, q3[1]; ccx q1[1], q2, q3; ccx q1, q2[1], q3; barrier; ccx q1, q2, q3; """ parsed = qiskit.qasm2.loads(program) q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") q3 = QuantumRegister(2, "q3") qc = QuantumCircuit(q1, q2, q3) qc.ccx(q1[0], q2[0], q3[1]) qc.ccx(q1[1], q2[0], q3[1]) qc.ccx(q1[1], q2[0], q3[0]) qc.ccx(q1[1], q2[1], q3[0]) qc.ccx(q1[0], q2[1], q3[0]) qc.ccx(q1[0], q2[1], q3[1]) qc.barrier() qc.ccx(q1[0], q2[0], q3[1]) qc.ccx(q1[1], q2[1], q3[1]) qc.ccx(q1[1], q2[0], q3[0]) qc.ccx(q1[1], q2[1], q3[1]) qc.ccx(q1[0], q2[1], q3[0]) qc.ccx(q1[1], q2[1], q3[1]) qc.barrier() qc.ccx(q1[0], q2[0], q3[0]) qc.ccx(q1[1], q2[1], q3[1]) self.assertEqual(parsed, qc) @ddt.data(True, False) def test_broadcast_against_empty_register(self, conditioned): cond = "if (cond == 0) " if conditioned else "" program = f""" OPENQASM 2; include "qelib1.inc"; qreg q1[1]; qreg q2[1]; qreg empty1[0]; qreg empty2[0]; qreg empty3[0]; creg cond[1]; // None of the following statements should produce any gate applications. {cond}h empty1; {cond}cx q1[0], empty1; {cond}cx empty1, q2[0]; {cond}cx empty1, empty2; {cond}ccx empty1, q1[0], q2[0]; {cond}ccx q1[0], empty2, q2[0]; {cond}ccx q1[0], q2[0], empty3; {cond}ccx empty1, empty2, q1[0]; {cond}ccx empty1, q1[0], empty2; {cond}ccx q1[0], empty1, empty2; {cond}ccx empty1, empty2, empty3; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit( QuantumRegister(1, "q1"), QuantumRegister(1, "q2"), QuantumRegister(0, "empty1"), QuantumRegister(0, "empty2"), QuantumRegister(0, "empty3"), ClassicalRegister(1, "cond"), ) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ qreg q[2]; creg cond[1]; if (cond == 0) U(0, 0, 0) q[0]; if (cond == 1) CX q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), cond) qc.u(0, 0, 0, 0).c_if(cond, 0) qc.cx(1, 0).c_if(cond, 1) self.assertEqual(parsed, qc) def test_conditioned_broadcast(self): program = """ qreg q1[2]; qreg q2[2]; creg cond[1]; if (cond == 0) U(0, 0, 0) q1; if (cond == 1) CX q1[0], q2; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2, cond) qc.u(0, 0, 0, q1[0]).c_if(cond, 0) qc.u(0, 0, 0, q1[1]).c_if(cond, 0) qc.cx(q1[0], q2[0]).c_if(cond, 1) qc.cx(q1[0], q2[1]).c_if(cond, 1) self.assertEqual(parsed, qc) def test_constant_folding(self): # Most expression-related things are tested in `test_expression.py` instead. program = """ qreg q[1]; U(4 + 3 * 2 ^ 2, cos(pi) * (1 - ln(1)), 2 ^ 3 ^ 2) q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.u(16.0, -1.0, 512.0, 0) self.assertEqual(parsed, qc) def test_call_defined_gate(self): program = """ gate my_gate a { U(0, 0, 0) a; } qreg q[2]; my_gate q[0]; my_gate q; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit()]) my_gate_def.u(0, 0, 0, 0) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0]) qc.append(my_gate(), [0]) qc.append(my_gate(), [1]) self.assertEqual(parsed, qc) def test_parameterless_gates_accept_parentheses(self): program = """ qreg q[2]; CX q[0], q[1]; CX() q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.cx(0, 1) qc.cx(1, 0) self.assertEqual(parsed, qc) class TestGateDefinition(QiskitTestCase): def test_simple_definition(self): program = """ gate not_bell a, b { U(0, 0, 0) a; CX a, b; } qreg q[2]; not_bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) not_bell_def = QuantumCircuit([Qubit(), Qubit()]) not_bell_def.u(0, 0, 0, 0) not_bell_def.cx(0, 1) not_bell = gate_builder("not_bell", [], not_bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(not_bell(), [0, 1]) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ gate not_bell a, b { U(0, 0, 0) a; CX a, b; } qreg q[2]; creg cond[1]; if (cond == 0) not_bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) not_bell_def = QuantumCircuit([Qubit(), Qubit()]) not_bell_def.u(0, 0, 0, 0) not_bell_def.cx(0, 1) not_bell = gate_builder("not_bell", [], not_bell_def) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), cond) qc.append(not_bell().c_if(cond, 0), [0, 1]) self.assertEqual(parsed, qc) def test_constant_folding_in_definition(self): program = """ gate bell a, b { U(pi/2, 0, pi) a; CX a, b; } qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.u(math.pi / 2, 0, math.pi, 0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_parameterised_gate(self): # Most of the tests of deep parameter expressions are in `test_expression.py`. program = """ gate my_gate(a, b) c { U(a, b, a + 2 * b) c; } qreg q[1]; my_gate(0.25, 0.5) q[0]; my_gate(0.5, 0.25) q[0]; """ parsed = qiskit.qasm2.loads(program) a, b = Parameter("a"), Parameter("b") my_gate_def = QuantumCircuit([Qubit()]) my_gate_def.u(a, b, a + 2 * b, 0) my_gate = gate_builder("my_gate", [a, b], my_gate_def) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(my_gate(0.25, 0.5), [0]) qc.append(my_gate(0.5, 0.25), [0]) self.assertEqual(parsed, qc) # Also check the decomposition has come out exactly as expected. The floating-point # assertions are safe as exact equality checks because there are no lossy operations with # these parameters, and the answer should be exact. decomposed = qc.decompose() self.assertEqual(decomposed.data[0].operation.name, "u") self.assertEqual(list(decomposed.data[0].operation.params), [0.25, 0.5, 1.25]) self.assertEqual(decomposed.data[1].operation.name, "u") self.assertEqual(list(decomposed.data[1].operation.params), [0.5, 0.25, 1.0]) def test_parameterless_gate_with_parentheses(self): program = """ gate my_gate() a { U(0, 0, 0) a; } qreg q[1]; my_gate q[0]; my_gate() q[0]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit()]) my_gate_def.u(0, 0, 0, 0) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(my_gate(), [0]) qc.append(my_gate(), [0]) self.assertEqual(parsed, qc) def test_access_includes_in_definition(self): program = """ include "qelib1.inc"; gate bell a, b { h a; cx a, b; } qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_access_previous_defined_gate(self): program = """ include "qelib1.inc"; gate bell a, b { h a; cx a, b; } gate second_bell a, b { bell b, a; } qreg q[2]; second_bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) second_bell_def = QuantumCircuit([Qubit(), Qubit()]) second_bell_def.append(bell(), [1, 0]) second_bell = gate_builder("second_bell", [], second_bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(second_bell(), [0, 1]) self.assertEqual(parsed, qc) def test_qubits_lookup_differently_to_gates(self): # The spec is somewhat unclear on this, and this leads to super weird text, but it's # technically unambiguously resolvable and this is more permissive. program = """ include "qelib1.inc"; gate bell h, cx { h h; cx h, cx; } qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_parameters_lookup_differently_to_gates(self): # The spec is somewhat unclear on this, and this leads to super weird text, but it's # technically unambiguously resolvable and this is more permissive. program = """ include "qelib1.inc"; gate shadow(rx, rz) a { rz(rz) a; rx(rx) a; } qreg q[1]; shadow(0.5, 2.0) q[0]; """ parsed = qiskit.qasm2.loads(program) rx, rz = Parameter("rx"), Parameter("rz") shadow_def = QuantumCircuit([Qubit()]) shadow_def.rz(rz, 0) shadow_def.rx(rx, 0) shadow = gate_builder("shadow", [rx, rz], shadow_def) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(shadow(0.5, 2.0), [0]) self.assertEqual(parsed, qc) def test_unused_parameters_convert_correctly(self): # The main risk here is that there might be lazy application in the gate definition # bindings, and we might accidentally try and bind parameters that aren't actually in the # definition. program = """ gate my_gate(p) q { U(0, 0, 0) q; } qreg q[1]; my_gate(0.5) q[0]; """ parsed = qiskit.qasm2.loads(program) # No top-level circuit equality test here, because all the internals of gate application are # an implementation detail, and we don't want to tie the tests and implementation together # too closely. self.assertEqual(list(parsed.qregs), [QuantumRegister(1, "q")]) self.assertEqual(list(parsed.cregs), []) self.assertEqual(len(parsed.data), 1) self.assertEqual(parsed.data[0].qubits, (parsed.qubits[0],)) self.assertEqual(parsed.data[0].clbits, ()) self.assertEqual(parsed.data[0].operation.name, "my_gate") self.assertEqual(list(parsed.data[0].operation.params), [0.5]) decomposed = QuantumCircuit(QuantumRegister(1, "q")) decomposed.u(0, 0, 0, 0) self.assertEqual(parsed.decompose(), decomposed) def test_qubit_barrier_in_definition(self): program = """ gate my_gate a, b { barrier a; barrier b; barrier a, b; } qreg q[2]; my_gate q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.barrier(0) my_gate_def.barrier(1) my_gate_def.barrier([0, 1]) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0, 1]) self.assertEqual(parsed, qc) def test_bare_barrier_in_definition(self): program = """ gate my_gate a, b { barrier; } qreg q[2]; my_gate q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.barrier(my_gate_def.qubits) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0, 1]) self.assertEqual(parsed, qc) def test_duplicate_barrier_in_definition(self): program = """ gate my_gate a, b { barrier a, a; barrier b, a, b; } qreg q[2]; my_gate q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.barrier(0) my_gate_def.barrier([1, 0]) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0, 1]) self.assertEqual(parsed, qc) def test_pickleable(self): program = """ include "qelib1.inc"; gate my_gate(a) b, c { rz(2 * a) b; h b; cx b, c; } qreg q[2]; my_gate(0.5) q[0], q[1]; my_gate(0.25) q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) a = Parameter("a") my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.rz(2 * a, 0) my_gate_def.h(0) my_gate_def.cx(0, 1) my_gate = gate_builder("my_gate", [a], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(0.5), [0, 1]) qc.append(my_gate(0.25), [1, 0]) self.assertEqual(parsed, qc) with io.BytesIO() as fptr: pickle.dump(parsed, fptr) fptr.seek(0) loaded = pickle.load(fptr) self.assertEqual(parsed, loaded) def test_qpy_single_call_roundtrip(self): program = """ include "qelib1.inc"; gate my_gate(a) b, c { rz(2 * a) b; h b; cx b, c; } qreg q[2]; my_gate(0.5) q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) # QPY won't persist custom gates by design choice, so instead let us check against the # explicit form it uses. my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.rz(1.0, 0) my_gate_def.h(0) my_gate_def.cx(0, 1) my_gate = Gate("my_gate", 2, [0.5]) my_gate.definition = my_gate_def qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate, [0, 1]) with io.BytesIO() as fptr: qpy.dump(parsed, fptr) fptr.seek(0) loaded = qpy.load(fptr)[0] self.assertEqual(loaded, qc) # See https://github.com/Qiskit/qiskit-terra/issues/8941 @unittest.expectedFailure def test_qpy_double_call_roundtrip(self): program = """ include "qelib1.inc"; gate my_gate(a) b, c { rz(2 * a) b; h b; cx b, c; } qreg q[2]; my_gate(0.5) q[0], q[1]; my_gate(0.25) q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) my_gate1_def = QuantumCircuit([Qubit(), Qubit()]) my_gate1_def.rz(1.0, 0) my_gate1_def.h(0) my_gate1_def.cx(0, 1) my_gate1 = Gate("my_gate", 2, [0.5]) my_gate1.definition = my_gate1_def my_gate2_def = QuantumCircuit([Qubit(), Qubit()]) my_gate2_def.rz(0.5, 0) my_gate2_def.h(0) my_gate2_def.cx(0, 1) my_gate2 = Gate("my_gate", 2, [0.25]) my_gate2.definition = my_gate2_def qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate1, [0, 1]) qc.append(my_gate2, [1, 0]) with io.BytesIO() as fptr: qpy.dump(parsed, fptr) fptr.seek(0) loaded = qpy.load(fptr)[0] self.assertEqual(loaded, qc) class TestOpaque(QiskitTestCase): def test_simple(self): program = """ opaque my_gate a; opaque my_gate2() a; qreg q[2]; my_gate q[0]; my_gate() q[1]; my_gate2 q[0]; my_gate2() q[1]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(Gate("my_gate", 1, []), [0]) qc.append(Gate("my_gate", 1, []), [1]) qc.append(Gate("my_gate2", 1, []), [0]) qc.append(Gate("my_gate2", 1, []), [1]) self.assertEqual(parsed, qc) def test_parameterised(self): program = """ opaque my_gate(a, b) c, d; qreg q[2]; my_gate(0.5, 0.25) q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(Gate("my_gate", 2, [0.5, 0.25]), [1, 0]) self.assertEqual(parsed, qc) class TestBarrier(QiskitTestCase): def test_single_register_argument(self): program = """ qreg first[3]; qreg second[3]; barrier first; barrier second; """ parsed = qiskit.qasm2.loads(program) first = QuantumRegister(3, "first") second = QuantumRegister(3, "second") qc = QuantumCircuit(first, second) qc.barrier(first) qc.barrier(second) self.assertEqual(parsed, qc) def test_single_qubit_argument(self): program = """ qreg first[3]; qreg second[3]; barrier first[1]; barrier second[0]; """ parsed = qiskit.qasm2.loads(program) first = QuantumRegister(3, "first") second = QuantumRegister(3, "second") qc = QuantumCircuit(first, second) qc.barrier(first[1]) qc.barrier(second[0]) self.assertEqual(parsed, qc) def test_empty_circuit_empty_arguments(self): program = "barrier;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit() self.assertEqual(parsed, qc) def test_one_register_circuit_empty_arguments(self): program = "qreg q1[2]; barrier;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q1")) qc.barrier(qc.qubits) self.assertEqual(parsed, qc) def test_multi_register_circuit_empty_arguments(self): program = "qreg q1[2]; qreg q2[3]; qreg q3[1]; barrier;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit( QuantumRegister(2, "q1"), QuantumRegister(3, "q2"), QuantumRegister(1, "q3") ) qc.barrier(qc.qubits) self.assertEqual(parsed, qc) def test_include_empty_register(self): program = """ qreg q[2]; qreg empty[0]; barrier empty; barrier q, empty; barrier; """ parsed = qiskit.qasm2.loads(program) q = QuantumRegister(2, "q") qc = QuantumCircuit(q, QuantumRegister(0, "empty")) qc.barrier(q) qc.barrier(qc.qubits) self.assertEqual(parsed, qc) def test_allows_duplicate_arguments(self): # There's nothing in the paper that implies this should be forbidden. program = """ qreg q1[3]; qreg q2[2]; barrier q1, q1; barrier q1[0], q1; barrier q1, q1[0]; barrier q1, q2, q1; """ parsed = qiskit.qasm2.loads(program) q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.barrier(q1) qc.barrier(q1) qc.barrier(q1) qc.barrier(q1, q2) self.assertEqual(parsed, qc) class TestMeasure(QiskitTestCase): def test_single(self): program = """ qreg q[1]; creg c[1]; measure q[0] -> c[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c")) qc.measure(0, 0) self.assertEqual(parsed, qc) def test_broadcast(self): program = """ qreg q[2]; creg c[2]; measure q -> c; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c")) qc.measure(0, 0) qc.measure(1, 1) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ qreg q[2]; creg c[2]; creg cond[1]; if (cond == 0) measure q[0] -> c[0]; if (cond == 1) measure q -> c; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"), cond) qc.measure(0, 0).c_if(cond, 0) qc.measure(0, 0).c_if(cond, 1) qc.measure(1, 1).c_if(cond, 1) self.assertEqual(parsed, qc) def test_broadcast_against_empty_register(self): program = """ qreg q_empty[0]; creg c_empty[0]; measure q_empty -> c_empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "q_empty"), ClassicalRegister(0, "c_empty")) self.assertEqual(parsed, qc) def test_conditioned_broadcast_against_empty_register(self): program = """ qreg q_empty[0]; creg c_empty[0]; creg cond[1]; if (cond == 0) measure q_empty -> c_empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit( QuantumRegister(0, "q_empty"), ClassicalRegister(0, "c_empty"), ClassicalRegister(1, "cond"), ) self.assertEqual(parsed, qc) class TestReset(QiskitTestCase): def test_single(self): program = """ qreg q[1]; reset q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.reset(0) self.assertEqual(parsed, qc) def test_broadcast(self): program = """ qreg q[2]; reset q; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.reset(0) qc.reset(1) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ qreg q[2]; creg cond[1]; if (cond == 0) reset q[0]; if (cond == 1) reset q; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), cond) qc.reset(0).c_if(cond, 0) qc.reset(0).c_if(cond, 1) qc.reset(1).c_if(cond, 1) self.assertEqual(parsed, qc) def test_broadcast_against_empty_register(self): program = """ qreg empty[0]; reset empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "empty")) self.assertEqual(parsed, qc) def test_conditioned_broadcast_against_empty_register(self): program = """ qreg empty[0]; creg cond[1]; if (cond == 0) reset empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "empty"), ClassicalRegister(1, "cond")) self.assertEqual(parsed, qc) class TestInclude(QiskitTestCase): def setUp(self): super().setUp() self.tmp_dir = pathlib.Path(tempfile.mkdtemp()) def tearDown(self): # Doesn't really matter if the removal fails, since this was a tempdir anyway; it'll get # cleaned up by the OS at some point. shutil.rmtree(self.tmp_dir, ignore_errors=True) super().tearDown() def test_qelib1_include(self): program = """ include "qelib1.inc"; qreg q[3]; u3(0.5, 0.25, 0.125) q[0]; u2(0.5, 0.25) q[0]; u1(0.5) q[0]; cx q[0], q[1]; id q[0]; x q[0]; y q[0]; z q[0]; h q[0]; s q[0]; sdg q[0]; t q[0]; tdg q[0]; rx(0.5) q[0]; ry(0.5) q[0]; rz(0.5) q[0]; cz q[0], q[1]; cy q[0], q[1]; ch q[0], q[1]; ccx q[0], q[1], q[2]; crz(0.5) q[0], q[1]; cu1(0.5) q[0], q[1]; cu3(0.5, 0.25, 0.125) q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(3, "q")) qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0]) qc.append(lib.U2Gate(0.5, 0.25), [0]) qc.append(lib.U1Gate(0.5), [0]) qc.append(lib.CXGate(), [0, 1]) qc.append(lib.UGate(0, 0, 0), [0]) # Stand-in for id. qc.append(lib.XGate(), [0]) qc.append(lib.YGate(), [0]) qc.append(lib.ZGate(), [0]) qc.append(lib.HGate(), [0]) qc.append(lib.SGate(), [0]) qc.append(lib.SdgGate(), [0]) qc.append(lib.TGate(), [0]) qc.append(lib.TdgGate(), [0]) qc.append(lib.RXGate(0.5), [0]) qc.append(lib.RYGate(0.5), [0]) qc.append(lib.RZGate(0.5), [0]) qc.append(lib.CZGate(), [0, 1]) qc.append(lib.CYGate(), [0, 1]) qc.append(lib.CHGate(), [0, 1]) qc.append(lib.CCXGate(), [0, 1, 2]) qc.append(lib.CRZGate(0.5), [0, 1]) qc.append(lib.CU1Gate(0.5), [0, 1]) qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1]) self.assertEqual(parsed, qc) def test_qelib1_after_gate_definition(self): program = """ gate bell a, b { U(pi/2, 0, pi) a; CX a, b; } include "qelib1.inc"; qreg q[2]; bell q[0], q[1]; rx(0.5) q[0]; bell q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.u(math.pi / 2, 0, math.pi, 0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) qc.rx(0.5, 0) qc.append(bell(), [1, 0]) self.assertEqual(parsed, qc) def test_include_can_define_version(self): include = """ OPENQASM 2.0; qreg inner_q[2]; """ with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write(include) program = """ OPENQASM 2.0; include "include.qasm"; """ parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) qc = QuantumCircuit(QuantumRegister(2, "inner_q")) self.assertEqual(parsed, qc) def test_can_define_gates(self): include = """ gate bell a, b { h a; cx a, b; } """ with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write(include) program = """ OPENQASM 2.0; include "qelib1.inc"; include "include.qasm"; qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_nested_include(self): inner = "creg c[2];" with open(self.tmp_dir / "inner.qasm", "w") as fp: fp.write(inner) outer = """ qreg q[2]; include "inner.qasm"; """ with open(self.tmp_dir / "outer.qasm", "w") as fp: fp.write(outer) program = """ OPENQASM 2.0; include "outer.qasm"; """ parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c")) self.assertEqual(parsed, qc) def test_first_hit_is_used(self): empty = self.tmp_dir / "empty" empty.mkdir() first = self.tmp_dir / "first" first.mkdir() with open(first / "include.qasm", "w") as fp: fp.write("qreg q[1];") second = self.tmp_dir / "second" second.mkdir() with open(second / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' parsed = qiskit.qasm2.loads(program, include_path=(empty, first, second)) qc = QuantumCircuit(QuantumRegister(1, "q")) self.assertEqual(parsed, qc) def test_qelib1_ignores_search_path(self): with open(self.tmp_dir / "qelib1.inc", "w") as fp: fp.write("qreg not_used[2];") program = 'include "qelib1.inc";' parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) qc = QuantumCircuit() self.assertEqual(parsed, qc) def test_include_from_current_directory(self): include = """ qreg q[2]; """ with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write(include) program = """ OPENQASM 2.0; include "include.qasm"; """ prevdir = os.getcwd() os.chdir(self.tmp_dir) try: parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) finally: os.chdir(prevdir) def test_load_searches_source_directory(self): with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm") qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) def test_load_searches_source_directory_last(self): first = self.tmp_dir / "first" first.mkdir() with open(first / "include.qasm", "w") as fp: fp.write("qreg q[2];") with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg not_used[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_path=(first,)) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) def test_load_searches_source_directory_prepend(self): first = self.tmp_dir / "first" first.mkdir() with open(first / "include.qasm", "w") as fp: fp.write("qreg not_used[2];") with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) parsed = qiskit.qasm2.load( self.tmp_dir / "program.qasm", include_path=(first,), include_input_directory="prepend" ) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) def test_load_can_ignore_source_directory(self): with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unable to find 'include.qasm'"): qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_input_directory=None) @ddt.ddt class TestCustomInstructions(QiskitTestCase): def test_qelib1_include_overridden(self): program = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; u3(0.5, 0.25, 0.125) q[0]; u2(0.5, 0.25) q[0]; u1(0.5) q[0]; cx q[0], q[1]; id q[0]; x q[0]; y q[0]; z q[0]; h q[0]; s q[0]; sdg q[0]; t q[0]; tdg q[0]; rx(0.5) q[0]; ry(0.5) q[0]; rz(0.5) q[0]; cz q[0], q[1]; cy q[0], q[1]; ch q[0], q[1]; ccx q[0], q[1], q[2]; crz(0.5) q[0], q[1]; cu1(0.5) q[0], q[1]; cu3(0.5, 0.25, 0.125) q[0], q[1]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(3, "q")) qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0]) qc.append(lib.U2Gate(0.5, 0.25), [0]) qc.append(lib.U1Gate(0.5), [0]) qc.append(lib.CXGate(), [0, 1]) qc.append(lib.IGate(), [0]) qc.append(lib.XGate(), [0]) qc.append(lib.YGate(), [0]) qc.append(lib.ZGate(), [0]) qc.append(lib.HGate(), [0]) qc.append(lib.SGate(), [0]) qc.append(lib.SdgGate(), [0]) qc.append(lib.TGate(), [0]) qc.append(lib.TdgGate(), [0]) qc.append(lib.RXGate(0.5), [0]) qc.append(lib.RYGate(0.5), [0]) qc.append(lib.RZGate(0.5), [0]) qc.append(lib.CZGate(), [0, 1]) qc.append(lib.CYGate(), [0, 1]) qc.append(lib.CHGate(), [0, 1]) qc.append(lib.CCXGate(), [0, 1, 2]) qc.append(lib.CRZGate(0.5), [0, 1]) qc.append(lib.CU1Gate(0.5), [0, 1]) qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1]) self.assertEqual(parsed, qc) # Also test that the output matches what Qiskit puts out. from_qiskit = QuantumCircuit.from_qasm_str(program) self.assertEqual(parsed, from_qiskit) def test_qelib1_sparse_overrides(self): """Test that the qelib1 special import still works as expected when a couple of gates in the middle of it are custom. As long as qelib1 is handled specially, there is a risk that this handling will break in weird ways when custom instructions overlap it.""" program = """ include "qelib1.inc"; qreg q[3]; u3(0.5, 0.25, 0.125) q[0]; u2(0.5, 0.25) q[0]; u1(0.5) q[0]; cx q[0], q[1]; id q[0]; x q[0]; y q[0]; z q[0]; h q[0]; s q[0]; sdg q[0]; t q[0]; tdg q[0]; rx(0.5) q[0]; ry(0.5) q[0]; rz(0.5) q[0]; cz q[0], q[1]; cy q[0], q[1]; ch q[0], q[1]; ccx q[0], q[1], q[2]; crz(0.5) q[0], q[1]; cu1(0.5) q[0], q[1]; cu3(0.5, 0.25, 0.125) q[0], q[1]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("id", 0, 1, lib.IGate), qiskit.qasm2.CustomInstruction("h", 0, 1, lib.HGate), qiskit.qasm2.CustomInstruction("crz", 1, 2, lib.CRZGate), ], ) qc = QuantumCircuit(QuantumRegister(3, "q")) qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0]) qc.append(lib.U2Gate(0.5, 0.25), [0]) qc.append(lib.U1Gate(0.5), [0]) qc.append(lib.CXGate(), [0, 1]) qc.append(lib.IGate(), [0]) qc.append(lib.XGate(), [0]) qc.append(lib.YGate(), [0]) qc.append(lib.ZGate(), [0]) qc.append(lib.HGate(), [0]) qc.append(lib.SGate(), [0]) qc.append(lib.SdgGate(), [0]) qc.append(lib.TGate(), [0]) qc.append(lib.TdgGate(), [0]) qc.append(lib.RXGate(0.5), [0]) qc.append(lib.RYGate(0.5), [0]) qc.append(lib.RZGate(0.5), [0]) qc.append(lib.CZGate(), [0, 1]) qc.append(lib.CYGate(), [0, 1]) qc.append(lib.CHGate(), [0, 1]) qc.append(lib.CCXGate(), [0, 1, 2]) qc.append(lib.CRZGate(0.5), [0, 1]) qc.append(lib.CU1Gate(0.5), [0, 1]) qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1]) self.assertEqual(parsed, qc) def test_user_gate_after_overidden_qelib1(self): program = """ include "qelib1.inc"; qreg q[1]; opaque my_gate q; my_gate q[0]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(Gate("my_gate", 1, []), [0]) self.assertEqual(parsed, qc) def test_qiskit_extra_builtins(self): program = """ qreg q[5]; u(0.5 ,0.25, 0.125) q[0]; p(0.5) q[0]; sx q[0]; sxdg q[0]; swap q[0], q[1]; cswap q[0], q[1], q[2]; crx(0.5) q[0], q[1]; cry(0.5) q[0], q[1]; cp(0.5) q[0], q[1]; csx q[0], q[1]; cu(0.5, 0.25, 0.125, 0.0625) q[0], q[1]; rxx(0.5) q[0], q[1]; rzz(0.5) q[0], q[1]; rccx q[0], q[1], q[2]; rc3x q[0], q[1], q[2], q[3]; c3x q[0], q[1], q[2], q[3]; c3sqrtx q[0], q[1], q[2], q[3]; c4x q[0], q[1], q[2], q[3], q[4]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(5, "q")) qc.append(lib.UGate(0.5, 0.25, 0.125), [0]) qc.append(lib.PhaseGate(0.5), [0]) qc.append(lib.SXGate(), [0]) qc.append(lib.SXdgGate(), [0]) qc.append(lib.SwapGate(), [0, 1]) qc.append(lib.CSwapGate(), [0, 1, 2]) qc.append(lib.CRXGate(0.5), [0, 1]) qc.append(lib.CRYGate(0.5), [0, 1]) qc.append(lib.CPhaseGate(0.5), [0, 1]) qc.append(lib.CSXGate(), [0, 1]) qc.append(lib.CUGate(0.5, 0.25, 0.125, 0.0625), [0, 1]) qc.append(lib.RXXGate(0.5), [0, 1]) qc.append(lib.RZZGate(0.5), [0, 1]) qc.append(lib.RCCXGate(), [0, 1, 2]) qc.append(lib.RC3XGate(), [0, 1, 2, 3]) qc.append(lib.C3XGate(), [0, 1, 2, 3]) qc.append(lib.C3SXGate(), [0, 1, 2, 3]) qc.append(lib.C4XGate(), [0, 1, 2, 3, 4]) self.assertEqual(parsed, qc) # There's also the 'u0' gate, but this is weird so we don't wildly care what its definition # is and it has no Qiskit equivalent, so we'll just test that it using it doesn't produce an # error. parsed = qiskit.qasm2.loads( "qreg q[1]; u0(1) q[0];", custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) self.assertEqual(parsed.data[0].operation.name, "u0") def test_qiskit_override_delay_opaque(self): program = """ opaque delay(t) q; qreg q[1]; delay(1) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.delay(1, 0, unit="dt") self.assertEqual(parsed, qc) def test_qiskit_override_u0_opaque(self): program = """ opaque u0(n) q; qreg q[1]; u0(2) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.id(0) qc.id(0) self.assertEqual(parsed.decompose(), qc) def test_can_override_u(self): program = """ qreg q[1]; U(0.5, 0.25, 0.125) q[0]; """ class MyGate(Gate): def __init__(self, a, b, c): super().__init__("u", 1, [a, b, c]) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("U", 3, 1, MyGate, builtin=True)], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5, 0.25, 0.125), [0]) self.assertEqual(parsed, qc) def test_can_override_cx(self): program = """ qreg q[2]; CX q[0], q[1]; """ class MyGate(Gate): def __init__(self): super().__init__("cx", 2, []) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 2, MyGate, builtin=True)], ) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(MyGate(), [0, 1]) self.assertEqual(parsed, qc) @ddt.data(lambda x: x, reversed) def test_can_override_both_builtins_with_other_gates(self, order): program = """ gate unimportant q {} qreg q[2]; U(0.5, 0.25, 0.125) q[0]; CX q[0], q[1]; """ class MyUGate(Gate): def __init__(self, a, b, c): super().__init__("u", 1, [a, b, c]) class MyCXGate(Gate): def __init__(self): super().__init__("cx", 2, []) custom = [ qiskit.qasm2.CustomInstruction("unused", 0, 1, lambda: Gate("unused", 1, [])), qiskit.qasm2.CustomInstruction("U", 3, 1, MyUGate, builtin=True), qiskit.qasm2.CustomInstruction("CX", 0, 2, MyCXGate, builtin=True), ] custom = order(custom) parsed = qiskit.qasm2.loads(program, custom_instructions=custom) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(MyUGate(0.5, 0.25, 0.125), [0]) qc.append(MyCXGate(), [0, 1]) self.assertEqual(parsed, qc) def test_custom_builtin_gate(self): program = """ qreg q[1]; builtin(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("builtin", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True) ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_builtin_as_gate(self): program = """ qreg q[1]; gate builtin(t) q {} builtin(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("builtin", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True) ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_builtin_as_opaque(self): program = """ qreg q[1]; opaque builtin(t) q; builtin(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("builtin", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True) ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_custom_as_gate(self): program = """ qreg q[1]; gate my_gate(t) q {} my_gate(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("my_gate", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)] ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_custom_as_opaque(self): program = """ qreg q[1]; opaque my_gate(t) q; my_gate(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("my_gate", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)] ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) class TestCustomClassical(QiskitTestCase): def test_qiskit_extensions(self): program = """ include "qelib1.inc"; qreg q[1]; rx(asin(0.3)) q[0]; ry(acos(0.3)) q[0]; rz(atan(0.3)) q[0]; """ parsed = qiskit.qasm2.loads(program, custom_classical=qiskit.qasm2.LEGACY_CUSTOM_CLASSICAL) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.rx(math.asin(0.3), 0) qc.ry(math.acos(0.3), 0) qc.rz(math.atan(0.3), 0) self.assertEqual(parsed, qc) def test_zero_parameter_custom(self): program = """ qreg q[1]; U(f(), 0, 0) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: 0.2)] ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.u(0.2, 0, 0, 0) self.assertEqual(parsed, qc) def test_multi_parameter_custom(self): program = """ qreg q[1]; U(f(0.2), g(0.4, 0.1), h(1, 2, 3)) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_classical=[ qiskit.qasm2.CustomClassical("f", 1, lambda x: 1 + x), qiskit.qasm2.CustomClassical("g", 2, math.atan2), qiskit.qasm2.CustomClassical("h", 3, lambda x, y, z: z - y + x), ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.u(1.2, math.atan2(0.4, 0.1), 2, 0) self.assertEqual(parsed, qc) def test_use_in_gate_definition(self): # pylint: disable=invalid-name program = """ gate my_gate(a, b) q { U(f(a, b), g(f(b, f(b, a))), b) q; } qreg q[1]; my_gate(0.5, 0.25) q[0]; my_gate(0.25, 0.5) q[0]; """ f = lambda x, y: x - y g = lambda x: 2 * x parsed = qiskit.qasm2.loads( program, custom_classical=[ qiskit.qasm2.CustomClassical("f", 2, f), qiskit.qasm2.CustomClassical("g", 1, g), ], ) first_gate = parsed.data[0].operation second_gate = parsed.data[1].operation self.assertEqual(list(first_gate.params), [0.5, 0.25]) self.assertEqual(list(second_gate.params), [0.25, 0.5]) self.assertEqual( list(first_gate.definition.data[0].operation.params), [ f(0.5, 0.25), g(f(0.25, f(0.25, 0.5))), 0.25, ], ) self.assertEqual( list(second_gate.definition.data[0].operation.params), [ f(0.25, 0.5), g(f(0.5, f(0.5, 0.25))), 0.5, ], ) @ddt.ddt class TestStrict(QiskitTestCase): @ddt.data( "gate my_gate(p0, p1$) q0, q1 {}", "gate my_gate(p0, p1) q0, q1$ {}", "opaque my_gate(p0, p1$) q0, q1;", "opaque my_gate(p0, p1) q0, q1$;", 'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125$) q[0], q[1];', 'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1]$;', "qreg q[2]; barrier q[0], q[1]$;", 'include "qelib1.inc"; qreg q[1]; rx(sin(pi$)) q[0];', ) def test_trailing_comma(self, program): without = qiskit.qasm2.loads("OPENQASM 2.0;\n" + program.replace("$", ""), strict=True) with_ = qiskit.qasm2.loads(program.replace("$", ","), strict=False) self.assertEqual(with_, without) def test_trailing_semicolon_after_gate(self): program = """ include "qelib1.inc"; gate bell a, b { h a; cx a, b; }; // <- the important bit of the test qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_empty_statement(self): # This is allowed more as a side-effect of allowing the trailing semicolon after gate # definitions. program = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; h q[0]; ; cx q[0], q[1]; ;;;; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.h(0) qc.cx(0, 1) self.assertEqual(parsed, qc) def test_single_quoted_path(self): program = """ include 'qelib1.inc'; qreg q[1]; h q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.h(0) self.assertEqual(parsed, qc)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.cp(pi/2, 1, 2) qc.cp(pi/4, 0, 2) qc.h(1) qc.cp(pi/2, 0, 1) qc.h(0) qc.swap(0, 2) qc.draw() def qft_rotations(circuit, n): if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): qft_rotations(circuit, n) swap_registers(circuit, n) return circuit qc = QuantumCircuit(4) qft(qc,4) qc.draw() # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 (101 in binary) qc.x(0) qc.x(2) qc.draw() sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qft(qc, 3) qc.draw() qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.drivers.second_quantization import GaussianForcesDriver from qiskit_nature.problems.second_quantization import VibrationalStructureProblem from qiskit_nature.settings import settings settings.dict_aux_operators = True driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2) # 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["VibrationalEnergy"] print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) # this is now done explicitly and already requires the basis problem = driver.run(basis=basis) problem.hamiltonian.truncation_order = 2 hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers.second_quantization import GaussianLogResult from qiskit_nature.properties.second_quantization.vibrational.bases import HarmonicBasis from qiskit_nature.settings import settings settings.dict_aux_operators = True log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log") hamiltonian = log_result.get_vibrational_energy() print(hamiltonian) hamiltonian.basis = HarmonicBasis([2, 2, 3, 4]) op = hamiltonian.second_q_ops()["VibrationalEnergy"] print("\n".join(str(op).splitlines()[:10] + ["..."])) from qiskit_nature.second_q.drivers import GaussianLogResult from qiskit_nature.second_q.formats import watson_to_problem from qiskit_nature.second_q.problems import HarmonicBasis log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log") watson = log_result.get_watson_hamiltonian() print(watson) basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) problem = watson_to_problem(watson, basis) hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers.second_quantization import GaussianForcesDriver from qiskit_nature.problems.second_quantization import VibrationalStructureProblem driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2) # we trigger driver.run() implicitly like so: second_q_ops = problem.second_q_ops() hamiltonian_op = second_q_ops.pop("VibrationalEnergy") aux_ops = second_q_ops from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) problem = driver.run(basis=basis) problem.hamiltonian.truncation_order = 2 hamiltonian_op, aux_ops = problem.second_q_ops() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/abbarreto/qiskit2
abbarreto
from qiskit import * nshots = 8192 qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') simulator = Aer.get_backend('qasm_simulator') device = provider.get_backend('ibmq_bogota') from qiskit.tools.monitor import job_monitor from qiskit.tools.visualization import plot_histogram def qc_ent_dist(): qc = QuantumCircuit(2, name = 'E dist') qc.h([1]); qc.cx(1, 0) return qc qc_ent_dist_ = qc_ent_dist(); qc_ent_dist_.draw(output = 'mpl') def qc_encoding(cbits): qc = QuantumCircuit(1, name = 'codificação') if cbits == '00': qc.id([0]) elif cbits == '01': qc.z([0]) elif cbits == '10': qc.x([0]) elif cbits == '11': qc.x([0]); qc.z([0]) return qc qc_encoding_ = qc_encoding('11'); qc_encoding_.draw(output = 'mpl') def qc_decoding(): qc = QuantumCircuit(2, name = 'decodificação') qc.cx(1, 0); qc.h([1]) return qc qc_decoding_ = qc_decoding(); qc_decoding_.draw(output = 'mpl') cbits = '00' qc = QuantumCircuit(2, 2) qc_ent_dist_ = qc_ent_dist(); qc.append(qc_ent_dist_, [0,1]) qc.barrier() qc_encoding_ = qc_encoding(cbits); qc.append(qc_encoding_, [0]) qc.barrier() qc_decoding_ = qc_decoding(); qc.append(qc_decoding_, [0,1]) qc.measure([0,1],[0,1]) #qc.draw(output = 'mpl') qc.decompose().draw(output = 'mpl') result = execute(qc, backend = simulator, shots = nshots).result() plot_histogram(result.get_counts(qc)) job = execute(qc, backend = device, shots = nshots) job_monitor(job) plot_histogram(job.result().get_counts(qc))
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/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
# !sudo apt install lrslib # !pip install -e git+https://github.com/Pitt-JonesLab/mirror-gates#egg=mirror-gates[core] # !pip install pylatexenc from qiskit.transpiler import CouplingMap coupling_map = CouplingMap.from_line(4) from transpile_benchy.library import CircuitLibrary lib = CircuitLibrary(circuit_list=[]) qc = lib.get_circuit("qft_n4") qc = qc.decompose() display(qc.draw("mpl")) from mirror_gates.pass_managers import Mirage mirage = Mirage( coupling_map, # coupling map name="Mirage-$\sqrt{\texttt{iSWAP}}$", # transpile_benchy and figure labels) parallel=True, # run trials in parallel or serial cx_basis=False, # turning on sets CNOT as the basis gate, # (can take arbitrary basis but parameters are not configured that way yet) cost_function="depth", # switch to "basic" for counting SWAPs fixed_aggression=None, # force aggression level on all iterations layout_trials=None, # how many independent layout trials to run (20) fb_iters=None, # how many forward-backward iterations to run (4) swap_trials=None, # how many independent routing trials to run (20) no_vf2=False, # keep False to use VF2 for finding complete layouts logger=None, # from logging moduel ) mirage_qc = mirage.run(circuit=qc) mirage_qc.draw("mpl") # from qiskit import transpile # from mirror_gates import sqiswap_equiv # mirage_qc = transpile( # qc, # optimization_level=3, # coupling_map=coupling_map, # basis_gates=["u", "xx_plus_yy", "id"], # routing_method="mirage", # layout_method="sabre_layout_v2", # ) # mirage_qc.draw("mpl")
https://github.com/andre-juan/quantum_nearest_neighbors
andre-juan
import numpy as np from scipy.linalg import expm from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute from qiskit.circuit import AncillaQubit from qiskit.visualization import plot_histogram from qiskit.circuit.library.standard_gates import XGate, ZGate, HGate from qiskit.circuit.add_control import add_control from qiskit.extensions import UnitaryGate def test_circuit(qc): ''' auxiliar function, to test intermediate steps, looking at measurement results this function allows the inspection of the amplitudes of states, at any point of the circuit (call it with the desired circuit) ''' cr = ClassicalRegister(qc.num_qubits, "m_cl") qc_cr = QuantumCircuit(cr) qc_test = qc + qc_cr for i in range(qc.num_qubits): qc_test.measure(i, i) ################################# backend = Aer.get_backend("qasm_simulator") job = execute(qc_test, backend, shots=1e5, seed_simulator=42) results = job.result() counts = results.get_counts() return plot_histogram(counts, title="Results", figsize=(12, 4)) qr_input = QuantumRegister(4, "i") qc_input = QuantumCircuit(qr_input) x = "0010" for i in range(len(x)): if x[i] == "1": qc_input.x(i) qc_input.draw("mpl") test_circuit(qc_input) X = np.array([[0, 0, 0, 0], [0, 0, 0, 1], [1, 1, 1, 0], [1, 1, 1, 1]]) # number of examples N = X.shape[0] # number of features n = X.shape[1] y = np.array([0, 0, 1, 1]) # full dataset, of the form [[X], [y]] dataset = np.append(X, y.reshape((-1, 1)), axis=1) # n+1 because the last register will encode the class! amplitudes = np.zeros(2**(n+1)) amplitudes # integer representation of binary strings in training dataset # notice the [::-1], which is necessary to adjust the endianness! data_points_X = [int("".join(str(i) for i in X[j])[::-1], 2) for j in range(dataset.shape[0])] data_points_X # integer representation considering also the class # IMPORTANT: sum 2**n for elements in class 1 # this is necessary to encode also the class! data_points = [x + 2**n if y[i] == 1 else x for i, x in enumerate(data_points_X)] data_points amplitudes[data_points] = 1 amplitudes = amplitudes/np.sqrt(amplitudes.sum()) amplitudes qr_features = QuantumRegister(n, "f") qr_class = QuantumRegister(1, "cl") qc_training = QuantumCircuit(qr_features, qr_class) qc_training.initialize(amplitudes, [qr_features, qr_class]) qc_training.draw("mpl") test_circuit(qc_training) dataset qr_anc = QuantumRegister(1, "anc") qc_anc = QuantumCircuit(qr_anc) qc_anc.draw("mpl") qc = qc_input + qc_training + qc_anc qc.barrier() qc.draw("mpl") test_circuit(qc) qc.h(-1) qc.barrier() qc.draw("mpl") for i in range(4): qc.cnot(i, 4+i) qc.barrier() qc.draw("mpl") # matrices of 1 and \sigma_z to be exponentiated below # source of the matrix exponential methods below: # https://quantumcomputing.stackexchange.com/questions/10317/quantum-circuit-to-implement-matrix-exponential idtt = np.eye(2) sz = np.array([[1,0], [0,-1]]) # define the exponentiated unitaries U_1_minus = expm(-1j * (np.pi/(2*4)) * ((idtt-sz)/2)) U_1_plus = expm(1j * (np.pi/(2*4)) * ((idtt-sz)/2)) # defining controlled gates u1m = add_control(operation=UnitaryGate(U_1_minus, label="$U_1^-$"), num_ctrl_qubits=1, ctrl_state=0, label="$CU_1^-$") u1p = add_control(operation=UnitaryGate(U_1_plus, label="$U_1^+$"), num_ctrl_qubits=1, ctrl_state=1, label="$CU_1^+$") # build a circuit to apply the unitary above # this will be combined with the main circuit later on (notice: same registers!!). qc_u = QuantumCircuit(qr_features, qr_anc) for i in range(4): # apply the unitaries qc_u.append(u1p, [qr_anc[0], qr_features[i]]) qc_u.append(u1m, [qr_anc[0], qr_features[i]]) # # decompose this portion of the circuit # # (this will be appended to the main circuit later on) # qc_u = qc_u.decompose() qc_u.draw("mpl") qr_input = QuantumRegister(4, "i") qr_features = QuantumRegister(4, "f") qr_class = QuantumRegister(1, "cl") qr_anc = QuantumRegister(1, "anc") qc_prep = QuantumCircuit(qr_input, qr_features, qr_class, qr_anc) # build the state |0010,0110,0 ;1⟩ + |0010,0110,0 ;0⟩ # input qc_prep.x(qr_input[2]) # hamming ditance # qc_prep.x(qr_features[1]) # qc_prep.x(qr_features[2]) qc_prep.x(qr_features[3]) # ancilla qc_prep.h(qr_anc[0]) qc_prep.barrier() ################################################## qc_test = qc_prep.combine(qc_u) qc_test.barrier() ################################################## qc_test.h(qr_anc[0]) qc_test.barrier() ################################################## cr = ClassicalRegister(qc_test.num_qubits, "c") qc_cr = QuantumCircuit(cr) qc_test = qc_test + qc_cr for i in range(qc_test.num_qubits): qc_test.measure(i, i) ################################################## qc_test.draw("mpl") cr = ClassicalRegister(qc_test.num_qubits, "c") qc_cr = QuantumCircuit(cr) qc_prep = qc_prep + qc_cr for i in range(qc_prep.num_qubits): qc_prep.measure(i, i) backend = Aer.get_backend("qasm_simulator") job = execute(qc_prep, backend, shots=1e5, seed_simulator=42) results = job.result() counts = results.get_counts() plot_histogram(counts, title="Results", figsize=(12, 4)) backend = Aer.get_backend("qasm_simulator") job = execute(qc_test, backend, shots=1e5, seed_simulator=42) results = job.result() counts = results.get_counts() plot_histogram(counts, title="Results", figsize=(12, 4)) print("Ancila 0") (np.cos(np.pi/8))**2 print("Ancila 1") (np.sin(np.pi/8))**2 qc = qc.combine(qc_u) qc.barrier() qc.draw("mpl") qc.h(-1) qc.barrier() qc.draw("mpl", scale=0.75) # copying the qc so far, before measurement qc_bckp = qc.copy() qc = qc_bckp.copy() cr = ClassicalRegister(qc.num_qubits, "c") qc_cr = QuantumCircuit(cr) qc = qc + qc_cr for i in range(qc.num_qubits): qc.measure(i, i) # qc.draw("mpl") backend = Aer.get_backend("qasm_simulator") job = execute(qc, backend, shots=1e5, seed_simulator=42) results = job.result() counts = results.get_counts() plot_histogram(counts, title="Results", figsize=(12, 4)) # using the same endiannes of qiskit, i.e., |0010,0010,0;0> = 0001000100 {"0001000100" : round((0.25)*(np.cos(np.pi/8))**2, 3), "1001000100" : round((0.25)*(np.sin(np.pi/8))**2, 3), "0011000100" : round((0.25)*(np.cos(2*np.pi/8))**2, 3), "1011000100" : round((0.25)*(np.sin(2*np.pi/8))**2, 3), "0100110100" : round((0.25)*(np.cos(2*np.pi/8))**2, 3), "1100110100" : round((0.25)*(np.sin(2*np.pi/8))**2, 3), "0110110100" : round((0.25)*(np.cos(3*np.pi/8))**2, 3), "1110110100" : round((0.25)*(np.sin(3*np.pi/8))**2, 3)} qc = qc_bckp.copy() # first, lets's measure the ancilla cr_anc = ClassicalRegister(1, "c_anc") qc_cr_anc = QuantumCircuit(cr_anc) qc_cr_anc.draw("mpl") qc = qc + qc_cr_anc qc.measure(qr_anc, cr_anc[0]) # qc.draw("mpl", scale=0.7) # theoretical probability of measuring ancilla in |0> (0.25)*((np.cos(np.pi/8))**2 + 2*(np.cos(2*np.pi/8))**2 + (np.cos(3*np.pi/8))**2) backend = Aer.get_backend("qasm_simulator") job = execute(qc, backend, shots=1e4, seed_simulator=42) results = job.result() counts = results.get_counts() plot_histogram(counts, title="Results", figsize=(12, 4)) qc = qc_bckp.copy() cr_anc = ClassicalRegister(1, "c_anc") qc_cr_anc = QuantumCircuit(cr_anc) cr_class = ClassicalRegister(1, "c_class") qc_cr_class = QuantumCircuit(cr_class) qc = qc + qc_cr_anc + qc_cr_class qc.measure(qr_anc, cr_anc) qc.measure(qr_class, cr_class) qc.draw("mpl") backend = Aer.get_backend("qasm_simulator") job = execute(qc, backend, shots=1e4, seed_simulator=42) results = job.result() counts = results.get_counts() # filtering out measurements of ancila = |1> (last register) keys = list(counts.keys()).copy() for key in keys: if key[-1] == "1": counts.pop(key) plot_histogram(counts, title="Results", figsize=(12, 4)) # theoretical probability of measuring class qubit in |0>, given ancilla was in |0> (0.5)*((np.cos(np.pi/8))**2 + (np.cos(2*np.pi/8))**2) # probability of measuring class qubit in |1>, given ancilla was in |0> (0.5)*((np.cos(2*np.pi/8))**2 + (np.cos(3*np.pi/8))**2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl')
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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. """Example on how to load a file into a QuantumCircuit.""" from qiskit import QuantumCircuit from qiskit import execute, BasicAer circ = QuantumCircuit.from_qasm_file("examples/qasm/entangled_registers.qasm") print(circ) # See the backend sim_backend = BasicAer.get_backend("qasm_simulator") # Compile and run the Quantum circuit on a local simulator backend job_sim = execute(circ, sim_backend) sim_result = job_sim.result() # Show the results print("simulation: ", sim_result) print(sim_result.get_counts(circ))
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
Keerthiraj-Nagaraj
from IPython.display import Image, display Image("ryoko.png", width="70") Image('asteroids_example.png') Image('asteroids_beam_example.png') Image('false_asteroids_example.png') Image('asteroids_example.png') problem_set = \ [[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '3']], [['0', '0'], ['1', '1'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '1'], ['1', '3'], ['3', '2'], ['3', '3']], [['0', '2'], ['1', '0'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '1'], ['3', '3']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '3'], ['1', '2'], ['2', '2'], ['2', '3'], ['3', '0']], [['0', '3'], ['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '3'], ['2', '1'], ['2', '3'], ['3', '0']], [['0', '1'], ['0', '3'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '2']], [['0', '0'], ['1', '3'], ['2', '0'], ['2', '1'], ['2', '3'], ['3', '1']], [['0', '1'], ['0', '2'], ['1', '0'], ['1', '2'], ['2', '2'], ['2', '3']], [['0', '3'], ['1', '0'], ['1', '3'], ['2', '1'], ['2', '2'], ['3', '0']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '3'], ['3', '0'], ['3', '1']], [['0', '1'], ['1', '0'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '1']]] def week3_ans_func(problem_set): ##### build your quantum circuit here ##### In addition, please make it a function that can solve the problem even with different inputs (problem_set). We do validation with different inputs. #### Code for Grover's algorithm with iterations = 1 will be as follows. #### for i in range(1): #### oracle() #### diffusion() return qc # Submission code from qc_grader import grade_ex3, prepare_ex3, submit_ex3 # Execute your circuit with following prepare_ex3() function. # The prepare_ex3() function works like the execute() function with only QuantumCircuit as an argument. job = prepare_ex3(week3_ans_func) result = job.result() counts = result.get_counts() original_problem_set_counts = counts[0] original_problem_set_counts # The bit string with the highest number of observations is treated as the solution. # Check your answer by executing following code. # The quantum cost of the QuantumCircuit is obtained as the score. The lower the cost, the better. grade_ex3(job) # Submit your results by executing following code. You can submit as many times as you like during the period. submit_ex3(job)
https://github.com/microsoft/qiskit-qir
microsoft
## # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. ## from qiskit_qir.translate import to_qir_module from qiskit import QuantumCircuit, ClassicalRegister from qiskit.circuit import Parameter import numpy as np from pyqir import Context, Module, is_entry_point from typing import List import test_utils import pytest def get_parameterized_circuit(num_qubits: int, num_params: int) -> List[QuantumCircuit]: theta_range = np.linspace(0, 2 * np.pi, num_params) theta = Parameter("θ") circuit = QuantumCircuit(num_qubits, 1) circuit.h(0) for i in range(num_qubits - 1): circuit.cx(i, i + 1) circuit.barrier() circuit.rz(theta, range(num_qubits)) circuit.barrier() for i in reversed(range(num_qubits - 1)): circuit.cx(i, i + 1) circuit.h(0) circuit.measure(0, 0) circuits = [ circuit.assign_parameters({theta: theta_val}, inplace=False) for theta_val in theta_range ] return circuits @pytest.mark.parametrize("num_params", [1, 2, 3]) def test_binding_generates_corresponding_entry_points(num_params: int) -> None: circuits = get_parameterized_circuit(2, num_params) bitcode = to_qir_module(circuits)[0].bitcode mod = Module.from_bitcode(Context(), bitcode) funcs = list(filter(is_entry_point, mod.functions)) assert len(funcs) == num_params def test_batch_entry_points_use_circuit_names() -> None: qc1 = QuantumCircuit(1, name="first") qc2 = QuantumCircuit(1, name="second") module, entry_points = to_qir_module(list([qc1, qc2])) mod = Module.from_bitcode(Context(), module.bitcode) functions = list(filter(is_entry_point, mod.functions)) assert len(functions) == 2 for function in functions: assert function.name in ["first", "second"] assert entry_points == list([x.name for x in functions]) def test_batch_entry_points_make_unique_names_on_duplicates() -> None: name = "first" qc1 = QuantumCircuit(1, name=name) qc2 = QuantumCircuit(1, name=name) module, entry_points = to_qir_module(list([qc1, qc2])) mod = Module.from_bitcode(Context(), module.bitcode) functions = list(filter(is_entry_point, mod.functions)) assert len(functions) == 2 for function in functions: assert function.name.startswith(name) assert functions[0].name != functions[1].name assert entry_points == list([x.name for x in functions]) def test_batch_entry_points_have_appropriate_attributes() -> None: qc1 = QuantumCircuit(1, 2, name="first") qc2 = QuantumCircuit(1, name="second") qc3 = QuantumCircuit(name="second") qc4 = QuantumCircuit(name="second") cr = ClassicalRegister(2, "creg") qc4.add_register(cr) bitcode = to_qir_module(list([qc1, qc2, qc3, qc4]))[0].bitcode mod = Module.from_bitcode(Context(), bitcode) functions = list(filter(is_entry_point, mod.functions)) assert len(functions) == 4 test_utils.check_attributes_on_entrypoint(functions[0], 1, 2) test_utils.check_attributes_on_entrypoint(functions[1], 1) test_utils.check_attributes_on_entrypoint(functions[2]) test_utils.check_attributes_on_entrypoint(functions[3], expected_results=2) def test_passing_list_with_non_quantum_circuits_raises_value_error() -> None: qc = QuantumCircuit(1) with pytest.raises(ValueError): _ = to_qir_module(list([qc, 2])) with pytest.raises(ValueError): _ = to_qir_module(list([2, qc])) with pytest.raises(ValueError): _ = to_qir_module(list([2])) with pytest.raises(ValueError): _ = to_qir_module(list([qc, 2, qc])) def test_passing_non_quantum_circuits_raises_value_error() -> None: with pytest.raises(ValueError): _ = to_qir_module(2) def test_passing_empty_list_of_quantum_circuits_raises_value_error() -> None: with pytest.raises(ValueError): _ = to_qir_module(list([]))
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.x(0).c_if(cr, 0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl')
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # 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 = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/Spintronic6889/Introduction-of-Quantum-walk-its-application-on-search-and-decision-making
Spintronic6889
!python --version !pip install qiskit !pip install pylatexenc from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram from qiskit.visualization import plot_state_city from random import randrange from qiskit.tools.monitor import job_monitor %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import random import math #discrete time quantum random walk with a hadamard coin n=2 steps=1 qpos = QuantumRegister(n,'qpos') qcoin = QuantumRegister(1,'qcoin') cpos = ClassicalRegister(n,'cr') QC = QuantumCircuit(qpos, qcoin) #initialized #QC.x(qcoin[0]) for i in range(steps): #coin QC.h(qcoin[0]) QC.barrier() #increment gate operator for i in range(n): QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') QC.barrier() #decrement gate operator QC.x(qcoin[0]) for i in range(n): if i+1 < n: QC.x(qpos[i+1:]) QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') if i+1 < n: QC.x(qpos[i+1:]) QC.barrier() a=n/2 p=math.floor(a) #print(p) for k in range(n): if(k<p): QC.swap(qpos[n-1-k],qpos[k]) #print(a) display(QC.draw(output="mpl")) QC.measure_all() # # Execute the circuit on the qasm simulator job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000) counts = job.result().get_counts(QC) print(counts) plot_histogram(counts, color='midnightblue', title="New Histogram") #aer_sim = Aer.get_backend('aer_simulator') #qobj = assemble(had) #result = aer_sim.run(qobj).result() #counts = result.get_counts() #plot_histogram(counts) #discrete time quantum random walk with a hadamard coin n=2 steps=2 qpos = QuantumRegister(n,'qpos') qcoin = QuantumRegister(1,'qcoin') cpos = ClassicalRegister(n,'cr') QC = QuantumCircuit(qpos, qcoin) #initialized #QC.x(qcoin[0]) for i in range(steps): #coin QC.h(qcoin[0]) QC.barrier() #increment gate operator for i in range(n): QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') QC.barrier() #decrement gate operator QC.x(qcoin[0]) for i in range(n): if i+1 < n: QC.x(qpos[i+1:]) QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') if i+1 < n: QC.x(qpos[i+1:]) QC.barrier() a=n/2 p=math.floor(a) #print(p) for k in range(n): if(k<p): QC.swap(qpos[n-1-k],qpos[k]) #print(a) display(QC.draw(output="mpl")) QC.measure_all() # # Execute the circuit on the qasm simulator job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000) counts = job.result().get_counts(QC) print(counts) plot_histogram(counts, color='midnightblue', title="New Histogram") #aer_sim = Aer.get_backend('aer_simulator') #qobj = assemble(had) #result = aer_sim.run(qobj).result() #counts = result.get_counts() #plot_histogram(counts) #discrete time quantum random walk with a hadamard coin n=2 steps=3 qpos = QuantumRegister(n,'qpos') qcoin = QuantumRegister(1,'qcoin') cpos = ClassicalRegister(n,'cr') QC = QuantumCircuit(qpos, qcoin) #initialized #QC.x(qcoin[0]) for i in range(steps): #coin QC.h(qcoin[0]) QC.barrier() #increment gate operator for i in range(n): QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') QC.barrier() #decrement gate operator QC.x(qcoin[0]) for i in range(n): if i+1 < n: QC.x(qpos[i+1:]) QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') if i+1 < n: QC.x(qpos[i+1:]) QC.barrier() a=n/2 p=math.floor(a) #print(p) for k in range(n): if(k<p): QC.swap(qpos[n-1-k],qpos[k]) #print(a) display(QC.draw(output="mpl")) QC.measure_all() # # Execute the circuit on the qasm simulator job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000) counts = job.result().get_counts(QC) print(counts) plot_histogram(counts, color='midnightblue', title="New Histogram") #aer_sim = Aer.get_backend('aer_simulator') #qobj = assemble(had) #result = aer_sim.run(qobj).result() #counts = result.get_counts() #plot_histogram(counts) from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city #discrete time quantum random walk with a hadamard coin n=3 steps=11 qpos = QuantumRegister(n,'qpos') qcoin = QuantumRegister(1,'qcoin') cpos = ClassicalRegister(n,'cr') QC = QuantumCircuit(qpos, qcoin) #initialized #QC.x(qcoin[0]) for i in range(steps): #coin QC.h(qcoin[0]) QC.barrier() #increment gate operator for i in range(n): QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') QC.barrier() #decrement gate operator QC.x(qcoin[0]) for i in range(n): if i+1 < n: QC.x(qpos[i+1:]) QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') if i+1 < n: QC.x(qpos[i+1:]) QC.barrier() a=n/2 p=math.floor(a) #print(p) for k in range(n): if(k<p): QC.swap(qpos[n-1-k],qpos[k]) #print(a) display(QC.draw(output="mpl")) state = DensityMatrix.from_instruction(QC) plot_state_city(state,figsize=(15, 8), color=['midnightblue', 'midnightblue'], title="New State City") QC.measure_all() # # Execute the circuit on the qasm simulator job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000) counts = job.result().get_counts(QC) print(counts) plot_histogram(counts, figsize=(10, 2), color='midnightblue', title="New Histogram") #aer_sim = Aer.get_backend('aer_simulator') #qobj = assemble(had) #result = aer_sim.run(qobj).result() #counts = result.get_counts() #plot_histogram(counts) # Import Aer from qiskit import Aer # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') # Create a Quantum Program for execution job = execute(QC, backend) result = job.result() outputstate = result.get_statevector(QC, decimals=3) print(outputstate) #discrete time quantum random walk with a hadamard coin n=6 steps=11 qpos = QuantumRegister(n,'qpos') qcoin = QuantumRegister(1,'qcoin') cpos = ClassicalRegister(n,'cr') QC = QuantumCircuit(qpos, qcoin) #initialized coin |0> #QC.x(qcoin[0]) for i in range(steps): #coin QC.h(qcoin[0]) QC.barrier() #increment gate operator for i in range(n): QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') QC.barrier() #decrement gate operator QC.x(qcoin[0]) for i in range(n): if i+1 < n: QC.x(qpos[i+1:]) QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') if i+1 < n: QC.x(qpos[i+1:]) QC.barrier() a=n/2 p=math.floor(a) #print(p) for k in range(n): if(k<p): QC.swap(qpos[n-1-k],qpos[k]) #print(a) display(QC.draw(output="mpl")) QC.measure_all() # # Execute the circuit on the qasm simulator job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000) counts = job.result().get_counts(QC) print(counts) plot_histogram(counts, figsize=(10, 2), color='midnightblue', title="New Histogram") #aer_sim = Aer.get_backend('aer_simulator') #qobj = assemble(had) #result = aer_sim.run(qobj).result() #counts = result.get_counts() #plot_histogram(counts) #discrete time quantum random walk with a hadamard coin n=6 steps=11 qpos = QuantumRegister(n,'qpos') qcoin = QuantumRegister(1,'qcoin') cpos = ClassicalRegister(n,'cr') QC = QuantumCircuit(qpos, qcoin) #initialized coin |1> QC.x(qcoin[0]) for i in range(steps): #coin QC.h(qcoin[0]) QC.barrier() #increment gate operator for i in range(n): QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') QC.barrier() #decrement gate operator QC.x(qcoin[0]) for i in range(n): if i+1 < n: QC.x(qpos[i+1:]) QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') if i+1 < n: QC.x(qpos[i+1:]) QC.barrier() a=n/2 p=math.floor(a) #print(p) for k in range(n): if(k<p): QC.swap(qpos[n-1-k],qpos[k]) #print(a) display(QC.draw(output="mpl")) QC.measure_all() # # Execute the circuit on the qasm simulator job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000) counts = job.result().get_counts(QC) print(counts) plot_histogram(counts, figsize=(10, 2), color='midnightblue', title="New Histogram") #aer_sim = Aer.get_backend('aer_simulator') #qobj = assemble(had) #result = aer_sim.run(qobj).result() #counts = result.get_counts() #plot_histogram(counts) from qiskit import * %matplotlib inline #discrete time quantum random walk with a hadamard coin n=6 steps=11 qpos = QuantumRegister(n,'qpos') qcoin = QuantumRegister(1,'qcoin') cpos = ClassicalRegister(n,'cr') QC = QuantumCircuit(qpos, qcoin) pi=math.pi #initialized coin Ugate QC.u(pi/2, 3*pi/2, 0, qcoin[0]) for i in range(steps): #coin QC.h(qcoin[0]) QC.barrier() #increment gate operator for i in range(n): QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') QC.barrier() #decrement gate operator QC.x(qcoin[0]) for i in range(n): if i+1 < n: QC.x(qpos[i+1:]) QC.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla') if i+1 < n: QC.x(qpos[i+1:]) QC.barrier() a=n/2 p=math.floor(a) #print(p) for k in range(n): if(k<p): QC.swap(qpos[n-1-k],qpos[k]) #print(a) display(QC.draw(output="mpl")) QC.measure_all() # # Execute the circuit on the qasm simulator job = execute(QC,Aer.get_backend('aer_simulator'),shots=10000) counts = job.result().get_counts(QC) print(counts) plot_histogram(counts, figsize=(10, 2), color='midnightblue', title="New Histogram") #aer_sim = Aer.get_backend('aer_simulator') #qobj = assemble(had) #result = aer_sim.run(qobj).result() #counts = result.get_counts() #plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.visualization.timeline import draw as timeline_draw from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") timeline_draw(circ)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can make the bars more transparent to better see the ones that are behind # if they overlap. import numpy as np from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) state = Statevector(qc) plot_state_city(state, alpha=0.6)
https://github.com/miamico/Quantum_Generative_Adversarial_Networks
miamico
"""Simple example on how to log scalars and images to tensorboard without tensor ops. License: Copyleft """ __author__ = "Michael Gygli" import tensorflow as tf # from StringIO import StringIO import matplotlib.pyplot as plt import numpy as np class Logger(object): """Logging in tensorboard without tensorflow ops.""" def __init__(self, log_dir): """Creates a summary writer logging to log_dir.""" self.writer = tf.summary.FileWriter(log_dir) def log_scalar(self, tag, value, step): """Log a scalar variable. Parameter ---------- tag : basestring Name of the scalar value step : int training iteration """ summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)]) self.writer.add_summary(summary, step) def log_images(self, tag, images, step): """Logs a list of images.""" im_summaries = [] for nr, img in enumerate(images): # Write the image to a string s = StringIO() plt.imsave(s, img, format='png') # Create an Image object img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=img.shape[0], width=img.shape[1]) # Create a Summary value im_summaries.append(tf.Summary.Value(tag='%s/%d' % (tag, nr), image=img_sum)) # Create and write Summary summary = tf.Summary(value=im_summaries) self.writer.add_summary(summary, step) def log_histogram(self, tag, values, step, bins=1000): """Logs the histogram of a list/vector of values.""" # Convert to a numpy array values = np.array(values) # Create histogram using numpy counts, bin_edges = np.histogram(values, bins=bins) # Fill fields of histogram proto hist = tf.HistogramProto() hist.min = float(np.min(values)) hist.max = float(np.max(values)) hist.num = int(np.prod(values.shape)) hist.sum = float(np.sum(values)) hist.sum_squares = float(np.sum(values ** 2)) # Requires equal number as bins, where the first goes from -DBL_MAX to bin_edges[1] # See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/summary.proto#L30 # Thus, we drop the start of the first bin bin_edges = bin_edges[1:] # Add bin edges and counts for edge in bin_edges: hist.bucket_limit.append(edge) for c in counts: hist.bucket.append(c) # Create and write Summary summary = tf.Summary(value=[tf.Summary.Value(tag=tag, histo=hist)]) self.writer.add_summary(summary, step) self.writer.flush()
https://github.com/abbarreto/qiskit4
abbarreto
from sympy import * init_printing(use_unicode=True) mu_u = Matrix([[-1],[+1],[+1]]); mu_u A_R = Matrix([[1,1,-1,-1],[1,-1,1,-1],[1,-1,-1,1]]); A_R p1,p2,p3,p4 = symbols('p_1 p_2 p_3 p_4') p4 = 1-p1-p2-p3 cl = A_R[:,0]*p1 + A_R[:,1]*p2 + A_R[:,2]*p3 + A_R[:,3]*p4 mu_u - cl s1 = Matrix([[0,1],[1,0]]) s2 = Matrix([[0,-1j],[1j,0]]) s1*s2 import numpy as np a = [] # gera uma lista com com todos os 512 estados ônticos for j in range(-1,2,2): for k in range(-1,2,2): for l in range(-1,2,2): for m in range(-1,2,2): for n in range(-1,2,2): for o in range(-1,2,2): for p in range(-1,2,2): for q in range(-1,2,2): for r in range(-1,2,2): a.append(np.array([j,k,l,m,n,o,p,q,r])) a[10], a[10][5], len(a) mu = [] # gera, a partir dos estados ônticos, uma lista com os 512 vetores de medida, muitos dos quais são iguais for j in range(0,2**9): r1 = a[j][0]*a[j][1]*a[j][2] r2 = a[j][3]*a[j][4]*a[j][5] r3 = a[j][6]*a[j][7]*a[j][8] c1 = a[j][0]*a[j][3]*a[j][6] c2 = a[j][1]*a[j][4]*a[j][7] c3 = a[j][2]*a[j][5]*a[j][8] mu.append([r1,r2,r3,c1,c2,c3]) mu[0], len(mu) mu_ = [] # remove as repeticoes do vetor de medida for j in range(0,2**6): if mu[j] not in mu_: mu_.append(mu[j]) mu_, len(mu_), mu_[1] A_R = np.zeros((6,16))#; A_R for j in range(0,16): A_R[:,j] = mu_[j] print(A_R) print(A_R.shape) def rpv_zhsl(d): # vetor de probabilidades aleatório rn = np.zeros(d-1) for j in range(0,d-1): rn[j] = np.random.random() rpv = np.zeros(d) rpv[0] = 1.0 - rn[0]**(1.0/(d-1.0)) norm = rpv[0] if d > 2: for j in range(1,d-1): rpv[j] = (1.0 - rn[j]**(1.0/(d-j-1)))*(1.0-norm) norm = norm + rpv[j] rpv[d-1] = 1.0 - norm return rpv rpv = rpv_zhsl(16) print(rpv) print(np.linalg.norm(rpv)) mu_Q = np.zeros((6,1)); mu_Q = np.array([1,1,1,1,1,-1]); print(mu_Q.shape) p = np.zeros((16,1)); p = rpv_zhsl(16); print(p.shape) vec = mu_Q - A_R@p print(vec) def objective(x): mu_Q = np.array([1,1,1,1,1,-1]) vec = mu_Q - A_R@x return np.linalg.norm(vec) from scipy.optimize import minimize # define o vinculo como sendo uma distribuicao de probabilidades constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x)-1}, {'type':'ineq', 'fun': lambda x: x}, {'type':'ineq', 'fun': lambda x: 1-x}] # 'eq' quer dizer = 0 e 'ineq' quer dizer >=0 np.random.seed(130000) x0 = rpv_zhsl(16) print(x0) result = minimize(objective, x0, constraints=constraints, method='trust-constr') print('melhor distribuicao de probabilidades', result.x) print(objective(result.x)) from qiskit import * import numpy as np import math import qiskit nshots = 8192 IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_manila') 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 from qiskit.visualization import plot_histogram qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.barrier() # mede XI qc.h(0) qc.cx(0,2) qc.barrier() # mede IX qc.h(1) qc.cx(1,2) qc.barrier() # mede XX qc.cx(0,2) qc.cx(1,2) qc.barrier() qc.measure(2,0) qc.draw('mpl') job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts_exp = job_exp.result().get_counts(qc) counts_exp plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp']) qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.barrier() # mede YI qc.sdg(0) qc.h(0) qc.cx(0,2) qc.barrier() # mede IY qc.sdg(1) qc.h(1) qc.cx(1,2) qc.barrier() # mede YY qc.cx(0,2) qc.cx(1,2) qc.barrier() qc.measure(2,0) qc.draw('mpl') job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts_exp = job_exp.result().get_counts(qc) counts_exp plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp']) qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.barrier() qc.h(0) qc.cx(0,2) # mede XI qc.barrier() qc.sdg(1) qc.h(1) qc.cx(1,2) # mede IX qc.barrier() qc.cx(0,2); qc.cx(1,2) qc.barrier() qc.measure(2,0) qc.draw('mpl') job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts_exp = job_exp.result().get_counts(qc) counts_exp plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp']) qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.barrier() qc.sdg(0) qc.h(0) qc.cx(0,2) # mede XI qc.barrier() qc.h(1) qc.cx(1,2) # mede IX qc.barrier() qc.cx(0,2); qc.cx(1,2) qc.barrier() qc.measure(2,0) qc.draw('mpl') job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts_exp = job_exp.result().get_counts(qc) counts_exp plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp']) I = Matrix([[1,0],[0,1]]); X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]) I,X,Y,Z XX = kronecker_product(X,X); XX.eigenvects() YY = kronecker_product(Y,Y); YY.eigenvects() ZZ = kronecker_product(Z,Z); ZZ.eigenvects() qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.barrier() # mede ZZ qc.cx(0,2) qc.cx(1,2) qc.barrier() # mede XX qc.h([0,1]) qc.cx(0,2) qc.cx(1,2) qc.barrier() # mede YY qc.h([0,1]) qc.sdg([0,1]) qc.h([0,1]) qc.cx(0,2) qc.cx(1,2) qc.barrier() qc.measure(2,0) qc.draw('mpl') job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts_exp = job_exp.result().get_counts(qc) counts_exp plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp']) XY = kronecker_product(X,Y); XY.eigenvects() YX = kronecker_product(Y,X); YX.eigenvects() qr = QuantumRegister(3) cr = ClassicalRegister(1) qc = QuantumCircuit(qr,cr) qc.barrier() # mede ZZ qc.cx(0,2) qc.cx(1,2) qc.barrier() # mede XX qc.sdg(1) qc.h([0,1]) qc.cx(0,2) qc.cx(1,2) qc.barrier() # mede YY qc.h([0,1]) qc.sdg(0) qc.s(1) qc.h([0,1]) qc.cx(0,2) qc.cx(1,2) qc.barrier() qc.measure(2,0) qc.draw('mpl') job_sim = execute(qc, backend=simulator, shots=nshots) counts_sim = job_sim.result().get_counts(qc) job_exp = execute(qc, backend=device, shots=nshots) print(job_exp.job_id()) job_monitor(job_exp) counts_exp = job_exp.result().get_counts(qc) counts_exp plot_histogram([counts_sim, counts_exp], legend=['sim', 'exp']) cr1 = {'0': 7921, '1': 271} cr2 = {'0': 7944, '1': 248} cr3 = {'0': 7754, '1': 438} cc1 = {'0': 7913, '1': 279} cc2 = {'0': 7940, '1': 252} cc3 = {'0': 610, '1': 7582} r1a = (cr1['0']-cr1['1'])/(cr1['0']+cr1['1']) r2a = (cr2['0']-cr2['1'])/(cr2['0']+cr2['1']) r3a = (cr3['0']-cr3['1'])/(cr3['0']+cr3['1']) c1a = (cc1['0']-cc1['1'])/(cc1['0']+cc1['1']) c2a = (cc2['0']-cc2['1'])/(cc2['0']+cc2['1']) c3a = (cc3['0']-cc3['1'])/(cc3['0']+cc3['1']) print(r1a,r2a,r3a,c1a,c2a,c3a) def objective(x): mu_Q = np.array([0.93,0.94,0.89,0.93,0.94,-0.85]) vec = mu_Q - A_R@x return np.linalg.norm(vec) constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x)-1}, {'type':'ineq', 'fun': lambda x: x}, {'type':'ineq', 'fun': lambda x: 1-x}] np.random.seed(130000) x0 = rpv_zhsl(16) result = minimize(objective, x0, constraints=constraints, method='trust-constr') print('melhor distribuicao de probabilidades', result.x) print(objective(result.x))
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
import numpy as np from qiskit.visualization import plot_bloch_vector %matplotlib inline I = np.array([ [1., 0.], [0., 1.] ]) X = np.array([ [0., 1.], [1., 0.] ]) Y = np.array([ [0., -1.j], [1.j, 0.] ]) Z = np.array([ [1., 0.], [0., -1.] ]) def Rx(theta): return np.cos(theta/2) * I - 1.j * np.sin(theta/2) * X def Ry(theta): return np.cos(theta/2) * I - 1.j * np.sin(theta/2) * Y def Rz(theta): return np.cos(theta/2) * I - 1.j * np.sin(theta/2) * Z def density_matrix(state): if len(state.shape) == 1: state = state.reshape(-1, 1) return state * np.conjugate(state.T) def state2bloch(state): rho = density_matrix(state) x, y, z = np.trace(X @ rho), np.trace(Y @ rho), np.trace(Z @ rho) return np.real(np.array([x, y, z])) def bloch2state(vec, epsilon = 1e-10): x, y, z = np.real(vec) cos = np.sqrt((1 + z)/2) if z > 1 - epsilon: # theta = 0 return np.array([1., 0.]) elif z < -1 + epsilon: # theta = pi return np.array([0., 1.]) else: sin = np.sqrt(x**2 + y**2) / (2*cos) if x < 0: sin = -sin if abs(x) < epsilon: # phi = pi/2, 3pi/2 if y >= 0: phi = np.pi/2 else: phi = 3 * np.pi/2 else: phi = np.arctan(y/x) return np.array([cos, np.exp(1.j*phi)*sin]) #print(state2bloch(np.array([1., 0.]))) #print(bloch2state(np.array([0., 0., 1.]))) init_vec = np.array([0., 0., 1.]) print(init_vec) display(plot_bloch_vector(init_vec)) final_vec = state2bloch(Rx(np.pi/4) @ bloch2state(init_vec)) print(final_vec) display(plot_bloch_vector(final_vec)) init_state = np.array([1., 0.]) final_state = Rx(np.pi/4) @ Ry(np.pi/4) @ init_state final_vec = state2bloch(final_state) print(final_vec) display(plot_bloch_vector(final_vec)) def rot(theta): return np.array([ [np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)], ]) init_vec = np.array([0., 0., 1.]) vec = init_vec[:] vec[[2,0]] = rot(np.pi/4)@vec[[2,0]] # rotate only 2:z, 0:x around Y-axis vec[[1,2]] = rot(np.pi/4)@vec[[1,2]] # rotate only 1:y, 2:z around X-axis print(vec) display(plot_bloch_vector(vec)) from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(1) # First, rotate around Y-axis qc.ry(np.pi/4, 0) state = Statevector.from_instruction(qc) print('First, rotate around Y-axis...') display(plot_bloch_multivector(state)) # Then, rotate around X-axis qc.rx(np.pi/4, 0) print('Then, rotate around X-axis.') state = Statevector.from_instruction(qc) display(plot_bloch_multivector(state))
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit.quantum_info import Statevector from qiskit import QuantumCircuit import math qc = QuantumCircuit(4) qc.rx(math.pi/2, [0,1,2,3]) qc.p(math.pi/8, 1) qc.s(2) qc.t(3) qc.draw("mpl") state = Statevector.from_instruction(qc) state.draw('bloch')
https://github.com/Alfaxad/IBM_QC_Africa_2021
Alfaxad
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/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Quick program to test the quantum information states modules.""" import unittest import numpy as np from qiskit import QiskitError from qiskit.test import QiskitTestCase from qiskit.quantum_info.states import DensityMatrix, Statevector from qiskit.quantum_info import state_fidelity from qiskit.quantum_info import purity from qiskit.quantum_info import entropy from qiskit.quantum_info import concurrence from qiskit.quantum_info import entanglement_of_formation from qiskit.quantum_info import mutual_information from qiskit.quantum_info.states import shannon_entropy from qiskit.quantum_info import negativity class TestStateMeasures(QiskitTestCase): """Tests state measure functions""" def test_state_fidelity_statevector(self): """Test state_fidelity function for statevector inputs""" psi1 = [0.70710678118654746, 0, 0, 0.70710678118654746] psi2 = [0.0, 0.70710678118654746, 0.70710678118654746, 0.0] self.assertAlmostEqual(state_fidelity(psi1, psi1), 1.0, places=7, msg="vector-vector input") self.assertAlmostEqual(state_fidelity(psi2, psi2), 1.0, places=7, msg="vector-vector input") self.assertAlmostEqual(state_fidelity(psi1, psi2), 0.0, places=7, msg="vector-vector input") psi1 = Statevector([0.70710678118654746, 0, 0, 0.70710678118654746]) psi2 = Statevector([0.0, 0.70710678118654746, 0.70710678118654746, 0.0]) self.assertAlmostEqual(state_fidelity(psi1, psi1), 1.0, places=7, msg="vector-vector input") self.assertAlmostEqual(state_fidelity(psi2, psi2), 1.0, places=7, msg="vector-vector input") self.assertAlmostEqual(state_fidelity(psi1, psi2), 0.0, places=7, msg="vector-vector input") psi1 = Statevector([1, 0, 0, 1]) # invalid state psi2 = Statevector([1, 0, 0, 0]) self.assertRaises(QiskitError, state_fidelity, psi1, psi2) self.assertRaises(QiskitError, state_fidelity, psi1, psi2, validate=True) self.assertEqual(state_fidelity(psi1, psi2, validate=False), 1) def test_state_fidelity_density_matrix(self): """Test state_fidelity function for density matrix inputs""" rho1 = [[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]] mix = [[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.25, 0], [0, 0, 0, 0.25]] self.assertAlmostEqual(state_fidelity(rho1, rho1), 1.0, places=7, msg="matrix-matrix input") self.assertAlmostEqual(state_fidelity(mix, mix), 1.0, places=7, msg="matrix-matrix input") self.assertAlmostEqual(state_fidelity(rho1, mix), 0.25, places=7, msg="matrix-matrix input") rho1 = DensityMatrix(rho1) mix = DensityMatrix(mix) self.assertAlmostEqual(state_fidelity(rho1, rho1), 1.0, places=7, msg="matrix-matrix input") self.assertAlmostEqual(state_fidelity(mix, mix), 1.0, places=7, msg="matrix-matrix input") self.assertAlmostEqual(state_fidelity(rho1, mix), 0.25, places=7, msg="matrix-matrix input") rho1 = DensityMatrix([1, 0, 0, 0]) mix = DensityMatrix(np.diag([1, 0, 0, 1])) self.assertRaises(QiskitError, state_fidelity, rho1, mix) self.assertRaises(QiskitError, state_fidelity, rho1, mix, validate=True) self.assertEqual(state_fidelity(rho1, mix, validate=False), 1) def test_state_fidelity_mixed(self): """Test state_fidelity function for statevector and density matrix inputs""" psi1 = Statevector([0.70710678118654746, 0, 0, 0.70710678118654746]) rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]) mix = DensityMatrix([[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.25, 0], [0, 0, 0, 0.25]]) self.assertAlmostEqual(state_fidelity(psi1, rho1), 1.0, places=7, msg="vector-matrix input") self.assertAlmostEqual(state_fidelity(psi1, mix), 0.25, places=7, msg="vector-matrix input") self.assertAlmostEqual(state_fidelity(rho1, psi1), 1.0, places=7, msg="matrix-vector input") def test_purity_statevector(self): """Test purity function on statevector inputs""" psi = Statevector([1, 0, 0, 0]) self.assertEqual(purity(psi), 1) self.assertEqual(purity(psi, validate=True), 1) self.assertEqual(purity(psi, validate=False), 1) psi = [0.70710678118654746, 0.70710678118654746] self.assertAlmostEqual(purity(psi), 1) self.assertAlmostEqual(purity(psi, validate=True), 1) self.assertAlmostEqual(purity(psi, validate=False), 1) psi = np.array([0.5, 0.5j, -0.5j, -0.5]) self.assertAlmostEqual(purity(psi), 1) self.assertAlmostEqual(purity(psi, validate=True), 1) self.assertAlmostEqual(purity(psi, validate=False), 1) psi = Statevector([1, 0, 0, 1]) self.assertRaises(QiskitError, purity, psi) self.assertRaises(QiskitError, purity, psi, validate=True) self.assertEqual(purity(psi, validate=False), 4) def test_purity_density_matrix(self): """Test purity function on density matrix inputs""" rho = DensityMatrix(np.diag([1, 0, 0, 0])) self.assertEqual(purity(rho), 1) self.assertEqual(purity(rho, validate=True), 1) self.assertEqual(purity(rho, validate=False), 1) rho = np.diag([0.25, 0.25, 0.25, 0.25]) self.assertEqual(purity(rho), 0.25) self.assertEqual(purity(rho, validate=True), 0.25) self.assertEqual(purity(rho, validate=False), 0.25) rho = [[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]] self.assertEqual(purity(rho), 1) self.assertEqual(purity(rho, validate=True), 1) self.assertEqual(purity(rho, validate=False), 1) rho = np.diag([1, 0, 0, 1]) self.assertRaises(QiskitError, purity, rho) self.assertRaises(QiskitError, purity, rho, validate=True) self.assertEqual(purity(rho, validate=False), 2) def test_purity_equivalence(self): """Test purity is same for equivalent inputs""" for alpha, beta in [ (0, 0), (0, 0.25), (0.25, 0), (0.33, 0.33), (0.5, 0.5), (0.75, 0.25), (0, 0.75), ]: psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)]) rho = DensityMatrix(psi) self.assertAlmostEqual(purity(psi), purity(rho)) def test_entropy_statevector(self): """Test entropy function on statevector inputs""" test_psis = [ [1, 0], [0, 1, 0, 0], [0.5, 0.5, 0.5, 0.5], [0.5, 0.5j, -0.5j, 0.5], [0.70710678118654746, 0, 0, -0.70710678118654746j], [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j], ] for psi_ls in test_psis: self.assertEqual(entropy(psi_ls), 0) self.assertEqual(entropy(np.array(psi_ls)), 0) def test_entropy_density_matrix(self): """Test entropy function on density matrix inputs""" # Density matrix input rhos = [DensityMatrix(np.diag([0.5] + (n * [0]) + [0.5])) for n in range(1, 5)] for rho in rhos: self.assertAlmostEqual(entropy(rho), 1) self.assertAlmostEqual(entropy(rho, base=2), 1) self.assertAlmostEqual(entropy(rho, base=np.e), -1 * np.log(0.5)) # Array input for prob in [0.001, 0.3, 0.7, 0.999]: rho = np.diag([prob, 1 - prob]) self.assertAlmostEqual(entropy(rho), shannon_entropy([prob, 1 - prob])) self.assertAlmostEqual( entropy(rho, base=np.e), shannon_entropy([prob, 1 - prob], base=np.e) ) self.assertAlmostEqual(entropy(rho, base=2), shannon_entropy([prob, 1 - prob], base=2)) # List input rho = [[0.5, 0], [0, 0.5]] self.assertAlmostEqual(entropy(rho), 1) def test_entropy_equivalence(self): """Test entropy is same for equivalent inputs""" for alpha, beta in [ (0, 0), (0, 0.25), (0.25, 0), (0.33, 0.33), (0.5, 0.5), (0.75, 0.25), (0, 0.75), ]: psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)]) rho = DensityMatrix(psi) self.assertAlmostEqual(entropy(psi), entropy(rho)) def test_concurrence_statevector(self): """Test concurrence function on statevector inputs""" # Statevector input psi = Statevector([0.70710678118654746, 0, 0, -0.70710678118654746j]) self.assertAlmostEqual(concurrence(psi), 1) # List input psi = [1, 0, 0, 0] self.assertAlmostEqual(concurrence(psi), 0) # Array input psi = np.array([0.5, 0.5, 0.5, 0.5]) self.assertAlmostEqual(concurrence(psi), 0) # Larger than 2 qubit input psi_ls = [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j] psi = Statevector(psi_ls, dims=(2, 8)) self.assertAlmostEqual(concurrence(psi), 1) psi = Statevector(psi_ls, dims=(4, 4)) self.assertAlmostEqual(concurrence(psi), 1) psi = Statevector(psi_ls, dims=(8, 2)) self.assertAlmostEqual(concurrence(psi), 1) def test_concurrence_density_matrix(self): """Test concurrence function on density matrix inputs""" # Density matrix input rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]) rho2 = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]]) self.assertAlmostEqual(concurrence(rho1), 1) self.assertAlmostEqual(concurrence(rho2), 1) self.assertAlmostEqual(concurrence(0.5 * rho1 + 0.5 * rho2), 0) self.assertAlmostEqual(concurrence(0.75 * rho1 + 0.25 * rho2), 0.5) # List input rho = [[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] self.assertEqual(concurrence(rho), 0) # Array input rho = np.diag([0.25, 0.25, 0.25, 0.25]) self.assertEqual(concurrence(rho), 0) def test_concurrence_equivalence(self): """Test concurrence is same for equivalent inputs""" for alpha, beta in [ (0, 0), (0, 0.25), (0.25, 0), (0.33, 0.33), (0.5, 0.5), (0.75, 0.25), (0, 0.75), ]: psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)]) rho = DensityMatrix(psi) self.assertAlmostEqual(concurrence(psi), concurrence(rho)) def test_entanglement_of_formation_statevector(self): """Test entanglement of formation function on statevector inputs""" # Statevector input psi = Statevector([0.70710678118654746, 0, 0, -0.70710678118654746j]) self.assertAlmostEqual(entanglement_of_formation(psi), 1) # List input psi = [1, 0, 0, 0] self.assertAlmostEqual(entanglement_of_formation(psi), 0) # Array input psi = np.array([0.5, 0.5, 0.5, 0.5]) self.assertAlmostEqual(entanglement_of_formation(psi), 0) # Larger than 2 qubit input psi_ls = [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j] psi = Statevector(psi_ls, dims=(2, 8)) self.assertAlmostEqual(entanglement_of_formation(psi), 1) psi = Statevector(psi_ls, dims=(4, 4)) self.assertAlmostEqual(entanglement_of_formation(psi), 1) psi = Statevector(psi_ls, dims=(8, 2)) self.assertAlmostEqual(entanglement_of_formation(psi), 1) def test_entanglement_of_formation_density_matrix(self): """Test entanglement of formation function on density matrix inputs""" # Density matrix input rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]) rho2 = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]]) self.assertAlmostEqual(entanglement_of_formation(rho1), 1) self.assertAlmostEqual(entanglement_of_formation(rho2), 1) self.assertAlmostEqual(entanglement_of_formation(0.5 * rho1 + 0.5 * rho2), 0) self.assertAlmostEqual( entanglement_of_formation(0.75 * rho1 + 0.25 * rho2), 0.35457890266527003 ) # List input rho = [[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] self.assertEqual(entanglement_of_formation(rho), 0) # Array input rho = np.diag([0.25, 0.25, 0.25, 0.25]) self.assertEqual(entanglement_of_formation(rho), 0) def test_entanglement_of_formation_equivalence(self): """Test entanglement of formation is same for equivalent inputs""" for alpha, beta in [ (0, 0), (0, 0.25), (0.25, 0), (0.33, 0.33), (0.5, 0.5), (0.75, 0.25), (0, 0.75), ]: psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)]) rho = DensityMatrix(psi) self.assertAlmostEqual(entanglement_of_formation(psi), entanglement_of_formation(rho)) def test_mutual_information_statevector(self): """Test mutual_information function on statevector inputs""" # Statevector input psi = Statevector([0.70710678118654746, 0, 0, -0.70710678118654746j]) self.assertAlmostEqual(mutual_information(psi), 2) # List input psi = [1, 0, 0, 0] self.assertAlmostEqual(mutual_information(psi), 0) # Array input psi = np.array([0.5, 0.5, 0.5, 0.5]) self.assertAlmostEqual(mutual_information(psi), 0) # Larger than 2 qubit input psi_ls = [0.70710678118654746] + (14 * [0]) + [0.70710678118654746j] psi = Statevector(psi_ls, dims=(2, 8)) self.assertAlmostEqual(mutual_information(psi), 2) psi = Statevector(psi_ls, dims=(4, 4)) self.assertAlmostEqual(mutual_information(psi), 2) psi = Statevector(psi_ls, dims=(8, 2)) self.assertAlmostEqual(mutual_information(psi), 2) def test_mutual_information_density_matrix(self): """Test mutual_information function on density matrix inputs""" # Density matrix input rho1 = DensityMatrix([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]]) rho2 = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5j, 0], [0, 0.5j, 0.5, 0], [0, 0, 0, 0]]) self.assertAlmostEqual(mutual_information(rho1), 2) self.assertAlmostEqual(mutual_information(rho2), 2) # List input rho = [[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] self.assertEqual(mutual_information(rho), 0) # Array input rho = np.diag([0.25, 0.25, 0.25, 0.25]) self.assertEqual(mutual_information(rho), 0) def test_mutual_information_equivalence(self): """Test mutual_information is same for equivalent inputs""" for alpha, beta in [ (0, 0), (0, 0.25), (0.25, 0), (0.33, 0.33), (0.5, 0.5), (0.75, 0.25), (0, 0.75), ]: psi = Statevector([alpha, beta, 0, 1j * np.sqrt(1 - alpha**2 - beta**2)]) rho = DensityMatrix(psi) self.assertAlmostEqual(mutual_information(psi), mutual_information(rho)) def test_negativity_statevector(self): """Test negativity function on statevector inputs""" # Constructing separable quantum statevector state = Statevector([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0]) negv = negativity(state, [0]) self.assertAlmostEqual(negv, 0, places=7) # Constructing entangled quantum statevector state = Statevector([0, 1 / np.sqrt(2), -1 / np.sqrt(2), 0]) negv = negativity(state, [1]) self.assertAlmostEqual(negv, 0.5, places=7) def test_negativity_density_matrix(self): """Test negativity function on density matrix inputs""" # Constructing separable quantum state rho = DensityMatrix.from_label("10+") negv = negativity(rho, [0, 1]) self.assertAlmostEqual(negv, 0, places=7) negv = negativity(rho, [0, 2]) self.assertAlmostEqual(negv, 0, places=7) # Constructing entangled quantum state rho = DensityMatrix([[0, 0, 0, 0], [0, 0.5, -0.5, 0], [0, -0.5, 0.5, 0], [0, 0, 0, 0]]) negv = negativity(rho, [0]) self.assertAlmostEqual(negv, 0.5, places=7) negv = negativity(rho, [1]) self.assertAlmostEqual(negv, 0.5, places=7) if __name__ == "__main__": unittest.main()
https://github.com/shufan-mct/IBM_quantum_challenge_2020
shufan-mct
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) provider = IBMQ.load_account() #initialization 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 problem_set = \ [[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '3']], [['0', '0'], ['1', '1'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '1'], ['1', '3'], ['3', '2'], ['3', '3']], [['0', '2'], ['1', '0'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '1'], ['3', '3']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '3'], ['1', '2'], ['2', '2'], ['2', '3'], ['3', '0']], [['0', '3'], ['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '3'], ['2', '1'], ['2', '3'], ['3', '0']], [['0', '1'], ['0', '3'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '2']], [['0', '0'], ['1', '3'], ['2', '0'], ['2', '1'], ['2', '3'], ['3', '1']], [['0', '1'], ['0', '2'], ['1', '0'], ['1', '2'], ['2', '2'], ['2', '3']], [['0', '3'], ['1', '0'], ['1', '3'], ['2', '1'], ['2', '2'], ['3', '0']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '3'], ['3', '0'], ['3', '1']], [['0', '1'], ['1', '0'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '1']]] bi_16=\ [ [0,0,0,0],[0,0,0,1],[0,0,1,0],[0,0,1,1], [0,1,0,0],[0,1,0,1],[0,1,1,0],[0,1,1,1], [1,0,0,0],[1,0,0,1],[1,0,1,0],[1,0,1,1], [1,1,0,0],[1,1,0,1],[1,1,1,0],[1,1,1,1] ] ad= QuantumRegister(4, name='ad') ad_sw = QuantumRegister(1, name='ad_sw') row = QuantumRegister(4, name='row') column = QuantumRegister(4, name='column') flag = QuantumRegister(2, name='flag') flag2=QuantumRegister(1, name='flag2') ancilla = QuantumRegister(7, name='a') cbits = ClassicalRegister(4,name='c') #qc = QuantumCircuit(ad,ad_sw,row,column,flag,cbits) problem_set = \ [[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '3']], [['0', '0'], ['1', '1'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '1'], ['1', '3'], ['3', '2'], ['3', '3']], [['0', '2'], ['1', '0'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '1'], ['3', '3']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '3'], ['1', '2'], ['2', '2'], ['2', '3'], ['3', '0']], [['0', '3'], ['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '3'], ['2', '1'], ['2', '3'], ['3', '0']], [['0', '1'], ['0', '3'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '2']], [['0', '0'], ['1', '3'], ['2', '0'], ['2', '1'], ['2', '3'], ['3', '1']], [['0', '1'], ['0', '2'], ['1', '0'], ['1', '2'], ['2', '2'], ['2', '3']], [['0', '3'], ['1', '0'], ['1', '3'], ['2', '1'], ['2', '2'], ['3', '0']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '3'], ['3', '0'], ['3', '1']], [['0', '1'], ['1', '0'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '1']]] def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "$U_diff$" return U_s qc = QuantumCircuit(ad,ad_sw,row,column,flag,flag2,ancilla,cbits) qc.h(ad) qc.x(flag2) qc.h(flag2) a=0 for problem in problem_set: #x gate for b in range(4): if bi_16[a][b]==0: qc.x(ad[3-b]) #ad--mct-->ad_sw qc.mct(ad,ad_sw[0],ancilla,mode='basic') #address set up------------------------------------------ for i in range(5): for j in range(i+1,6): for k in range(0,6): if(k!=i and k!=j): m=int(problem[k][0]) n=int(problem[k][1]) qc.cx(ad_sw,row[m]) qc.cx(ad_sw,column[n]) qc.mct([row[0],row[1],row[2],row[3],column[0],column[1],column[2],column[3],flag[0]],flag[1],ancilla,mode='basic') qc.mct([row[0],row[1],row[2],row[3],column[0],column[1],column[2],column[3]],flag[1],ancilla,mode='basic') for k in range(0,6): if(k!=i and k!=j): m=int(problem[k][0]) n=int(problem[k][1]) qc.cx(ad_sw,row[m]) qc.cx(ad_sw,column[n]) qc.x(flag[0]) qc.ccx(flag[0],flag[1],flag2[0]) qc.x(flag[0]) for i in range(5): for j in range(i+1,6): for k in range(0,6): if(k!=i and k!=j): m=int(problem[k][0]) n=int(problem[k][1]) qc.cx(ad_sw,row[m]) qc.cx(ad_sw,column[n]) qc.mct([row[0],row[1],row[2],row[3],column[0],column[1],column[2],column[3],flag[0]],flag[1],ancilla,mode='basic') qc.mct([row[0],row[1],row[2],row[3],column[0],column[1],column[2],column[3]],flag[1],ancilla,mode='basic') for k in range(0,6): if(k!=i and k!=j): m=int(problem[k][0]) n=int(problem[k][1]) qc.cx(ad_sw,row[m]) qc.cx(ad_sw,column[n]) #address set up----------------------------------------- qc.mct(ad,ad_sw[0],ancilla,mode='basic') #x gate for b in range(4): if bi_16[a][b]==0: qc.x(ad[3-b]) a=a+1 qc.append(diffuser(4),[0,1,2,3]) qc.measure(ad,cbits) qasm_simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=qasm_simulator, shots=1024).result() plot_histogram(result.get_counts()) #qc.draw() qc.measure(flag,cbits) qasm_simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=qasm_simulator, shots=1024).result() plot_histogram(result.get_counts()) def counter(qc,r_or_c,auxiliary): for i in range(len(r_or_c)): qc.mct([r_or_c[i],auxiliary[0],auxiliary[1]],auxiliary[2],mode='noancilla') qc.ccx(r_or_c[i],auxiliary[0],auxiliary[1]) qc.cx(r_or_c[i],auxiliary[0]) def counterd(qc,r_or_c,auxiliary): for i in range(len(r_or_c)): qc.cx(r_or_c[3-i],auxiliary[0]) qc.ccx(r_or_c[3-i],auxiliary[0],auxiliary[1]) qc.mct([r_or_c[3-i],auxiliary[0],auxiliary[1]],auxiliary[2],mode='noancilla') def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "$U_diff$" return U_s qc.h(ad) qc.x(flag) qc.h(flag) i=0 for problem in problem_set: #x gate for j in range(4): if bi_16[i][j]==0: qc.x(ad[3-j]) #ad--mct-->ad_sw qc.mct(ad,ad_sw[0],mode='noancilla') #address set up------------------------------------------ for area in problem: j=int(area[0]) k=int(area[1]) qc.cx(ad_sw[0],row[j]) qc.cx(ad_sw[0],column[k]) qc.barrier() counter(qc,row,ct_r) counter(qc,column,ct_c) #------flip 1 qc.x(ct_r[0]) qc.x(ct_r[2]) qc.x(ct_c[0]) qc.x(ct_c[2]) qc.mct([ct_r[:],ct_c[:]]) qc.x(ct_r[0]) qc.x(ct_r[2]) qc.x(ct_c[0]) qc.x(ct_c[2]) #-------flip 2 #-------flip 3 counter(qc,column,ct_c) counter(qc,row,ct_r) qc.barrier() for area in problem: j=int(area[0]) k=int(area[1]) qc.cx(ad_sw[0],row[j]) qc.cx(ad_sw[0],column[k]) #address set up------------------------------------------ qc.mct(ad,ad_sw[0],mode='noancilla') #x gate for j in range(4): if bi_16[i][j]==0: qc.x(ad[3-j]) i=i+1 qc.append(diffuser(4),[0,1,2,3]) qc.measure(ad,cbits) qasm_simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=qasm_simulator, shots=1024).result() plot_histogram(result.get_counts()) qc.draw() ad= QuantumRegister(4, name='ad') ad_sw = QuantumRegister(1, name='ad_sw') row = QuantumRegister(4, name='row') column = QuantumRegister(4, name='column') ct = QuantumRegister(3, name='ct') flag = QuantumRegister(1, name='flag') cbits = ClassicalRegister(3,name='c') problem_set = \ [[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '3']], [['0', '0'], ['1', '1'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '1'], ['1', '3'], ['3', '2'], ['3', '3']], [['0', '2'], ['1', '0'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '1'], ['3', '3']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '3'], ['1', '2'], ['2', '2'], ['2', '3'], ['3', '0']], [['0', '3'], ['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '3'], ['2', '1'], ['2', '3'], ['3', '0']], [['0', '1'], ['0', '3'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '2']], [['0', '0'], ['1', '3'], ['2', '0'], ['2', '1'], ['2', '3'], ['3', '1']], [['0', '1'], ['0', '2'], ['1', '0'], ['1', '2'], ['2', '2'], ['2', '3']], [['0', '3'], ['1', '0'], ['1', '3'], ['2', '1'], ['2', '2'], ['3', '0']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '3'], ['3', '0'], ['3', '1']], [['0', '1'], ['1', '0'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '1']]] problem=[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']] qc = QuantumCircuit(ad,ad_sw,row,column,ct,flag, cbits) qc.x(ad_sw) for area in problem: j=int(area[0]) k=int(area[1]) qc.cx(ad_sw[0],row[j]) qc.cx(ad_sw[0],column[k]) qc.barrier() counter(qc,row,column,ct) qc.measure(ct,cbits) """ qc.x(ct[0]) qc.ccx(ct[0],ct[2],flag) qc.x(ct[0]) counterd(qc,row,column,ct) qc.barrier() for area in problem: j=int(area[0]) k=int(area[1]) qc.cx(ad_sw[0],row[j]) qc.cx(ad_sw[0],column[k]) qc.measure(flag,cbits) """ qasm_simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=qasm_simulator, shots=1024).result() plot_histogram(result.get_counts()) qc.draw()
https://github.com/derek-wang-ibm/coding-with-qiskit
derek-wang-ibm
import qiskit qiskit.__version__ from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_quantum", # ibm_cloud token = 'YOURTOKENHERE') QiskitRuntimeService.save_account(channel='ibm_quantum', token = 'YOURTOKENHERE') backend = service.backend(name = "ibm_brisbane") backend.num_qubits
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. """ResourceEstimation pass testing""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import ResourceEstimation from qiskit.test import QiskitTestCase class TestResourceEstimationPass(QiskitTestCase): """Tests for PropertySet methods.""" def test_empty_dag(self): """Empty DAG.""" circuit = QuantumCircuit() passmanager = PassManager() passmanager.append(ResourceEstimation()) passmanager.run(circuit) self.assertEqual(passmanager.property_set["size"], 0) self.assertEqual(passmanager.property_set["depth"], 0) self.assertEqual(passmanager.property_set["width"], 0) self.assertDictEqual(passmanager.property_set["count_ops"], {}) def test_just_qubits(self): """A dag with 8 operations and no classic bits""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) passmanager = PassManager() passmanager.append(ResourceEstimation()) passmanager.run(circuit) self.assertEqual(passmanager.property_set["size"], 8) self.assertEqual(passmanager.property_set["depth"], 7) self.assertEqual(passmanager.property_set["width"], 2) self.assertDictEqual(passmanager.property_set["count_ops"], {"cx": 6, "h": 2}) if __name__ == "__main__": unittest.main()
https://github.com/GabrielPontolillo/QiskitPBT
GabrielPontolillo
import random from qiskit import QuantumCircuit from QiskitPBT.case_studies.deutsch_jozsa.deutsch_jozsa import deutsch_jozsa_circ from QiskitPBT.case_studies.deutsch_jozsa.dj_helpers import BalancedOracleInputGenerator from QiskitPBT.property import Property class DeutschJozsaWorksForBalancedFunction(Property): # specify the inputs that are to be generated def get_input_generators(self): return [BalancedOracleInputGenerator(5, 10)] # specify the preconditions for the test def preconditions(self, oracle): return True # specify the operations to be performed on the input def operations(self, oracle: QuantumCircuit): circ = deutsch_jozsa_circ(oracle) # if oracle is constant this should be all 0 baseline = QuantumCircuit(oracle.num_qubits - 1, oracle.num_qubits - 1) self.statistical_analysis.assert_different(self, list(range(oracle.num_qubits - 1)), circ, list(range(oracle.num_qubits - 1)), baseline, basis=["z"])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import * # Create a Quantum Circuit acting on a quantum register of three qubits circ = QuantumCircuit(3) # Add a H gate on qubit $q_{0}$, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{1}$, putting # the qubits in a Bell state. circ.cx(0, 1) # Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{2}$, putting # the qubits in a GHZ state. circ.cx(0, 2) circ.draw('mpl') # Import Aer from qiskit import Aer # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') # Create a Quantum Program for execution job = backend.run(circ) result = job.result() outputstate = result.get_statevector(circ, decimals=3) print(outputstate) from qiskit.visualization import plot_state_city plot_state_city(outputstate) # Run the quantum circuit on a unitary simulator backend backend = Aer.get_backend('unitary_simulator') job = backend.run(circ) result = job.result() # Show the results print(result.get_unitary(circ, decimals=3)) # Create a Quantum Circuit meas = QuantumCircuit(3, 3) meas.barrier(range(3)) # map the quantum measurement to the classical bits meas.measure(range(3), range(3)) # The Qiskit circuit object supports composition using # the compose method. circ.add_register(meas.cregs[0]) qc = circ.compose(meas) #drawing the circuit qc.draw() # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim = backend_sim.run(transpile(qc, backend_sim), shots=1024) # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(qc) print(counts) from qiskit.visualization import plot_histogram plot_histogram(counts) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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/ericardomuten/qiskit-advocate-mentorship
ericardomuten
# Mount Google Drive from google.colab import drive # import drive from google colab ROOT = "/content/drive" # default location for the drive print(ROOT) # print content of ROOT (Optional) drive.mount(ROOT) # we mount the google drive at /content/drive !pip install qiskit from IPython.display import clear_output clear_output() import os def restart_runtime(): os.kill(os.getpid(), 9) restart_runtime() # %matplotlib inline import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import tensorflow as tf from tensorflow.keras.utils import to_categorical (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train_flatten = x_train.reshape(x_train.shape[0], x_train.shape[1]*x_train.shape[2])/255.0 x_test_flatten = x_test.reshape(x_test.shape[0], x_test.shape[1]*x_test.shape[2])/255.0 # Sanity check print(x_train_flatten.shape, y_train.shape) print(x_test_flatten.shape, y_test.shape) x_train_0 = x_train_flatten[y_train == 0] x_train_1 = x_train_flatten[y_train == 1] x_train_2 = x_train_flatten[y_train == 2] x_train_3 = x_train_flatten[y_train == 3] x_train_4 = x_train_flatten[y_train == 4] x_train_5 = x_train_flatten[y_train == 5] x_train_6 = x_train_flatten[y_train == 6] x_train_7 = x_train_flatten[y_train == 7] x_train_8 = x_train_flatten[y_train == 8] x_train_9 = x_train_flatten[y_train == 9] x_train_list = [x_train_0, x_train_1, x_train_2, x_train_3, x_train_4, x_train_5, x_train_6, x_train_7, x_train_8, x_train_9] print(x_train_0.shape) print(x_train_1.shape) print(x_train_2.shape) print(x_train_3.shape) print(x_train_4.shape) print(x_train_5.shape) print(x_train_6.shape) print(x_train_7.shape) print(x_train_8.shape) print(x_train_9.shape) x_test_0 = x_test_flatten[y_test == 0] x_test_1 = x_test_flatten[y_test == 1] x_test_2 = x_test_flatten[y_test == 2] x_test_3 = x_test_flatten[y_test == 3] x_test_4 = x_test_flatten[y_test == 4] x_test_5 = x_test_flatten[y_test == 5] x_test_6 = x_test_flatten[y_test == 6] x_test_7 = x_test_flatten[y_test == 7] x_test_8 = x_test_flatten[y_test == 8] x_test_9 = x_test_flatten[y_test == 9] x_test_list = [x_test_0, x_test_1, x_test_2, x_test_3, x_test_4, x_test_5, x_test_6, x_test_7, x_test_8, x_test_9] print(x_test_0.shape) print(x_test_1.shape) print(x_test_2.shape) print(x_test_3.shape) print(x_test_4.shape) print(x_test_5.shape) print(x_test_6.shape) print(x_test_7.shape) print(x_test_8.shape) print(x_test_9.shape) def binary_classification_data_generator(num_sample, mult_test, n_class, class_list): X_train = x_train_list[class_list[0]][:num_sample, :] X_test = x_test_list[class_list[0]][:int(mult_test*num_sample), :] Y_train = np.zeros((n_class*X_train.shape[0],), dtype=int) Y_test = np.zeros((n_class*X_test.shape[0],), dtype=int) for i in range(n_class-1): X_train = np.concatenate((X_train, x_train_list[class_list[i+1]][:num_sample, :]), axis=0) Y_train[num_sample*(i+1):num_sample*(i+2)] = int(i+1) X_test = np.concatenate((X_test, x_test_list[class_list[i+1]][:int(mult_test*num_sample), :]), axis=0) Y_test[int(mult_test*num_sample*(i+1)):int(mult_test*num_sample*(i+2))] = int(i+1) Y_train = to_categorical(Y_train) Y_test = to_categorical(Y_test) return X_train, Y_train, X_test, Y_test num_sample = 200 n_class = 2 mult_test = 2.5 X_train01, Y_train01, X_test01, Y_test01 = binary_classification_data_generator(num_sample, mult_test, n_class, [0,1]) # Sanity check print(X_train01.shape, Y_train01.shape) print(X_test01.shape, Y_test01.shape) plt.imshow plt.imshow(np.concatenate((X_train01[0].reshape(28,28), X_train01[-1].reshape(28,28)), axis=1), cmap='gray') X_train36, Y_train36, X_test36, Y_test36 = binary_classification_data_generator(num_sample, mult_test, n_class, [3,6]) # Sanity check print(X_train36.shape, Y_train36.shape) print(X_test36.shape, Y_test36.shape) plt.imshow plt.imshow(np.concatenate((X_train36[0].reshape(28,28), X_train36[-1].reshape(28,28)), axis=1), cmap='gray') def normalize(X, use_params=False, params=None): """Normalize the given dataset X Args: X: ndarray, dataset Returns: (Xbar, mean, std): tuple of ndarray, Xbar is the normalized dataset with mean 0 and standard deviation 1; mean and std are the mean and standard deviation respectively. Note: You will encounter dimensions where the standard deviation is zero, for those when you do normalization the normalized data will be NaN. Handle this by setting using `std = 1` for those dimensions when doing normalization. """ if use_params: mu = params[0] std_filled = [1] else: mu = np.mean(X, axis=0) std = np.std(X, axis=0) #std_filled = std.copy() #std_filled[std==0] = 1. Xbar = (X - mu)/(std + 1e-8) return Xbar, mu, std X_train01, mu_train01, std_train01 = normalize(X_train01) X_test01 = (X_test01 - mu_train01)/(std_train01 + 1e-8) # Sanity check print(X_train01.shape, Y_train01.shape) print(X_test01.shape, Y_test01.shape) X_train36, mu_train36, std_train36 = normalize(X_train36) X_test36 = (X_test36 - mu_train36)/(std_train36 + 1e-8) # Sanity check print(X_train36.shape, Y_train36.shape) print(X_test36.shape, Y_test36.shape) from sklearn.decomposition import PCA from matplotlib import pyplot as plt num_component = 6 pca01 = PCA(n_components=num_component, svd_solver='full') pca36 = PCA(n_components=num_component, svd_solver='full') pca01.fit(X_train01) pca36.fit(X_train36) print(np.cumsum(pca01.explained_variance_ratio_)) print(np.cumsum(pca36.explained_variance_ratio_)) X_train01 = pca01.transform(X_train01) X_test01 = pca01.transform(X_test01) # Sanity check print(X_train01.shape, Y_train01.shape) print(X_test01.shape, Y_test01.shape) X_train36 = pca36.transform(X_train36) X_test36 = pca36.transform(X_test36) # Sanity check print(X_train36.shape, Y_train36.shape) print(X_test36.shape, Y_test36.shape) X_train01 = (X_train01.T / np.sqrt(np.sum(X_train01 ** 2, -1))).T X_test01 = (X_test01.T / np.sqrt(np.sum(X_test01 ** 2, -1))).T plt.scatter(X_train01[:100, 0], X_train01[:100, 1]) plt.scatter(X_train01[100:200, 0], X_train01[100:200, 1]) plt.scatter(X_train01[200:300, 0], X_train01[200:300, 1]) X_train36 = (X_train36.T / np.sqrt(np.sum(X_train36 ** 2, -1))).T X_test36 = (X_test36.T / np.sqrt(np.sum(X_test36 ** 2, -1))).T plt.scatter(X_train36[:100, 0], X_train36[:100, 1]) plt.scatter(X_train36[100:200, 0], X_train36[100:200, 1]) plt.scatter(X_train36[200:300, 0], X_train36[200:300, 1]) from qiskit import * import numpy as np # Set a random seed np.random.seed(42) def drc_circuit(x_sample, parameters, num_features, layer=1): q_reg = QuantumRegister(1) c_reg = ClassicalRegister(1) circuit = QuantumCircuit(q_reg, c_reg) # Layer iteration for i in range(layer): # Gate iteration for j in range(int(num_features/3)): circuit.u(*(parameters[3*j:3*(j+1)] * x_sample[3*j:3*(j+1)] + parameters[3*j+num_features:3*(j+1)+num_features]), 0) circuit.measure(0,0) return circuit num_features = 6 num_layer = 1 params = np.random.uniform(size=(2*num_features*num_layer + 2)) drc_circuit(X_train01[0], params, num_features).draw() def weighted_fidelity_cost_function(params, X_train, Y_train, backend, L=1, num_features=6, shots=2000): loss = 0 # Training sample iteration for k in range(len(X_train)): circuit = drc_circuit(X_train[k], params, num_features, layer=L) t_circ = transpile(circuit, backend) qobj = assemble(t_circ, shots=shots) job = backend.run(qobj) result = job.result().get_counts(circuit) counts = np.array(list(result.values())) # Pauli-Z eigenvalue states = np.array([0, -1]) # Compute probabilities for each state probabilities = counts / shots # Get state expectation z_expectation = np.sum(states * probabilities) # Get weighted fidelity fidel_0 = params[-2]*(1 + z_expectation)/2 fidel_1 = params[-1]*(1 - z_expectation)/2 # Calculate the loss from the sample loss += ((fidel_0 - Y_train[k,0])**2 + (fidel_1 - Y_train[k,1])**2)/2 loss = loss/len(X_train) return loss def drc_pred(params, X, backend, L=1, num_features=6, shots=2000): pred = [] # Sample iteration for k in range(len(X)): circuit = drc_circuit(X[k], params, num_features, layer=L) t_circ = transpile(circuit, backend) qobj = assemble(t_circ, shots=shots) job = backend.run(qobj) result = job.result().get_counts(circuit) counts = np.array(list(result.values())) # Pauli-Z eigenvalue states = np.array([0, -1]) # Compute probabilities for each state probabilities = counts / shots # Get state expectation z_expectation = np.sum(states * probabilities) # Get weighted fidelity fidel_0 = params[-2]*(1 + z_expectation)/2 fidel_1 = params[-1]*(1 - z_expectation)/2 pred += [[fidel_0, fidel_1]] return np.array(pred) shots=2000 backend = Aer.get_backend('qasm_simulator') num_layer = 1 num_features = 6 params = np.random.uniform(size=(2*num_features*num_layer + 2)) from qiskit.aqua.components.optimizers import COBYLA import scipy opt_params_01 = scipy.optimize.minimize(fun=weighted_fidelity_cost_function, x0=params, method='COBYLA', args=(X_train01, Y_train01, backend, num_layer, num_features, shots), options={'maxiter':1000}) print(opt_params_01) Y_pred_train = drc_pred(opt_params_01['x'], X_train01, backend, L=num_layer, num_features=num_features, shots=shots) Y_pred_test = drc_pred(opt_params_01['x'], X_test01, backend, L=num_layer, num_features=num_features, shots=shots) train_acc = (np.argmax(Y_pred_train, axis=1) == np.argmax(Y_train01, axis=1)).sum()/len(Y_train01) test_acc = (np.argmax(Y_pred_test, axis=1) == np.argmax(Y_test01, axis=1)).sum()/len(Y_test01) print("Train Accuracy:", train_acc) print("Test Accuracy:", test_acc) train_acc_list01 = [] test_acc_list01 = [] train_loss_list01 = [] test_loss_list01 = [] for i in range(5): opt_params_01 = scipy.optimize.minimize(fun=weighted_fidelity_cost_function, x0=params, method='COBYLA', args=(X_train01, Y_train01, backend, i+1, num_features, shots), options={'maxiter':1000}) print("Number of layer: " + str(i+1) + ", status: finished.") Y_pred_train = drc_pred(opt_params_01['x'], X_train01, backend, L=num_layer, num_features=num_features, shots=shots) Y_pred_test = drc_pred(opt_params_01['x'], X_test01, backend, L=num_layer, num_features=num_features, shots=shots) train_acc = (np.argmax(Y_pred_train, axis=1) == np.argmax(Y_train01, axis=1)).sum()/len(Y_train01) test_acc = (np.argmax(Y_pred_test, axis=1) == np.argmax(Y_test01, axis=1)).sum()/len(Y_test01) train_acc_list01 += [train_acc] test_acc_list01 += [test_acc] train_loss = weighted_fidelity_cost_function(opt_params_01['x'], X_train01, Y_train01, backend, L=num_layer, num_features=num_features, shots=shots) test_loss = weighted_fidelity_cost_function(opt_params_01['x'], X_test01, Y_test01, backend, L=num_layer, num_features=num_features, shots=shots) train_loss_list01 += [train_loss] test_loss_list01 += [test_loss] plt.plot(train_acc_list01, label='Train Acc') plt.plot(test_acc_list01, label='Test Acc') plt.xlabel('Number of Layer') plt.ylabel('Classification Accuracy') plt.legend() plt.show() plt.plot(train_loss_list01, label='Train Loss') plt.plot(test_loss_list01, label='Test Loss') plt.xlabel('Number of Layer') plt.ylabel('Loss') plt.legend() plt.show() import pandas as pd d = {'Training Acc': [0.9875, 0.9175], 'Testing Acc': [0.992, 0.915]} pd.DataFrame(data=d, index=["Qiskit (COBYLA, QASM Simulator)", "PennyLane (Adam, PennyLane's Statevector Simulator)"]) opt_params_36 = scipy.optimize.minimize(fun=weighted_fidelity_cost_function, x0=params, method='COBYLA', args=(X_train36, Y_train36, backend, num_layer, num_features, shots), options={'maxiter':1000}) print(opt_params_36) Y_pred_train = drc_pred(opt_params_36['x'], X_train36, backend, L=num_layer, num_features=num_features, shots=shots) Y_pred_test = drc_pred(opt_params_36['x'], X_test36, backend, L=num_layer, num_features=num_features, shots=shots) train_acc = (np.argmax(Y_pred_train, axis=1) == np.argmax(Y_train36, axis=1)).sum()/len(Y_train36) test_acc = (np.argmax(Y_pred_test, axis=1) == np.argmax(Y_test36, axis=1)).sum()/len(Y_test36) print("Train Accuracy:", train_acc) print("Test Accuracy:", test_acc)
https://github.com/Rishwi/Beyond-Classical-a-quantum-computing-crash-course-using-qiskit
Rishwi
#pip install qiskit from qiskit import * from qiskit.tools.visualization import plot_histogram stt="Hello world" res = ''.join(format(ord(i), 'b') for i in stt) print(res) s = res n = len(s) circuit = QuantumCircuit(n+1,n) circuit.x(n) circuit.barrier() circuit.h(range(n+1)) circuit.barrier() for i, tf in enumerate(reversed(s)): if tf == '1': circuit.cx(i, n) circuit.barrier() circuit.h(range(n+1)) circuit.barrier() circuit.measure(range(n), range(n)) %matplotlib inline circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1).result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) kk=result.get_counts() kkk=list(kk.keys()) strrr=kkk[0] print(strrr) res=strrr #i'm changing res variable, so, now i don't know what's in res i=0 mainstr=[] while i<len(res): if res[i:i+6] != '100000': sk=res[i:i+7] i=i+7 ssk=int(sk, base=2) print(ssk) mainstr.append(chr(ssk)) elif res[i:i+6] == '100000': i=i+6 mainstr.append(" ") print(''.join(mainstr))
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from qiskit import transpile, Aer from qiskit.providers.ibmq import IBMQFactory from qiskit.utils import QuantumInstance from qiskit.test.mock import FakeProvider ## The component that manages the execution of quantum algorithms for QuantumSolver class QExecute: ## Constructor def __init__(self, token: str = ''): ## The IBMQ Experience token self.token = token ## The fake backends provider self.provider_fake = FakeProvider() ## The available backends self.backends = [ Aer.get_backend('aer_simulator') ] fake_backends = [ 'fake_armonk', 'fake_tenerife', 'fake_casablanca', 'fake_melbourne', 'fake_guadalupe', 'fake_tokyo', 'fake_paris', 'fake_cambridge', 'fake_rochester', 'fake_brooklyn' ] for fake_backend in fake_backends: self.backends.append(self.provider_fake.get_backend(fake_backend)) if self.token: ## The IBMQ provider self.provider = IBMQFactory().enable_account(self.token) self.backends += self.provider.backends() ## The current backend self.current_backend = None ## Current backend setter def set_current_backend(self, backend_name: str): if backend_name == 'aer_simulator': self.current_backend = self.backends[0] elif backend_name[0:5] == 'fake_': self.current_backend = self.provider_fake.get_backend(backend_name) elif self.provider: self.current_backend = self.provider.get_backend(backend_name) ## Check if the guest mode is activated def is_guest_mode(self): return self.token == '' ## Print the available backends def print_avaiable_backends(self): print('\nAvaliable backends:') for i in range(len(self.backends)): backend = self.backends[i] status = backend.status() config = backend.configuration() jobs_in_queue = status.pending_jobs q_instance = QuantumInstance(backend) is_simulator = q_instance.is_simulator or str(backend)[0:5] == 'fake_' is_operational = status.operational print('[' + str(i + 1) + ']\tName:', str(backend), \ '\n\tNumber of qubits:', str(config.n_qubits) + \ '\n\tMaximum shots:', str(config.max_shots) + \ '\n\tJobs in queue:', str(jobs_in_queue)) print('\tIs ' + ('' if is_simulator else 'NOT ') + 'a simulator') if is_operational: print('\t✅ Is operational') else: print('\t❌ Is NOT operational') print() ## Backend selection menu def select_backend(self): range_backends = '[1 - ' + str(len(self.backends)) + ']' index = -2 while index < 0 or index >= len(self.backends): msg = '[&] Select a backend of the list ' + str(range_backends) + ': ' index = int(input(msg)) - 1 if index == -1: self.current_backend = None print('[$] Backend not selected') return if index < 0 or index >= len(self.backends) or \ not self.backends[index].status().operational: index = -1 print('[!] The backend must be one of the list', range_backends, \ 'and must be operational') else: self.current_backend = self.backends[index] print('[$]', str(self.current_backend), 'selected') ## Run the circuit using the current backend def run(self, circuit: 'QuantumCircuit', n_shots: int): # Compile the circuit down to low-level QASM instructions # supported by the backend compiled_circuit = transpile(circuit, self.current_backend) # Execute the circuit on the current backend job = self.current_backend.run(compiled_circuit, shots=n_shots) # Return the counts from the job results return job.result().get_counts(compiled_circuit)
https://github.com/carstenblank/dc-qiskit-qml
carstenblank
# -*- coding: utf-8 -*- # Copyright 2018, Carsten Blank. # # 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. import logging import unittest import numpy import qiskit from qiskit.providers import BackendV2 from scipy import sparse from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler, Normalizer from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier from dc_qiskit_qml.distance_based.hadamard.state import QmlBinaryDataStateCircuitBuilder from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder from dc_qiskit_qml.distance_based.hadamard.state.cnot import CCXToffoli from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import MottonenStatePreparation from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import FFQRAMStateVectorRoutine from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import QiskitNativeStatePreparation from dc_qiskit_qml.encoding_maps import EncodingMap, NormedAmplitudeEncoding logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO') log = logging.getLogger(__name__) def get_data(only_two_features=True): from sklearn.preprocessing import StandardScaler, Normalizer from sklearn.datasets import load_iris X, y = load_iris(return_X_y=True) X = [x[0:2] if only_two_features else x for x, y in zip(X, y) if y != 2] y = [y for x, y in zip(X, y) if y != 2] scaler, normalizer = StandardScaler(), Normalizer(norm='l2', copy=True) X = scaler.fit_transform(X, y) X = normalizer.fit_transform(X, y) return X, y def predict(qml, only_two_features=True): # type: (QmlHadamardNeighborClassifier, bool) -> tuple X, y = get_data(only_two_features) X_train = [X[33], X[85]] y_train = [y[33], y[85]] X_test = [X[28], X[36]] y_test = [y[28], y[36]] log.info("Training with %d samples.", len(X_train)) qml.fit(X_train, y_train) log.info("Predict on %d unseen samples.", len(X_test)) for i in X_test: log.info("Predict: %s.", i) labels = qml.predict(X_test) log.info("Predict: %s (%s%% / %s). Expected: %s" % (labels, qml.last_predict_probability, qml.last_predict_p_acc, y_test)) return labels, y_test # noinspection NonAsciiCharacters class QmlHadamardMöttönenTests(unittest.TestCase): def runTest(self): log.info("Testing 'QmlHadamardNeighborClassifier' with Möttönen Preparation.") execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2 classifier_state_factory = QmlGenericStateCircuitBuilder(MottonenStatePreparation()) qml = QmlHadamardNeighborClassifier(encoding_map=NormedAmplitudeEncoding(), classifier_circuit_factory=classifier_state_factory, backend=execution_backend, shots=100 * 8192) y_predict, y_test = predict(qml) predictions_match = [p == l for p, l in zip(y_predict, y_test)] self.assertTrue(all(predictions_match)) self.assertEqual(len(qml.last_predict_probability), 2) input_1_probability = qml.last_predict_probability[0] input_2_probability = qml.last_predict_probability[1] self.assertAlmostEqual(input_1_probability, 0.629, delta=0.02) self.assertAlmostEqual(input_2_probability, 0.547, delta=0.02) class QmlHadamardFFQramTests(unittest.TestCase): def runTest(self): log.info("Testing 'QmlHadamardNeighborClassifier' with FF Qram Preparation.") execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2 classifier_state_factory = QmlGenericStateCircuitBuilder(FFQRAMStateVectorRoutine()) qml = QmlHadamardNeighborClassifier(backend=execution_backend, classifier_circuit_factory=classifier_state_factory, encoding_map=NormedAmplitudeEncoding(), shots=100 * 8192) y_predict, y_test = predict(qml) predictions_match = [p == l for p, l in zip(y_predict, y_test)] self.assertTrue(all(predictions_match), "The predictions must be correct.") self.assertEqual(len(qml.last_predict_probability), 2) input_1_probability = qml.last_predict_probability[0] input_2_probability = qml.last_predict_probability[1] self.assertAlmostEqual(input_1_probability, 0.629, delta=0.02) self.assertAlmostEqual(input_2_probability, 0.547, delta=0.02) class QmlHadamardQiskitInitializerTests(unittest.TestCase): def runTest(self): log.info("Testing 'QmlHadamardNeighborClassifier' with FF Qram Preparation.") execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2 classifier_state_factory = QmlGenericStateCircuitBuilder(QiskitNativeStatePreparation()) qml = QmlHadamardNeighborClassifier(backend=execution_backend, classifier_circuit_factory=classifier_state_factory, encoding_map=NormedAmplitudeEncoding(), shots=100 * 8192) y_predict, y_test = predict(qml) predictions_match = [p == l for p, l in zip(y_predict, y_test)] self.assertTrue(all(predictions_match), "The predictions must be correct.") self.assertEqual(len(qml.last_predict_probability), 2) input_1_probability = qml.last_predict_probability[0] input_2_probability = qml.last_predict_probability[1] self.assertAlmostEqual(input_1_probability, 0.629, delta=0.02) self.assertAlmostEqual(input_2_probability, 0.547, delta=0.02) # noinspection NonAsciiCharacters class QmlHadamardMultiClassesTests(unittest.TestCase): def runTest(self): log.info("Testing 'QmlHadamardNeighborClassifier' with Möttönen Preparation.") execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2 classifier_state_factory = QmlGenericStateCircuitBuilder(MottonenStatePreparation()) qml = QmlHadamardNeighborClassifier(encoding_map=NormedAmplitudeEncoding(), classifier_circuit_factory=classifier_state_factory, backend=execution_backend, shots=100 * 8192) from sklearn.datasets import load_wine from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler, Normalizer from sklearn.pipeline import Pipeline X, y = load_wine(return_X_y=True) preprocessing_pipeline = Pipeline([ ('scaler', StandardScaler()), ('pca2', PCA(n_components=2)), ('l2norm', Normalizer(norm='l2', copy=True)) ]) X = preprocessing_pipeline.fit_transform(X, y) X_train = X[[33, 88, 144]] y_train = y[[33, 88, 144]] X_test = X[[28, 140]] y_test = y[[28, 140]] qml.fit(X_train, y_train) prediction = qml.predict(X_test) self.assertEqual(len(prediction), len(y_test)) self.assertListEqual(prediction, list(y_test)) # noinspection NonAsciiCharacters class QmlHadamardCNOTQubitEncodingTests(unittest.TestCase): def runTest(self): log.info("Testing 'QmlHadamardNeighborClassifier' with CNOT Preparation.") execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2 X_train = numpy.asarray([[1.0, 1.0], [-1.0, 1.0], [-1.0, -1.0], [1.0, -1.0]]) y_train = [0, 1, 0, 1] X_test = numpy.asarray([[0.2, 0.4], [0.4, -0.8]]) y_test = [0, 1] class MyEncodingMap(EncodingMap): def map(self, input_vector: list) -> sparse.dok_matrix: result = sparse.dok_matrix((4, 1)) index = 0 if input_vector[0] > 0 and input_vector[1] > 0: index = 0 if input_vector[0] < 0 < input_vector[1]: index = 1 if input_vector[0] < 0 and input_vector[1] < 0: index = 2 if input_vector[0] > 0 > input_vector[1]: index = 3 result[index, 0] = 1.0 return result encoding_map = MyEncodingMap() initial_state_builder = QmlBinaryDataStateCircuitBuilder(CCXToffoli()) qml = QmlHadamardNeighborClassifier(backend=execution_backend, shots=100 * 8192, encoding_map=encoding_map, classifier_circuit_factory=initial_state_builder) qml.fit(X_train, y_train) prediction = qml.predict(X_test) self.assertEqual(len(prediction), len(y_test)) self.assertListEqual(prediction, y_test) class FullIris(unittest.TestCase): def runTest(self): from sklearn.datasets import load_iris X, y = load_iris(return_X_y=True) X = numpy.asarray([x[0:2] for x, yy in zip(X, y) if yy != 2]) y = numpy.asarray([yy for x, yy in zip(X, y) if yy != 2]) preprocessing_pipeline = Pipeline([ ('scaler', StandardScaler()), ('l2norm', Normalizer(norm='l2', copy=True)) ]) X = preprocessing_pipeline.fit_transform(X, y) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42) initial_state_builder = QmlGenericStateCircuitBuilder(MottonenStatePreparation()) execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2 qml = QmlHadamardNeighborClassifier(backend=execution_backend, shots=8192, classifier_circuit_factory=initial_state_builder, encoding_map=NormedAmplitudeEncoding()) qml.fit(X_train, y_train) prediction = qml.predict(X_test) self.assertEqual(len(prediction), len(y_test)) self.assertListEqual(prediction, list(y_test)) for i in range(len(qml.last_predict_p_acc)): self.assertAlmostEqual(qml.last_predict_p_acc[i], QmlHadamardNeighborClassifier.p_acc_theory(X_train, y_train, X_test[i]), delta=0.05) for i in range(len(qml.last_predict_probability)): predicted_label = prediction[i] self.assertAlmostEqual(qml.last_predict_probability[i], QmlHadamardNeighborClassifier.p_label_theory(X_train, y_train, X_test[i], predicted_label), delta=0.05)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/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/Z-928/Bugs4Q
Z-928
#https://github.com/Qiskit/qiskit-terra/issues/2009 import numpy as np from qiskit import * from qiskit.tools.qi.qi import random_unitary_matrix from qiskit.mapper import two_qubit_kak q = QuantumRegister(2, 'q') qc = QuantumCircuit(q) num_gates = np.random.randint(30) # h = 0, x = 1, y = 2, z = 3, cx = 4 for _ in range(num_gates): item = np.random.randint(5) if item in [0, 1, 2, 3]: idx = np.random.randint(size) if item == 0: qc.h(q[idx]) elif item == 1: qc.x(q[idx]) elif item == 2: qc.y(q[idx]) elif item == 3: qc.z(q[idx]) else: idx = np.random.permutation(size) qc.cx(q[int(idx[0])], q[int(idx[1])]) uni = Aer.get_backend('unitary_simulator') res = execute(qc, uni).result() U = res.get_unitary() two_qubit_kak(U)
https://github.com/carstenblank/dc-qiskit-algorithms
carstenblank
# 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. import logging import unittest import qiskit from ddt import ddt, unpack, data from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute import qiskit.extensions from qiskit.result import Result import dc_qiskit_algorithms logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO') log = logging.getLogger('test_DraperAdder') @ddt class MultipleControlledNotGateTest(unittest.TestCase): @unpack @data( {'vector': [-0.1, 0.2, -0.3, 0.4, -0.5, 0.6, -0.7, 0.8]} ) def test_1(self, vector): q = QuantumRegister(4) c = ClassicalRegister(4) qc = QuantumCircuit(q, c) qc.x(q[1]) qc.x(q[2]) qc.x(q[3]) qc.ccx_uni_rot(7, [q[1], q[2], q[3]], q[0]) qc.measure(q, c) backend = qiskit.BasicAer.get_backend('qasm_simulator') job_sim = execute(qc, backend, shots=10000) sim_result = job_sim.result() # type: Result counts = sim_result.get_counts(qc) # type: dict log.info(counts) self.assertIsNotNone(counts.keys()) self.assertListEqual(list(counts.keys()), ['1111']) def test_2(self): q = QuantumRegister(4) c = ClassicalRegister(4) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[2]) # State now ['0000', '0001', '0100', '0101'] qc.ccx_uni_rot(5, [q[0], q[1], q[2]], q[3]) # State now ['0000', '0001', '0100', '1101'] qc.measure(q, c) backend = qiskit.BasicAer.get_backend('qasm_simulator') job_sim = execute(qc, backend, shots=10000) sim_result = job_sim.result() # type: Result counts = sim_result.get_counts(qc) # type: dict log.info(counts) self.assertIsNotNone(counts.keys()) self.assertListEqual(list(sorted(counts.keys())), ['0000', '0001', '0100', '1101']) if __name__ == '__main__': unittest.main(verbosity=2)
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/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. """ Clifford operator class. """ from __future__ import annotations import functools import itertools import re from typing import Literal import numpy as np from qiskit.circuit import Instruction, QuantumCircuit from qiskit.circuit.library.standard_gates import HGate, IGate, SGate, XGate, YGate, ZGate from qiskit.circuit.operation import Operation from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.quantum_info.operators.mixins import AdjointMixin, generate_apidocs from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.scalar_op import ScalarOp from qiskit.quantum_info.operators.symplectic.base_pauli import _count_y from qiskit.utils.deprecation import deprecate_func from qiskit.synthesis.linear import calc_inverse_matrix from .base_pauli import BasePauli from .clifford_circuits import _append_circuit, _append_operation from .stabilizer_table import StabilizerTable class Clifford(BaseOperator, AdjointMixin, Operation): """An N-qubit unitary operator from the Clifford group. **Representation** An *N*-qubit Clifford operator is stored as a length *2N × (2N+1)* boolean tableau using the convention from reference [1]. * Rows 0 to *N-1* are the *destabilizer* group generators * Rows *N* to *2N-1* are the *stabilizer* group generators. The internal boolean tableau for the Clifford can be accessed using the :attr:`tableau` attribute. The destabilizer or stabilizer rows can each be accessed as a length-N Stabilizer table using :attr:`destab` and :attr:`stab` attributes. A more easily human readable representation of the Clifford operator can be obtained by calling the :meth:`to_dict` method. This representation is also used if a Clifford object is printed as in the following example .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford # Bell state generation circuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) cliff = Clifford(qc) # Print the Clifford print(cliff) # Print the Clifford destabilizer rows print(cliff.to_labels(mode="D")) # Print the Clifford stabilizer rows print(cliff.to_labels(mode="S")) .. parsed-literal:: Clifford: Stabilizer = ['+XX', '+ZZ'], Destabilizer = ['+IZ', '+XI'] ['+IZ', '+XI'] ['+XX', '+ZZ'] **Circuit Conversion** Clifford operators can be initialized from circuits containing *only* the following Clifford gates: :class:`~qiskit.circuit.library.IGate`, :class:`~qiskit.circuit.library.XGate`, :class:`~qiskit.circuit.library.YGate`, :class:`~qiskit.circuit.library.ZGate`, :class:`~qiskit.circuit.library.HGate`, :class:`~qiskit.circuit.library.SGate`, :class:`~qiskit.circuit.library.SdgGate`, :class:`~qiskit.circuit.library.SXGate`, :class:`~qiskit.circuit.library.SXdgGate`, :class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.CZGate`, :class:`~qiskit.circuit.library.CYGate`, :class:`~qiskit.circuit.library.DXGate`, :class:`~qiskit.circuit.library.SwapGate`, :class:`~qiskit.circuit.library.iSwapGate`, :class:`~qiskit.circuit.library.ECRGate`, :class:`~qiskit.circuit.library.LinearFunction`, :class:`~qiskit.circuit.library.PermutationGate`. They can be converted back into a :class:`~qiskit.circuit.QuantumCircuit`, or :class:`~qiskit.circuit.Gate` object using the :meth:`~Clifford.to_circuit` or :meth:`~Clifford.to_instruction` methods respectively. Note that this decomposition is not necessarily optimal in terms of number of gates. .. note:: A minimally generating set of gates for Clifford circuits is the :class:`~qiskit.circuit.library.HGate` and :class:`~qiskit.circuit.library.SGate` gate and *either* the :class:`~qiskit.circuit.library.CXGate` or :class:`~qiskit.circuit.library.CZGate` two-qubit gate. Clifford operators can also be converted to :class:`~qiskit.quantum_info.Operator` objects using the :meth:`to_operator` method. This is done via decomposing to a circuit, and then simulating the circuit as a unitary operator. References: 1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). `arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_ """ _COMPOSE_PHASE_LOOKUP = None _COMPOSE_1Q_LOOKUP = None def __array__(self, dtype=None): if dtype: return np.asarray(self.to_matrix(), dtype=dtype) return self.to_matrix() def __init__(self, data, validate=True, copy=True): """Initialize an operator object.""" # pylint: disable=cyclic-import from qiskit.circuit.library import LinearFunction, PermutationGate # Initialize from another Clifford if isinstance(data, Clifford): num_qubits = data.num_qubits self.tableau = data.tableau.copy() if copy else data.tableau # Initialize from ScalarOp as N-qubit identity discarding any global phase elif isinstance(data, ScalarOp): if not data.num_qubits or not data.is_unitary(): raise QiskitError("Can only initialize from N-qubit identity ScalarOp.") num_qubits = data.num_qubits self.tableau = np.fromfunction( lambda i, j: i == j, (2 * num_qubits, 2 * num_qubits + 1) ).astype(bool) # Initialize from LinearFunction elif isinstance(data, LinearFunction): num_qubits = len(data.linear) self.tableau = self.from_linear_function(data) # Initialize from PermutationGate elif isinstance(data, PermutationGate): num_qubits = len(data.pattern) self.tableau = self.from_permutation(data) # Initialize from a QuantumCircuit or Instruction object elif isinstance(data, (QuantumCircuit, Instruction)): num_qubits = data.num_qubits self.tableau = Clifford.from_circuit(data).tableau # DEPRECATED: data is StabilizerTable elif isinstance(data, StabilizerTable): self.tableau = self._stack_table_phase(data.array, data.phase) num_qubits = data.num_qubits # Initialize StabilizerTable directly from the data else: if isinstance(data, (list, np.ndarray)) and np.asarray(data, dtype=bool).ndim == 2: data = np.array(data, dtype=bool, copy=copy) if data.shape[0] == data.shape[1]: self.tableau = self._stack_table_phase( data, np.zeros(data.shape[0], dtype=bool) ) num_qubits = data.shape[0] // 2 elif data.shape[0] + 1 == data.shape[1]: self.tableau = data num_qubits = data.shape[0] // 2 else: raise QiskitError("") else: n_paulis = len(data) symp = self._from_label(data[0]) num_qubits = len(symp) // 2 tableau = np.zeros((n_paulis, len(symp)), dtype=bool) tableau[0] = symp for i in range(1, n_paulis): tableau[i] = self._from_label(data[i]) self.tableau = tableau # Validate table is a symplectic matrix if validate and not Clifford._is_symplectic(self.symplectic_matrix): raise QiskitError( "Invalid Clifford. Input StabilizerTable is not a valid symplectic matrix." ) # Initialize BaseOperator super().__init__(num_qubits=num_qubits) @property def name(self): """Unique string identifier for operation type.""" return "clifford" @property def num_clbits(self): """Number of classical bits.""" return 0 def __repr__(self): return f"Clifford({repr(self.tableau)})" def __str__(self): return ( f'Clifford: Stabilizer = {self.to_labels(mode="S")}, ' f'Destabilizer = {self.to_labels(mode="D")}' ) def __eq__(self, other): """Check if two Clifford tables are equal""" return super().__eq__(other) and (self.tableau == other.tableau).all() def copy(self): return type(self)(self, validate=False, copy=True) # --------------------------------------------------------------------- # Attributes # --------------------------------------------------------------------- # pylint: disable=bad-docstring-quotes @deprecate_func( since="0.24.0", additional_msg="Instead, index or iterate through the Clifford.tableau attribute.", ) def __getitem__(self, key): """Return a stabilizer Pauli row""" return self.table.__getitem__(key) @deprecate_func(since="0.24.0", additional_msg="Use Clifford.tableau property instead.") def __setitem__(self, key, value): """Set a stabilizer Pauli row""" self.tableau.__setitem__(key, self._stack_table_phase(value.array, value.phase)) @property @deprecate_func( since="0.24.0", additional_msg="Use Clifford.stab and Clifford.destab properties instead.", is_property=True, ) def table(self): """Return StabilizerTable""" return StabilizerTable(self.symplectic_matrix, phase=self.phase) @table.setter @deprecate_func( since="0.24.0", additional_msg="Use Clifford.stab and Clifford.destab properties instead.", is_property=True, ) def table(self, value): """Set the stabilizer table""" # Note this setter cannot change the size of the Clifford # It can only replace the contents of the StabilizerTable with # another StabilizerTable of the same size. if not isinstance(value, StabilizerTable): value = StabilizerTable(value) self.symplectic_matrix = value._table._array self.phase = value._table._phase @property @deprecate_func( since="0.24.0", additional_msg="Use Clifford.stab properties instead.", is_property=True, ) def stabilizer(self): """Return the stabilizer block of the StabilizerTable.""" array = self.tableau[self.num_qubits : 2 * self.num_qubits, :-1] phase = self.tableau[self.num_qubits : 2 * self.num_qubits, -1].reshape(self.num_qubits) return StabilizerTable(array, phase) @stabilizer.setter @deprecate_func( since="0.24.0", additional_msg="Use Clifford.stab properties instead.", is_property=True, ) def stabilizer(self, value): """Set the value of stabilizer block of the StabilizerTable""" if not isinstance(value, StabilizerTable): value = StabilizerTable(value) self.tableau[self.num_qubits : 2 * self.num_qubits, :-1] = value.array @property @deprecate_func( since="0.24.0", additional_msg="Use Clifford.destab properties instead.", is_property=True, ) def destabilizer(self): """Return the destabilizer block of the StabilizerTable.""" array = self.tableau[0 : self.num_qubits, :-1] phase = self.tableau[0 : self.num_qubits, -1].reshape(self.num_qubits) return StabilizerTable(array, phase) @destabilizer.setter @deprecate_func( since="0.24.0", additional_msg="Use Clifford.destab properties instead.", is_property=True, ) def destabilizer(self, value): """Set the value of destabilizer block of the StabilizerTable""" if not isinstance(value, StabilizerTable): value = StabilizerTable(value) self.tableau[: self.num_qubits, :-1] = value.array @property def symplectic_matrix(self): """Return boolean symplectic matrix.""" return self.tableau[:, :-1] @symplectic_matrix.setter def symplectic_matrix(self, value): self.tableau[:, :-1] = value @property def phase(self): """Return phase with boolean representation.""" return self.tableau[:, -1] @phase.setter def phase(self, value): self.tableau[:, -1] = value @property def x(self): """The x array for the symplectic representation.""" return self.tableau[:, 0 : self.num_qubits] @x.setter def x(self, value): self.tableau[:, 0 : self.num_qubits] = value @property def z(self): """The z array for the symplectic representation.""" return self.tableau[:, self.num_qubits : 2 * self.num_qubits] @z.setter def z(self, value): self.tableau[:, self.num_qubits : 2 * self.num_qubits] = value @property def destab(self): """The destabilizer array for the symplectic representation.""" return self.tableau[: self.num_qubits, :] @destab.setter def destab(self, value): self.tableau[: self.num_qubits, :] = value @property def destab_x(self): """The destabilizer x array for the symplectic representation.""" return self.tableau[: self.num_qubits, : self.num_qubits] @destab_x.setter def destab_x(self, value): self.tableau[: self.num_qubits, : self.num_qubits] = value @property def destab_z(self): """The destabilizer z array for the symplectic representation.""" return self.tableau[: self.num_qubits, self.num_qubits : 2 * self.num_qubits] @destab_z.setter def destab_z(self, value): self.tableau[: self.num_qubits, self.num_qubits : 2 * self.num_qubits] = value @property def destab_phase(self): """Return phase of destabilizer with boolean representation.""" return self.tableau[: self.num_qubits, -1] @destab_phase.setter def destab_phase(self, value): self.tableau[: self.num_qubits, -1] = value @property def stab(self): """The stabilizer array for the symplectic representation.""" return self.tableau[self.num_qubits :, :] @stab.setter def stab(self, value): self.tableau[self.num_qubits :, :] = value @property def stab_x(self): """The stabilizer x array for the symplectic representation.""" return self.tableau[self.num_qubits :, : self.num_qubits] @stab_x.setter def stab_x(self, value): self.tableau[self.num_qubits :, : self.num_qubits] = value @property def stab_z(self): """The stabilizer array for the symplectic representation.""" return self.tableau[self.num_qubits :, self.num_qubits : 2 * self.num_qubits] @stab_z.setter def stab_z(self, value): self.tableau[self.num_qubits :, self.num_qubits : 2 * self.num_qubits] = value @property def stab_phase(self): """Return phase of stabilizer with boolean representation.""" return self.tableau[self.num_qubits :, -1] @stab_phase.setter def stab_phase(self, value): self.tableau[self.num_qubits :, -1] = value # --------------------------------------------------------------------- # Utility Operator methods # --------------------------------------------------------------------- def is_unitary(self): """Return True if the Clifford table is valid.""" # A valid Clifford is always unitary, so this function is really # checking that the underlying Stabilizer table array is a valid # Clifford array. return Clifford._is_symplectic(self.symplectic_matrix) # --------------------------------------------------------------------- # BaseOperator Abstract Methods # --------------------------------------------------------------------- def conjugate(self): return Clifford._conjugate_transpose(self, "C") def adjoint(self): return Clifford._conjugate_transpose(self, "A") def transpose(self): return Clifford._conjugate_transpose(self, "T") def tensor(self, other: Clifford) -> Clifford: if not isinstance(other, Clifford): other = Clifford(other) return self._tensor(self, other) def expand(self, other: Clifford) -> Clifford: if not isinstance(other, Clifford): other = Clifford(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): n = a.num_qubits + b.num_qubits tableau = np.zeros((2 * n, 2 * n + 1), dtype=bool) clifford = cls(tableau, validate=False) clifford.destab_x[: b.num_qubits, : b.num_qubits] = b.destab_x clifford.destab_x[b.num_qubits :, b.num_qubits :] = a.destab_x clifford.destab_z[: b.num_qubits, : b.num_qubits] = b.destab_z clifford.destab_z[b.num_qubits :, b.num_qubits :] = a.destab_z clifford.stab_x[: b.num_qubits, : b.num_qubits] = b.stab_x clifford.stab_x[b.num_qubits :, b.num_qubits :] = a.stab_x clifford.stab_z[: b.num_qubits, : b.num_qubits] = b.stab_z clifford.stab_z[b.num_qubits :, b.num_qubits :] = a.stab_z clifford.phase[: b.num_qubits] = b.destab_phase clifford.phase[b.num_qubits : n] = a.destab_phase clifford.phase[n : n + b.num_qubits] = b.stab_phase clifford.phase[n + b.num_qubits :] = a.stab_phase return clifford def compose( self, other: Clifford | QuantumCircuit | Instruction, qargs: list | None = None, front: bool = False, ) -> Clifford: if qargs is None: qargs = getattr(other, "qargs", None) # If other is a QuantumCircuit we can more efficiently compose # using the _append_circuit method to update each gate recursively # to the current Clifford, rather than converting to a Clifford first # and then doing the composition of tables. if not front: if isinstance(other, QuantumCircuit): return _append_circuit(self.copy(), other, qargs=qargs) if isinstance(other, Instruction): return _append_operation(self.copy(), other, qargs=qargs) if not isinstance(other, Clifford): # Not copying is safe since we're going to drop our only reference to `other` at the end # of the function. other = Clifford(other, copy=False) # Validate compose dimensions self._op_shape.compose(other._op_shape, qargs, front) # Pad other with identities if composing on subsystem other = self._pad_with_identity(other, qargs) left, right = (self, other) if front else (other, self) if self.num_qubits == 1: return self._compose_1q(left, right) return self._compose_general(left, right) @classmethod def _compose_general(cls, first, second): # Correcting for phase due to Pauli multiplication. Start with factors of -i from XZ = -iY # on individual qubits, and then handle multiplication between each qubitwise pair. ifacts = np.sum(second.x & second.z, axis=1, dtype=int) x1, z1 = first.x.astype(np.uint8), first.z.astype(np.uint8) lookup = cls._compose_lookup() # The loop is over 2*n_qubits entries, and the entire loop is cubic in the number of qubits. for k, row2 in enumerate(second.symplectic_matrix): x1_select = x1[row2] z1_select = z1[row2] x1_accum = np.logical_xor.accumulate(x1_select, axis=0).astype(np.uint8) z1_accum = np.logical_xor.accumulate(z1_select, axis=0).astype(np.uint8) indexer = (x1_select[1:], z1_select[1:], x1_accum[:-1], z1_accum[:-1]) ifacts[k] += np.sum(lookup[indexer]) p = np.mod(ifacts, 4) // 2 phase = ( (np.matmul(second.symplectic_matrix, first.phase, dtype=int) + second.phase + p) % 2 ).astype(bool) data = cls._stack_table_phase( (np.matmul(second.symplectic_matrix, first.symplectic_matrix, dtype=int) % 2).astype( bool ), phase, ) return Clifford(data, validate=False, copy=False) @classmethod def _compose_1q(cls, first, second): # 1-qubit composition can be done with a simple lookup table; there are 24 elements in the # 1q Clifford group, so 576 possible combinations, which is small enough to look up. if cls._COMPOSE_1Q_LOOKUP is None: # The valid tables for 1q Cliffords. tables_1q = np.array( [ [[False, True], [True, False]], [[False, True], [True, True]], [[True, False], [False, True]], [[True, False], [True, True]], [[True, True], [False, True]], [[True, True], [True, False]], ] ) phases_1q = np.array([[False, False], [False, True], [True, False], [True, True]]) # Build the lookup table. cliffords = [ cls(cls._stack_table_phase(table, phase), validate=False, copy=False) for table, phase in itertools.product(tables_1q, phases_1q) ] cls._COMPOSE_1Q_LOOKUP = { (cls._hash(left), cls._hash(right)): cls._compose_general(left, right) for left, right in itertools.product(cliffords, repeat=2) } return cls._COMPOSE_1Q_LOOKUP[cls._hash(first), cls._hash(second)].copy() @classmethod def _compose_lookup( cls, ): if cls._COMPOSE_PHASE_LOOKUP is None: # A lookup table for calculating phases. The indices are # current_x, current_z, running_x_count, running_z_count # where all counts taken modulo 2. lookup = np.zeros((2, 2, 2, 2), dtype=int) lookup[0, 1, 1, 0] = lookup[1, 0, 1, 1] = lookup[1, 1, 0, 1] = -1 lookup[0, 1, 1, 1] = lookup[1, 0, 0, 1] = lookup[1, 1, 1, 0] = 1 lookup.setflags(write=False) cls._COMPOSE_PHASE_LOOKUP = lookup return cls._COMPOSE_PHASE_LOOKUP # --------------------------------------------------------------------- # Representation conversions # --------------------------------------------------------------------- def to_dict(self): """Return dictionary representation of Clifford object.""" return { "stabilizer": self.to_labels(mode="S"), "destabilizer": self.to_labels(mode="D"), } @classmethod def from_dict(cls, obj): """Load a Clifford from a dictionary""" labels = obj.get("destabilizer") + obj.get("stabilizer") n_paulis = len(labels) symp = cls._from_label(labels[0]) tableau = np.zeros((n_paulis, len(symp)), dtype=bool) tableau[0] = symp for i in range(1, n_paulis): tableau[i] = cls._from_label(labels[i]) return cls(tableau) def to_matrix(self): """Convert operator to Numpy matrix.""" return self.to_operator().data @classmethod def from_matrix(cls, matrix: np.ndarray) -> Clifford: """Create a Clifford from a unitary matrix. Note that this function takes exponentially long time w.r.t. the number of qubits. Args: matrix (np.array): A unitary matrix representing a Clifford to be converted. Returns: Clifford: the Clifford object for the unitary matrix. Raises: QiskitError: if the input is not a Clifford matrix. """ tableau = cls._unitary_matrix_to_tableau(matrix) if tableau is None: raise QiskitError("Non-Clifford matrix is not convertible") return cls(tableau) @classmethod def from_linear_function(cls, linear_function): """Create a Clifford from a Linear Function. If the linear function is represented by a nxn binary invertible matrix A, then the corresponding Clifford has symplectic matrix [[A^t, 0], [0, A^{-1}]]. Args: linear_function (LinearFunction): A linear function to be converted. Returns: Clifford: the Clifford object for this linear function. """ mat = linear_function.linear mat_t = np.transpose(mat) mat_i = calc_inverse_matrix(mat) dim = len(mat) zero = np.zeros((dim, dim), dtype=int) symplectic_mat = np.block([[mat_t, zero], [zero, mat_i]]) phase = np.zeros(2 * dim, dtype=int) tableau = cls._stack_table_phase(symplectic_mat, phase) return tableau @classmethod def from_permutation(cls, permutation_gate): """Create a Clifford from a PermutationGate. Args: permutation_gate (PermutationGate): A permutation to be converted. Returns: Clifford: the Clifford object for this permutation. """ pat = permutation_gate.pattern dim = len(pat) symplectic_mat = np.zeros((2 * dim, 2 * dim), dtype=int) for i, j in enumerate(pat): symplectic_mat[j, i] = True symplectic_mat[j + dim, i + dim] = True phase = np.zeros(2 * dim, dtype=bool) tableau = cls._stack_table_phase(symplectic_mat, phase) return tableau def to_operator(self) -> Operator: """Convert to an Operator object.""" return Operator(self.to_instruction()) @classmethod def from_operator(cls, operator: Operator) -> Clifford: """Create a Clifford from a operator. Note that this function takes exponentially long time w.r.t. the number of qubits. Args: operator (Operator): An operator representing a Clifford to be converted. Returns: Clifford: the Clifford object for the operator. Raises: QiskitError: if the input is not a Clifford operator. """ tableau = cls._unitary_matrix_to_tableau(operator.to_matrix()) if tableau is None: raise QiskitError("Non-Clifford operator is not convertible") return cls(tableau) def to_circuit(self): """Return a QuantumCircuit implementing the Clifford. For N <= 3 qubits this is based on optimal CX cost decomposition from reference [1]. For N > 3 qubits this is done using the general non-optimal compilation routine from reference [2]. Return: QuantumCircuit: a circuit implementation of the Clifford. References: 1. S. Bravyi, D. Maslov, *Hadamard-free circuits expose the structure of the Clifford group*, `arXiv:2003.09412 [quant-ph] <https://arxiv.org/abs/2003.09412>`_ 2. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). `arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_ """ from qiskit.synthesis.clifford import synth_clifford_full return synth_clifford_full(self) def to_instruction(self): """Return a Gate instruction implementing the Clifford.""" return self.to_circuit().to_gate() @staticmethod def from_circuit(circuit: QuantumCircuit | Instruction) -> Clifford: """Initialize from a QuantumCircuit or Instruction. Args: circuit (QuantumCircuit or ~qiskit.circuit.Instruction): instruction to initialize. Returns: Clifford: the Clifford object for the instruction. Raises: QiskitError: if the input instruction is non-Clifford or contains classical register instruction. """ if not isinstance(circuit, (QuantumCircuit, Instruction)): raise QiskitError("Input must be a QuantumCircuit or Instruction") # Initialize an identity Clifford clifford = Clifford(np.eye(2 * circuit.num_qubits), validate=False) if isinstance(circuit, QuantumCircuit): clifford = _append_circuit(clifford, circuit) else: clifford = _append_operation(clifford, circuit) return clifford @staticmethod def from_label(label: str) -> Clifford: """Return a tensor product of single-qubit Clifford gates. Args: label (string): single-qubit operator string. Returns: Clifford: The N-qubit Clifford operator. Raises: QiskitError: if the label contains invalid characters. Additional Information: The labels correspond to the single-qubit Cliffords are * - Label - Stabilizer - Destabilizer * - ``"I"`` - +Z - +X * - ``"X"`` - -Z - +X * - ``"Y"`` - -Z - -X * - ``"Z"`` - +Z - -X * - ``"H"`` - +X - +Z * - ``"S"`` - +Z - +Y """ # Check label is valid label_gates = { "I": IGate(), "X": XGate(), "Y": YGate(), "Z": ZGate(), "H": HGate(), "S": SGate(), } if re.match(r"^[IXYZHS\-+]+$", label) is None: raise QiskitError("Label contains invalid characters.") # Initialize an identity matrix and apply each gate num_qubits = len(label) op = Clifford(np.eye(2 * num_qubits, dtype=bool)) for qubit, char in enumerate(reversed(label)): op = _append_operation(op, label_gates[char], qargs=[qubit]) return op def to_labels(self, array: bool = False, mode: Literal["S", "D", "B"] = "B"): r"""Convert a Clifford to a list Pauli (de)stabilizer string labels. For large Clifford converting using the ``array=True`` kwarg will be more efficient since it allocates memory for the full Numpy array of labels in advance. .. list-table:: Stabilizer Representations :header-rows: 1 * - Label - Phase - Symplectic - Matrix - Pauli * - ``"+I"`` - 0 - :math:`[0, 0]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}` - :math:`I` * - ``"-I"`` - 1 - :math:`[0, 0]` - :math:`\begin{bmatrix} -1 & 0 \\ 0 & -1 \end{bmatrix}` - :math:`-I` * - ``"X"`` - 0 - :math:`[1, 0]` - :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}` - :math:`X` * - ``"-X"`` - 1 - :math:`[1, 0]` - :math:`\begin{bmatrix} 0 & -1 \\ -1 & 0 \end{bmatrix}` - :math:`-X` * - ``"Y"`` - 0 - :math:`[1, 1]` - :math:`\begin{bmatrix} 0 & 1 \\ -1 & 0 \end{bmatrix}` - :math:`iY` * - ``"-Y"`` - 1 - :math:`[1, 1]` - :math:`\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}` - :math:`-iY` * - ``"Z"`` - 0 - :math:`[0, 1]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}` - :math:`Z` * - ``"-Z"`` - 1 - :math:`[0, 1]` - :math:`\begin{bmatrix} -1 & 0 \\ 0 & 1 \end{bmatrix}` - :math:`-Z` Args: array (bool): return a Numpy array if True, otherwise return a list (Default: False). mode (Literal["S", "D", "B"]): return both stabilizer and destabilizer if "B", return only stabilizer if "S" and return only destabilizer if "D". Returns: list or array: The rows of the StabilizerTable in label form. Raises: QiskitError: if stabilizer and destabilizer are both False. """ if mode not in ("S", "B", "D"): raise QiskitError("mode must be B, S, or D.") size = 2 * self.num_qubits if mode == "B" else self.num_qubits offset = self.num_qubits if mode == "S" else 0 ret = np.zeros(size, dtype=f"<U{1 + self.num_qubits}") for i in range(size): z = self.tableau[i + offset, self.num_qubits : 2 * self.num_qubits] x = self.tableau[i + offset, 0 : self.num_qubits] phase = int(self.tableau[i + offset, -1]) * 2 label = BasePauli._to_label(z, x, phase, group_phase=True) if label[0] != "-": label = "+" + label ret[i] = label if array: return ret return ret.tolist() # --------------------------------------------------------------------- # Internal helper functions # --------------------------------------------------------------------- def _hash(self): """Produce a hashable value that is unique for each different Clifford. This should only be used internally when the classes being hashed are under our control, because classes of this type are mutable.""" return np.packbits(self.tableau).tobytes() @staticmethod def _is_symplectic(mat): """Return True if input is symplectic matrix.""" # Condition is # table.T * [[0, 1], [1, 0]] * table = [[0, 1], [1, 0]] # where we are block matrix multiplying using symplectic product dim = len(mat) // 2 if mat.shape != (2 * dim, 2 * dim): return False one = np.eye(dim, dtype=int) zero = np.zeros((dim, dim), dtype=int) seye = np.block([[zero, one], [one, zero]]) arr = mat.astype(int) return np.array_equal(np.mod(arr.T.dot(seye).dot(arr), 2), seye) @staticmethod def _conjugate_transpose(clifford, method): """Return the adjoint, conjugate, or transpose of the Clifford. Args: clifford (Clifford): a clifford object. method (str): what function to apply 'A', 'C', or 'T'. Returns: Clifford: the modified clifford. """ ret = clifford.copy() if method in ["A", "T"]: # Apply inverse # Update table tmp = ret.destab_x.copy() ret.destab_x = ret.stab_z.T ret.destab_z = ret.destab_z.T ret.stab_x = ret.stab_x.T ret.stab_z = tmp.T # Update phase ret.phase ^= clifford.dot(ret).phase if method in ["C", "T"]: # Apply conjugate ret.phase ^= np.mod(_count_y(ret.x, ret.z), 2).astype(bool) return ret def _pad_with_identity(self, clifford, qargs): """Pad Clifford with identities on other subsystems.""" if qargs is None: return clifford padded = Clifford(np.eye(2 * self.num_qubits, dtype=bool), validate=False, copy=False) inds = list(qargs) + [self.num_qubits + i for i in qargs] # Pad Pauli array for i, pos in enumerate(qargs): padded.tableau[inds, pos] = clifford.tableau[:, i] padded.tableau[inds, self.num_qubits + pos] = clifford.tableau[ :, clifford.num_qubits + i ] # Pad phase padded.phase[inds] = clifford.phase return padded @staticmethod def _stack_table_phase(table, phase): return np.hstack((table, phase.reshape(len(phase), 1))) @staticmethod def _from_label(label): phase = False if label[0] in ("-", "+"): phase = label[0] == "-" label = label[1:] num_qubits = len(label) symp = np.zeros(2 * num_qubits + 1, dtype=bool) xs = symp[0:num_qubits] zs = symp[num_qubits : 2 * num_qubits] for i, char in enumerate(label): if char not in ["I", "X", "Y", "Z"]: raise QiskitError( f"Pauli string contains invalid character: {char} not in ['I', 'X', 'Y', 'Z']." ) if char in ("X", "Y"): xs[num_qubits - 1 - i] = True if char in ("Z", "Y"): zs[num_qubits - 1 - i] = True symp[-1] = phase return symp @staticmethod def _pauli_matrix_to_row(mat, num_qubits): """Generate a binary vector (a row of tableau representation) from a Pauli matrix. Return None if the non-Pauli matrix is supplied.""" # pylint: disable=too-many-return-statements def find_one_index(x, decimals=6): indices = np.where(np.round(np.abs(x), decimals) == 1) return indices[0][0] if len(indices[0]) == 1 else None def bitvector(n, num_bits): return np.array([int(digit) for digit in format(n, f"0{num_bits}b")], dtype=bool)[::-1] # compute x-bits xint = find_one_index(mat[0, :]) if xint is None: return None xbits = bitvector(xint, num_qubits) # extract non-zero elements from matrix (rounded to 1, -1, 1j or -1j) entries = np.empty(len(mat), dtype=complex) for i, row in enumerate(mat): index = find_one_index(row) if index is None: return None expected = xint ^ i if index != expected: return None entries[i] = np.round(mat[i, index]) # compute z-bits zbits = np.empty(num_qubits, dtype=bool) for k in range(num_qubits): sign = np.round(entries[2**k] / entries[0]) if sign == 1: zbits[k] = False elif sign == -1: zbits[k] = True else: return None # compute phase phase = None num_y = sum(xbits & zbits) positive_phase = (-1j) ** num_y if entries[0] == positive_phase: phase = False elif entries[0] == -1 * positive_phase: phase = True if phase is None: return None # validate all non-zero elements coef = ((-1) ** phase) * positive_phase ivec, zvec = np.ones(2), np.array([1, -1]) expected = coef * functools.reduce(np.kron, [zvec if z else ivec for z in zbits[::-1]]) if not np.allclose(entries, expected): return None return np.hstack([xbits, zbits, phase]) @staticmethod def _unitary_matrix_to_tableau(matrix): # pylint: disable=invalid-name num_qubits = int(np.log2(len(matrix))) stab = np.empty((num_qubits, 2 * num_qubits + 1), dtype=bool) for i in range(num_qubits): label = "I" * (num_qubits - i - 1) + "X" + "I" * i Xi = Operator.from_label(label).to_matrix() target = matrix @ Xi @ np.conj(matrix).T row = Clifford._pauli_matrix_to_row(target, num_qubits) if row is None: return None stab[i] = row destab = np.empty((num_qubits, 2 * num_qubits + 1), dtype=bool) for i in range(num_qubits): label = "I" * (num_qubits - i - 1) + "Z" + "I" * i Zi = Operator.from_label(label).to_matrix() target = matrix @ Zi @ np.conj(matrix).T row = Clifford._pauli_matrix_to_row(target, num_qubits) if row is None: return None destab[i] = row tableau = np.vstack([stab, destab]) return tableau # Update docstrings for API docs generate_apidocs(Clifford)
https://github.com/hephaex/Quantum-Computing-Awesome-List
hephaex
from qiskit import QuantumCircuit from qiskit.circuit import Gate from math import pi qc = QuantumCircuit(2) c = 0 t = 1 qc = QuantumCircuit(2) # a controlled-Y qc.sdg(t) qc.cx(c,t) qc.s(t) qc.draw() qc = QuantumCircuit(2) # also a controlled-Z qc.h(t) qc.cx(c,t) qc.h(t) qc.draw() qc = QuantumCircuit(2) # a controlled-H qc.ry(pi/4,t) qc.cx(c,t) qc.ry(-pi/4,t) qc.draw() #Controlled Rotations qc = QuantumCircuit(2) theta = pi # theta can be anything (pi chosen arbitrarily) qc.ry(theta/2,t) qc.cx(c,t) qc.ry(-theta/2,t) qc.cx(c,t) qc.draw()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the EchoRZXWeylDecomposition pass""" import unittest from math import pi import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import ( EchoRZXWeylDecomposition, ) from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeParis import qiskit.quantum_info as qi from qiskit.quantum_info.synthesis.two_qubit_decompose import ( TwoQubitWeylDecomposition, ) class TestEchoRZXWeylDecomposition(QiskitTestCase): """Tests the EchoRZXWeylDecomposition pass.""" def setUp(self): super().setUp() self.backend = FakeParis() self.inst_map = self.backend.defaults().instruction_schedule_map def assertRZXgates(self, unitary_circuit, after): """Check the number of rzx gates""" alpha = TwoQubitWeylDecomposition(unitary_circuit).a beta = TwoQubitWeylDecomposition(unitary_circuit).b gamma = TwoQubitWeylDecomposition(unitary_circuit).c expected_rzx_number = 0 if not alpha == 0: expected_rzx_number += 2 if not beta == 0: expected_rzx_number += 2 if not gamma == 0: expected_rzx_number += 2 circuit_rzx_number = QuantumCircuit.count_ops(after)["rzx"] self.assertEqual(expected_rzx_number, circuit_rzx_number) @staticmethod def count_gate_number(gate, circuit): """Count the number of a specific gate type in a circuit""" if gate not in QuantumCircuit.count_ops(circuit): gate_number = 0 else: gate_number = QuantumCircuit.count_ops(circuit)[gate] return gate_number def test_rzx_number_native_weyl_decomposition(self): """Check the number of RZX gates for a hardware-native cx""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) unitary_circuit = qi.Operator(circuit).data after = EchoRZXWeylDecomposition(self.inst_map)(circuit) unitary_after = qi.Operator(after).data self.assertTrue(np.allclose(unitary_circuit, unitary_after)) # check whether the after circuit has the correct number of rzx gates. self.assertRZXgates(unitary_circuit, after) def test_h_number_non_native_weyl_decomposition_1(self): """Check the number of added Hadamard gates for a native and non-native rzz gate""" theta = pi / 11 qr = QuantumRegister(2, "qr") # rzz gate in native direction circuit = QuantumCircuit(qr) circuit.rzz(theta, qr[0], qr[1]) # rzz gate in non-native direction circuit_non_native = QuantumCircuit(qr) circuit_non_native.rzz(theta, qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = EchoRZXWeylDecomposition(self.inst_map) after = dag_to_circuit(pass_.run(dag)) dag_non_native = circuit_to_dag(circuit_non_native) pass_ = EchoRZXWeylDecomposition(self.inst_map) after_non_native = dag_to_circuit(pass_.run(dag_non_native)) circuit_rzx_number = self.count_gate_number("rzx", after) circuit_h_number = self.count_gate_number("h", after) circuit_non_native_h_number = self.count_gate_number("h", after_non_native) # for each pair of rzx gates four hadamard gates have to be added in # the case of a non-hardware-native directed gate. self.assertEqual( (circuit_rzx_number / 2) * 4, circuit_non_native_h_number - circuit_h_number ) def test_h_number_non_native_weyl_decomposition_2(self): """Check the number of added Hadamard gates for a swap gate""" qr = QuantumRegister(2, "qr") # swap gate in native direction. circuit = QuantumCircuit(qr) circuit.swap(qr[0], qr[1]) # swap gate in non-native direction. circuit_non_native = QuantumCircuit(qr) circuit_non_native.swap(qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = EchoRZXWeylDecomposition(self.inst_map) after = dag_to_circuit(pass_.run(dag)) dag_non_native = circuit_to_dag(circuit_non_native) pass_ = EchoRZXWeylDecomposition(self.inst_map) after_non_native = dag_to_circuit(pass_.run(dag_non_native)) circuit_rzx_number = self.count_gate_number("rzx", after) circuit_h_number = self.count_gate_number("h", after) circuit_non_native_h_number = self.count_gate_number("h", after_non_native) # for each pair of rzx gates four hadamard gates have to be added in # the case of a non-hardware-native directed gate. self.assertEqual( (circuit_rzx_number / 2) * 4, circuit_non_native_h_number - circuit_h_number ) def test_weyl_decomposition_gate_angles(self): """Check the number and angles of the RZX gates for different gates""" thetas = [pi / 9, 2.1, -0.2] qr = QuantumRegister(2, "qr") circuit_rxx = QuantumCircuit(qr) circuit_rxx.rxx(thetas[0], qr[1], qr[0]) circuit_ryy = QuantumCircuit(qr) circuit_ryy.ryy(thetas[1], qr[0], qr[1]) circuit_rzz = QuantumCircuit(qr) circuit_rzz.rzz(thetas[2], qr[1], qr[0]) circuits = [circuit_rxx, circuit_ryy, circuit_rzz] for circuit in circuits: unitary_circuit = qi.Operator(circuit).data dag = circuit_to_dag(circuit) pass_ = EchoRZXWeylDecomposition(self.inst_map) after = dag_to_circuit(pass_.run(dag)) dag_after = circuit_to_dag(after) unitary_after = qi.Operator(after).data # check whether the unitaries are equivalent. self.assertTrue(np.allclose(unitary_circuit, unitary_after)) # check whether the after circuit has the correct number of rzx gates. self.assertRZXgates(unitary_circuit, after) alpha = TwoQubitWeylDecomposition(unitary_circuit).a rzx_angles = [] for node in dag_after.two_qubit_ops(): if node.name == "rzx": rzx_angle = node.op.params[0] # check whether the absolute values of the RZX gate angles # are equivalent to the corresponding Weyl parameter. self.assertAlmostEqual(np.abs(rzx_angle), alpha) rzx_angles.append(rzx_angle) # check whether the angles of every RZX gate pair of an echoed RZX gate # have opposite signs. for idx in range(1, len(rzx_angles), 2): self.assertAlmostEqual(rzx_angles[idx - 1], -rzx_angles[idx]) def test_weyl_unitaries_random_circuit(self): """Weyl decomposition for a random two-qubit circuit.""" theta = pi / 9 epsilon = 5 delta = -1 eta = 0.2 qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) # random two-qubit circuit. circuit.rzx(theta, 0, 1) circuit.rzz(epsilon, 0, 1) circuit.rz(eta, 0) circuit.swap(1, 0) circuit.h(0) circuit.rzz(delta, 1, 0) circuit.swap(0, 1) circuit.cx(1, 0) circuit.swap(0, 1) circuit.h(1) circuit.rxx(theta, 0, 1) circuit.ryy(theta, 1, 0) circuit.ecr(0, 1) unitary_circuit = qi.Operator(circuit).data dag = circuit_to_dag(circuit) pass_ = EchoRZXWeylDecomposition(self.inst_map) after = dag_to_circuit(pass_.run(dag)) unitary_after = qi.Operator(after).data self.assertTrue(np.allclose(unitary_circuit, unitary_after)) if __name__ == "__main__": unittest.main()
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 a single qubit # The default initial state of qubit will be |0> or [1,0] qc = QuantumCircuit(1) # declare the intial sate as [0,1] or |1> #initial_state = [0,1] #qc.initialize(initial_state,0) #Apply the Pauli X-gate on the qubit qc.x(0) #Draw the circuit # qc.draw() qc.draw('mpl') #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() #plot the result as a bloch sphere visualization plot_bloch_multivector(out) # visualize the output as an animation visualize_transition(qc) #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/2lambda123/Qiskit-qiskit
2lambda123
# 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. """Compiler Test.""" import os import unittest from qiskit import BasicAer from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit import execute from qiskit.circuit.library import U1Gate, U2Gate from qiskit.compiler import transpile, assemble from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeRueschlikon, FakeTenerife from qiskit.qobj import QasmQobj class TestCompiler(QiskitTestCase): """Qiskit Compiler Tests.""" def setUp(self): super().setUp() self.seed_simulator = 42 self.backend = BasicAer.get_backend("qasm_simulator") def test_example_multiple_compile(self): """Test a toy example compiling multiple circuits. Pass if the results are correct. """ backend = BasicAer.get_backend("qasm_simulator") coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] qr = QuantumRegister(5) cr = ClassicalRegister(5) bell = QuantumCircuit(qr, cr) ghz = QuantumCircuit(qr, cr) # Create a GHZ state ghz.h(qr[0]) for i in range(4): ghz.cx(qr[i], qr[i + 1]) # Insert a barrier before measurement ghz.barrier() # Measure all of the qubits in the standard basis for i in range(5): ghz.measure(qr[i], cr[i]) # Create a Bell state bell.h(qr[0]) bell.cx(qr[0], qr[1]) bell.barrier() bell.measure(qr[0], cr[0]) bell.measure(qr[1], cr[1]) shots = 2048 bell_backend = transpile(bell, backend=backend) ghz_backend = transpile(ghz, backend=backend, coupling_map=coupling_map) bell_qobj = assemble(bell_backend, shots=shots, seed_simulator=10) ghz_qobj = assemble(ghz_backend, shots=shots, seed_simulator=10) bell_result = backend.run(bell_qobj).result() ghz_result = backend.run(ghz_qobj).result() threshold = 0.05 * shots counts_bell = bell_result.get_counts() target_bell = {"00000": shots / 2, "00011": shots / 2} self.assertDictAlmostEqual(counts_bell, target_bell, threshold) counts_ghz = ghz_result.get_counts() target_ghz = {"00000": shots / 2, "11111": shots / 2} self.assertDictAlmostEqual(counts_ghz, target_ghz, threshold) def test_compile_coupling_map(self): """Test compile_coupling_map. If all correct should return data with the same stats. The circuit may be different. """ backend = BasicAer.get_backend("qasm_simulator") qr = QuantumRegister(3, "qr") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr, cr, name="qccccccc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.cx(qr[0], qr[2]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) shots = 2048 coupling_map = [[0, 1], [1, 2]] initial_layout = [0, 1, 2] qc_b = transpile( qc, backend=backend, coupling_map=coupling_map, initial_layout=initial_layout ) qobj = assemble(qc_b, shots=shots, seed_simulator=88) job = backend.run(qobj) result = job.result() qasm_to_check = qc.qasm() self.assertEqual(len(qasm_to_check), 173) counts = result.get_counts(qc) target = {"000": shots / 2, "111": shots / 2} threshold = 0.05 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_example_swap_bits(self): """Test a toy example swapping a set bit around. Uses the mapper. Pass if results are correct. """ backend = BasicAer.get_backend("qasm_simulator") coupling_map = [ [0, 1], [0, 8], [1, 2], [1, 9], [2, 3], [2, 10], [3, 4], [3, 11], [4, 5], [4, 12], [5, 6], [5, 13], [6, 7], [6, 14], [7, 15], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], ] # ┌───┐ ░ ┌─┐ # q0_0: ┤ X ├─X───────────░─┤M├─────────────── # └───┘ │ ░ └╥┘ ┌─┐ # q0_1: ──────┼─────X──X──░──╫────┤M├───────── # │ │ │ ░ ║ └╥┘ ┌─┐ # q0_2: ──────X──X──┼──┼──░──╫─────╫────┤M├─── # │ │ │ ░ ║ ┌─┐ ║ └╥┘ # q1_0: ─────────┼──┼──┼──░──╫─┤M├─╫─────╫──── # │ │ │ ░ ║ └╥┘ ║ ┌─┐ ║ # q1_1: ─────────┼──┼──X──░──╫──╫──╫─┤M├─╫──── # │ │ ░ ║ ║ ║ └╥┘ ║ ┌─┐ # q1_2: ─────────X──X─────░──╫──╫──╫──╫──╫─┤M├ # ░ ║ ║ ║ ║ ║ └╥┘ # c0: 6/═════════════════════╩══╩══╩══╩══╩══╩═ # 0 3 1 4 2 5 n = 3 # make this at least 3 qr0 = QuantumRegister(n) qr1 = QuantumRegister(n) ans = ClassicalRegister(2 * n) qc = QuantumCircuit(qr0, qr1, ans) # Set the first bit of qr0 qc.x(qr0[0]) # Swap the set bit qc.swap(qr0[0], qr0[n - 1]) qc.swap(qr0[n - 1], qr1[n - 1]) qc.swap(qr1[n - 1], qr0[1]) qc.swap(qr0[1], qr1[1]) # Insert a barrier before measurement qc.barrier() # Measure all of the qubits in the standard basis for j in range(n): qc.measure(qr0[j], ans[j]) qc.measure(qr1[j], ans[j + n]) # First version: no mapping result = execute( qc, backend=backend, coupling_map=None, shots=1024, seed_simulator=14 ).result() self.assertEqual(result.get_counts(qc), {"010000": 1024}) # Second version: map to coupling graph result = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, seed_simulator=14 ).result() self.assertEqual(result.get_counts(qc), {"010000": 1024}) def test_parallel_compile(self): """Trigger parallel routines in compile.""" backend = FakeRueschlikon() qr = QuantumRegister(16) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) for k in range(1, 15): qc.cx(qr[0], qr[k]) qc.measure(qr[5], cr[0]) qlist = [qc for k in range(10)] qobj = assemble(transpile(qlist, backend=backend)) self.assertEqual(len(qobj.experiments), 10) def test_no_conflict_backend_passmanager(self): """execute(qc, backend=..., passmanager=...) See: https://github.com/Qiskit/qiskit-terra/issues/5037 """ backend = BasicAer.get_backend("qasm_simulator") qc = QuantumCircuit(2) qc.append(U1Gate(0), [0]) qc.measure_all() job = execute(qc, backend=backend, pass_manager=PassManager()) result = job.result().get_counts() self.assertEqual(result, {"00": 1024}) def test_compile_single_qubit(self): """Compile a single-qubit circuit in a non-trivial layout""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) layout = {qr[0]: 12} cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit2 = transpile( circuit, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout ) qobj = assemble(circuit2) compiled_instruction = qobj.experiments[0].instructions[0] self.assertEqual(compiled_instruction.name, "u2") self.assertEqual(compiled_instruction.qubits, [12]) self.assertEqual(compiled_instruction.params, [0, 3.141592653589793]) def test_compile_pass_manager(self): """Test compile with and without an empty pass manager.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.append(U1Gate(3.14), [qr[0]]) qc.append(U2Gate(3.14, 1.57), [qr[0]]) qc.barrier(qr) qc.measure(qr, cr) backend = BasicAer.get_backend("qasm_simulator") qrtrue = assemble(transpile(qc, backend, seed_transpiler=8), seed_simulator=42) rtrue = backend.run(qrtrue).result() qrfalse = assemble(PassManager().run(qc), seed_simulator=42) rfalse = backend.run(qrfalse).result() self.assertEqual(rtrue.get_counts(), rfalse.get_counts()) def test_mapper_overoptimization(self): """Check mapper overoptimization. The mapper should not change the semantics of the input. An overoptimization introduced issue #81: https://github.com/Qiskit/qiskit-terra/issues/81 """ # ┌───┐ ┌─┐ # q0_0: ┤ X ├──■───────┤M├─────────── # ├───┤┌─┴─┐┌───┐└╥┘ ┌─┐ # q0_1: ┤ Y ├┤ X ├┤ S ├─╫───■──┤M├─── # ├───┤└───┘├───┤ ║ ┌─┴─┐└╥┘┌─┐ # q0_2: ┤ Z ├──■──┤ T ├─╫─┤ X ├─╫─┤M├ # └───┘┌─┴─┐├───┤ ║ └┬─┬┘ ║ └╥┘ # q0_3: ─────┤ X ├┤ H ├─╫──┤M├──╫──╫─ # └───┘└───┘ ║ └╥┘ ║ ║ # c0: 4/════════════════╩═══╩═══╩══╩═ # 0 3 1 2 qr = QuantumRegister(4) cr = ClassicalRegister(4) circ = QuantumCircuit(qr, cr) circ.x(qr[0]) circ.y(qr[1]) circ.z(qr[2]) circ.cx(qr[0], qr[1]) circ.cx(qr[2], qr[3]) circ.s(qr[1]) circ.t(qr[2]) circ.h(qr[3]) circ.cx(qr[1], qr[2]) circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) coupling_map = [[0, 2], [1, 2], [2, 3]] shots = 1000 result1 = execute( circ, backend=self.backend, coupling_map=coupling_map, seed_simulator=self.seed_simulator, seed_transpiler=8, shots=shots, ) count1 = result1.result().get_counts() result2 = execute( circ, backend=self.backend, coupling_map=None, seed_simulator=self.seed_simulator, seed_transpiler=8, shots=shots, ) count2 = result2.result().get_counts() self.assertDictAlmostEqual(count1, count2, shots * 0.02) def test_grovers_circuit(self): """Testing a circuit originated in the Grover algorithm""" shots = 1000 coupling_map = None # 6-qubit grovers # # ┌───┐┌───┐ ┌───┐┌───┐ ┌───┐ ┌───┐┌───┐ ░ ┌─┐ # q0_0: ┤ H ├┤ X ├──■──┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├┤ H ├──────░─┤M├─── # ├───┤└───┘ │ └───┘└───┘ │ ├───┤ │ ├───┤├───┤ ░ └╥┘┌─┐ # q0_1: ┤ H ├──■────┼─────────■────┼──┤ X ├──■──┤ X ├┤ H ├──────░──╫─┤M├ # ├───┤ │ ┌─┴─┐ │ ┌─┴─┐└───┘ │ └───┘└───┘ ░ ║ └╥┘ # q0_2: ┤ X ├──┼──┤ X ├──■────┼──┤ X ├───────┼──────────────────░──╫──╫─ # ├───┤┌─┴─┐└───┘ │ ┌─┴─┐└───┘ │ ░ ║ ║ # q0_3: ┤ X ├┤ X ├───────■──┤ X ├────────────┼──────────────────░──╫──╫─ # └───┘└───┘ ┌─┴─┐├───┤┌───┐ ┌─┴─┐┌───┐┌───┐┌───┐ ░ ║ ║ # q0_4: ───────────────┤ X ├┤ X ├┤ H ├─────┤ X ├┤ H ├┤ X ├┤ H ├─░──╫──╫─ # └───┘└───┘└───┘ └───┘└───┘└───┘└───┘ ░ ║ ║ # q0_5: ────────────────────────────────────────────────────────░──╫──╫─ # ░ ║ ║ # c0: 2/═══════════════════════════════════════════════════════════╩══╩═ # 0 1 qr = QuantumRegister(6) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr, name="grovers") circuit.h(qr[0]) circuit.h(qr[1]) circuit.x(qr[2]) circuit.x(qr[3]) circuit.x(qr[0]) circuit.cx(qr[0], qr[2]) circuit.x(qr[0]) circuit.cx(qr[1], qr[3]) circuit.ccx(qr[2], qr[3], qr[4]) circuit.cx(qr[1], qr[3]) circuit.x(qr[0]) circuit.cx(qr[0], qr[2]) circuit.x(qr[0]) circuit.x(qr[1]) circuit.x(qr[4]) circuit.h(qr[4]) circuit.ccx(qr[0], qr[1], qr[4]) circuit.h(qr[4]) circuit.x(qr[0]) circuit.x(qr[1]) circuit.x(qr[4]) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[4]) circuit.barrier(qr) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) result = execute( circuit, backend=self.backend, coupling_map=coupling_map, seed_simulator=self.seed_simulator, shots=shots, ) counts = result.result().get_counts() expected_probs = {"00": 0.64, "01": 0.117, "10": 0.113, "11": 0.13} target = {key: shots * val for key, val in expected_probs.items()} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_math_domain_error(self): """Check for floating point errors. The math library operates over floats and introduces floating point errors that should be avoided. See: https://github.com/Qiskit/qiskit-terra/issues/111 """ # ┌───┐┌───┐ ┌─┐ # q0_0: ┤ Y ├┤ X ├─────┤M├───────────────────── # └───┘└─┬─┘ └╥┘ ┌─┐ # q0_1: ───────■────────╫─────────────■──┤M├─── # ┌───┐┌───┐┌───┐ ║ ┌───┐┌───┐┌─┴─┐└╥┘┌─┐ # q0_2: ┤ Z ├┤ H ├┤ Y ├─╫─┤ T ├┤ Z ├┤ X ├─╫─┤M├ # └┬─┬┘└───┘└───┘ ║ └───┘└───┘└───┘ ║ └╥┘ # q0_3: ─┤M├────────────╫─────────────────╫──╫─ # └╥┘ ║ ║ ║ # c0: 4/══╩═════════════╩═════════════════╩══╩═ # 3 0 1 2 qr = QuantumRegister(4) cr = ClassicalRegister(4) circ = QuantumCircuit(qr, cr) circ.y(qr[0]) circ.z(qr[2]) circ.h(qr[2]) circ.cx(qr[1], qr[0]) circ.y(qr[2]) circ.t(qr[2]) circ.z(qr[2]) circ.cx(qr[1], qr[2]) circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) coupling_map = [[0, 2], [1, 2], [2, 3]] shots = 2000 job = execute( circ, backend=self.backend, coupling_map=coupling_map, seed_simulator=self.seed_simulator, shots=shots, ) counts = job.result().get_counts() target = {"0001": shots / 2, "0101": shots / 2} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_random_parameter_circuit(self): """Run a circuit with randomly generated parameters.""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "random_n5_d5.qasm")) coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]] shots = 1024 qobj = execute( circ, backend=self.backend, coupling_map=coupling_map, shots=shots, seed_simulator=self.seed_simulator, ) counts = qobj.result().get_counts() expected_probs = { "00000": 0.079239867254200971, "00001": 0.032859032998526903, "00010": 0.10752610993531816, "00011": 0.018818532050952699, "00100": 0.054830807251011054, "00101": 0.0034141983951965164, "00110": 0.041649309748902276, "00111": 0.039967731207338125, "01000": 0.10516937819949743, "01001": 0.026635620063700002, "01010": 0.0053475143548793866, "01011": 0.01940513314416064, "01100": 0.0044028405481225047, "01101": 0.057524760052126644, "01110": 0.010795354134597078, "01111": 0.026491296821535528, "10000": 0.094827455395274859, "10001": 0.0008373965072688836, "10010": 0.029082297894094441, "10011": 0.012386622870598416, "10100": 0.018739140061148799, "10101": 0.01367656456536896, "10110": 0.039184170706009248, "10111": 0.062339335178438288, "11000": 0.00293674365989009, "11001": 0.012848433960739968, "11010": 0.018472497159499782, "11011": 0.0088903691234912003, "11100": 0.031305389080034329, "11101": 0.0004788556283690458, "11110": 0.002232419390471667, "11111": 0.017684822659235985, } target = {key: shots * val for key, val in expected_probs.items()} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_yzy_zyz_cases(self): """yzy_to_zyz works in previously failed cases. See: https://github.com/Qiskit/qiskit-terra/issues/607 """ backend = FakeTenerife() qr = QuantumRegister(2) circ1 = QuantumCircuit(qr) circ1.cx(qr[0], qr[1]) circ1.rz(0.7, qr[1]) circ1.rx(1.570796, qr[1]) qobj1 = assemble(transpile(circ1, backend)) self.assertIsInstance(qobj1, QasmQobj) circ2 = QuantumCircuit(qr) circ2.y(qr[0]) circ2.h(qr[0]) circ2.s(qr[0]) circ2.h(qr[0]) qobj2 = assemble(transpile(circ2, backend)) self.assertIsInstance(qobj2, QasmQobj) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/xin-0/QC-jupyter
xin-0
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, execute, BasicAer from qiskit.visualization import plot_bloch_multivector, plot_histogram circ = QuantumCircuit(2) circ.x(0) circ.x(1) circ.h(0) circ.cx(0,1) circ.measure_all() circ.draw("mpl") res_sim = BasicAer.get_backend("qasm_simulator") counts = execute(circ,backend=res_sim,shots=1024).result().get_counts() plot_histogram(counts) def state_prepare(qc:QuantumCircuit, reg0, reg1): qc.x(reg0) qc.x(reg1) qc.h(reg0) qc.cx(reg0, reg1) return def AB_gates(qc:QuantumCircuit, a, b): qc.z(a) qc.h(b) return qc = QuantumCircuit(2) state_prepare(qc,0,1) qc.barrier() AB_gates(qc,0,1) qc.measure_all() qc.draw("mpl") from qiskit.aqua.operators import Z, X, H, One, Zero operator = - Z ^ H psi = 1 / np.sqrt(2) * ((Zero ^ One) - (One ^ Zero)) mu = (~psi @ operator @ psi).eval() print(mu.real) operator = - Z ^ (X@H@X) psi = 1 / np.sqrt(2) * ((Zero ^ One) - (One ^ Zero)) mu = (~psi @ operator @ psi).eval() print(mu.real) operator = X psi = Zero mu = (~psi @ operator @ psi).eval() print(mu.real)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.compiler import transpile # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.h(1) qc.cx(1,0) qc.rx(dt, 1) qc.rz(- dt, 1) qc.rz(dt, 0) qc.cx(1,0) qc.h(1) qc.rx(dt, [1]) qc.rz(-dt, [0,1]) qc.rx(-dt, [0,1]) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 2 # 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) # YOUR TROTTERIZATION GOES HERE -- FINISH (end of example) target_time = np.pi shots = 8192 reps = 1 # WE USE A NOISELESS SIMULATION HERE backend = Aer.get_backend('qasm_simulator') counts_01 = [] counts_10 = [] for trotter_steps in range(0, 16, 1): print("number of trotter steps: ", trotter_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) # 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>) # init state |10> (= |110>) qc.x(0) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[0], qr[1]]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / trotter_steps}) if trotter_steps > 0 else qc t0_qc = transpile(qc, optimization_level=3, basis_gates=["sx","rz","cx"]) t0_qc = t0_qc.reverse_bits() t0_qc.measure(qr, cr) print("circuit depth: ", t0_qc.depth()) job = execute(t0_qc, backend=backend, shots=shots, optimization_level=0) print("pribability distribution: ", job.result().get_counts()) counts_01.append(job.result().get_counts().get("01", 0)) counts_10.append(job.result().get_counts().get("10", 0)) print() plt.plot(range(0,16), counts_10) plt.xlabel("trotter steps") plt.ylabel("shot counts of 10") plt.title("counts of |10>") plt.plot(range(0,16), counts_01) plt.xlabel("trotter steps") plt.ylabel("shot counts of 01") plt.title("counts of |01>") t0_qc.draw("mpl")
https://github.com/MAI-cyber/QIT
MAI-cyber
! pip install numpy ! pip install qiskit ! pip install matplotlib from qiskit import QuantumCircuit, Aer ,BasicAer, execute from qiskit.visualization import plot_bloch_multivector, plot_histogram, plot_state_qsphere from qiskit.quantum_info import Statevector import matplotlib.pyplot as plt import numpy as np alpha = 0.5 beta = 0.5j normalization_factor = np.sqrt(abs(alpha**2)+ abs(beta**2)) special_state = np.array([alpha, beta]) / normalization_factor plot_bloch_multivector(special_state) teleportation_circuit = QuantumCircuit(3, 1) # Initializing the special state teleportation_circuit.initialize(special_state,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 note gates based on Alice's Results teleportation_circuit.cx(1,2) teleportation_circuit.cz(0,2) teleportation_circuit.barrier() # Measuing Bob's Qubit teleportation_circuit.measure(2,0) teleportation_circuit.draw('mpl') shots_fired = 1000 backend=Aer.get_backend('qasm_simulator') result = execute(teleportation_circuit,backend, shots = shots_fired).result() plot_histogram(result.get_counts()) print(" Probability(0) =", abs((alpha/normalization_factor)**2)) print(" Probability(1) =", abs((beta/normalization_factor)**2)) from qiskit import IBMQ IBMQ.save_account('Add the IBM token here', overwrite=True) provider=IBMQ.load_account() backend=provider.get_backend('ibm_nairobi') from qiskit.tools import job_monitor job = execute(teleportation_circuit, backend=backend, shots=shots_fired) counts=job.result().get_counts() job_monitor(job) plot_histogram(counts)
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/CynthiaRios/quantum_orchestra
CynthiaRios
![alt text](./jupyter_images/header.png "Header") #Will redo on quentin's computer tomorrow (today) pip install ipywidgets #conda install -c conda-forge ipywidgets pip install music21 pip install pydub pip install RISE ## General Imports from qiskit import QuantumCircuit, execute from qiskit import Aer from shutil import copyfile from qiskit.visualization import plot_histogram from qiskit import IBMQ import qiskit.tools.jupyter import os %qiskit_job_watcher from IPython.display import Audio import wave import numpy as np ## Button Display Imports (Needs installations mentioned above) from IPython.display import display, Markdown, clear_output # widget packages import ipywidgets as widgets from pydub import AudioSegment from music21 import * ![alt text](./jupyter_images/quantumgates.png "Quantum Gates") #Will redo on quentin's computer tomorrow (today) piano_input = [None] * 5 piano = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([piano, piano2, piano3, piano4, piano5]) box guitar_input = [None] * 5 guitar = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([guitar, guitar2, guitar3, guitar4, guitar5]) box trumpet_input = [None] * 5 trumpet = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([trumpet, trumpet2, trumpet3, trumpet4, trumpet5]) box bass_input = [None] * 5 bass = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([bass, bass2, bass3, bass4, bass5]) box def GetGates(piano_input, guitar_input, bass_input, trumpet_input): if (piano.value == 'No Gate'): piano_input[0] = 'n' if (piano.value == 'X-Gate'): piano_input[0] = 'x' if (piano.value == 'Y-Gate'): piano_input[0] = 'y' if (piano.value == 'Z-Gate'): piano_input[0] = 'z' if (piano2.value == 'No Gate'): piano_input[1] = 'n' if (piano2.value == 'X-Gate'): piano_input[1] = 'x' if (piano2.value == 'Y-Gate'): piano_input[1] = 'y' if (piano2.value == 'Z-Gate'): piano_input[1] = 'z' if (piano3.value == 'No Gate'): piano_input[2] = 'n' if (piano3.value == 'X-Gate'): piano_input[2] = 'x' if (piano3.value == 'Y-Gate'): piano_input[2] = 'y' if (piano3.value == 'Z-Gate'): piano_input[2] = 'z' if (piano4.value == 'No Gate'): piano_input[3] = 'n' if (piano4.value == 'X-Gate'): piano_input[3] = 'x' if (piano4.value == 'Y-Gate'): piano_input[3] = 'y' if (piano4.value == 'Z-Gate'): piano_input[3] = 'z' if (piano5.value == 'No Gate'): piano_input[4] = 'n' if (piano5.value == 'X-Gate'): piano_input[4] = 'x' if (piano5.value == 'Y-Gate'): piano_input[4] = 'y' if (piano5.value == 'Z-Gate'): piano_input[4] = 'z' if (guitar.value == 'No Gate'): guitar_input[0] = 'n' if (guitar.value == 'X-Gate'): guitar_input[0] = 'x' if (guitar.value == 'Y-Gate'): guitar_input[0] = 'y' if (guitar.value == 'Z-Gate'): guitar_input[0] = 'z' if (guitar2.value == 'No Gate'): guitar_input[1] = 'n' if (guitar2.value == 'X-Gate'): guitar_input[1] = 'x' if (guitar2.value == 'Y-Gate'): guitar_input[1] = 'y' if (guitar2.value == 'Z-Gate'): guitar_input[1] = 'z' if (guitar3.value == 'No Gate'): guitar_input[2] = 'n' if (guitar3.value == 'X-Gate'): guitar_input[2] = 'x' if (guitar3.value == 'Y-Gate'): guitar_input[2] = 'y' if (guitar3.value == 'Z-Gate'): guitar_input[2] = 'z' if (guitar4.value == 'No Gate'): guitar_input[3] = 'n' if (guitar4.value == 'X-Gate'): guitar_input[3] = 'x' if (guitar4.value == 'Y-Gate'): guitar_input[3] = 'y' if (guitar4.value == 'Z-Gate'): guitar_input[3] = 'z' if (guitar5.value == 'No Gate'): guitar_input[4] = 'n' if (guitar5.value == 'X-Gate'): guitar_input[4] = 'x' if (guitar5.value == 'Y-Gate'): guitar_input[4] = 'y' if (guitar5.value == 'Z-Gate'): guitar_input[4] = 'z' if (bass.value == 'No Gate'): bass_input[0] = 'n' if (bass.value == 'X-Gate'): bass_input[0] = 'x' if (bass.value == 'Y-Gate'): bass_input[0] = 'y' if (bass.value == 'Z-Gate'): bass_input[0] = 'z' if (bass2.value == 'No Gate'): bass_input[1] = 'n' if (bass2.value == 'X-Gate'): bass_input[1] = 'x' if (bass2.value == 'Y-Gate'): bass_input[1] = 'y' if (bass2.value == 'Z-Gate'): bass_input[1] = 'z' if (bass3.value == 'No Gate'): bass_input[2] = 'n' if (bass3.value == 'X-Gate'): bass_input[2] = 'x' if (bass3.value == 'Y-Gate'): bass_input[2] = 'y' if (bass3.value == 'Z-Gate'): bass_input[2] = 'z' if (bass4.value == 'No Gate'): bass_input[3] = 'n' if (bass4.value == 'X-Gate'): bass_input[3] = 'x' if (bass4.value == 'Y-Gate'): bass_input[3] = 'y' if (bass4.value == 'Z-Gate'): bass_input[3] = 'z' if (bass5.value == 'No Gate'): bass_input[4] = 'n' if (bass5.value == 'X-Gate'): bass_input[4] = 'x' if (bass5.value == 'Y-Gate'): bass_input[4] = 'y' if (bass5.value == 'Z-Gate'): bass_input[4] = 'z' if (trumpet.value == 'No Gate'): trumpet_input[0] = 'n' if (trumpet.value == 'X-Gate'): trumpet_input[0] = 'x' if (trumpet.value == 'Y-Gate'): trumpet_input[0] = 'y' if (trumpet.value == 'Z-Gate'): trumpet_input[0] = 'z' if (trumpet2.value == 'No Gate'): trumpet_input[1] = 'n' if (trumpet2.value == 'X-Gate'): trumpet_input[1] = 'x' if (trumpet2.value == 'Y-Gate'): trumpet_input[1] = 'y' if (trumpet2.value == 'Z-Gate'): trumpet_input[1] = 'z' if (trumpet3.value == 'No Gate'): trumpet_input[2] = 'n' if (trumpet3.value == 'X-Gate'): trumpet_input[2] = 'x' if (trumpet3.value == 'Y-Gate'): trumpet_input[2] = 'y' if (trumpet3.value == 'Z-Gate'): trumpet_input[2] = 'z' if (trumpet4.value == 'No Gate'): trumpet_input[3] = 'n' if (trumpet4.value == 'X-Gate'): trumpet_input[3] = 'x' if (trumpet4.value == 'Y-Gate'): trumpet_input[3] = 'y' if (trumpet4.value == 'Z-Gate'): trumpet_input[3] = 'z' if (trumpet5.value == 'No Gate'): trumpet_input[4] = 'n' if (trumpet5.value == 'X-Gate'): trumpet_input[4] = 'x' if (trumpet5.value == 'Y-Gate'): trumpet_input[4] = 'y' if (trumpet5.value == 'Z-Gate'): trumpet_input[4] = 'z' return (piano_input, guitar_input, bass_input, trumpet_input) piano_input, guitar_input, bass_input, trumpet_input = GetGates(piano_input, guitar_input, bass_input, trumpet_input) #minimum user input will just be for them to fill out the create quantum circuit function inthe backend n = 5 #number of gates backend = Aer.get_backend('statevector_simulator') piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] def CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input): cct = QuantumCircuit(4,1) piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] for i in range(n-1): cct.h(i-1) cct.barrier() for i in range(n): if piano_input[i-1] == 'x': cct.x(0) if piano_input[i-1] == 'y': cct.y(0) if piano_input[i-1] == 'z': cct.z(0) piano_states.append(execute(cct, backend).result().get_statevector()) if guitar_input[i-1] == 'x': cct.x(1) if guitar_input[i-1] == 'y': cct.y(1) if guitar_input[i-1] == 'z': cct.z(1) guitar_states.append(execute(cct, backend).result().get_statevector()) if bass_input[i-1] == 'x': cct.x(2) if bass_input[i-1] == 'y': cct.y(2) if bass_input[i-1] == 'z': cct.z(2) bass_states.append(execute(cct, backend).result().get_statevector()) if trumpet_input[i-1] == 'x': cct.x(3) if trumpet_input[i-1] == 'y': cct.y(3) if trumpet_input[i-1] == 'z': cct.z(3) trumpet_states.append(execute(cct, backend).result().get_statevector()) cct.barrier() cct.draw('mpl') return piano_states, guitar_states, bass_states, trumpet_states, cct piano_states, guitar_states, bass_states, trumpet_states, cct = CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input) cct.draw(output="mpl") def SeperateArrays(states, vals_real, vals_imaginary): vals = [] for i in range(n+1): vals.append(states[i-1][0]) for i in range(n+1): vals_real.append((states[i-1][0].real)) vals_imaginary.append((states[i-1][0]).imag) return vals_real, vals_imaginary piano_real = [] piano_imaginary = [] piano_vals = [] guitar_real = [] guitar_imaginary = [] guitar_vals = [] bass_real = [] bass_imaginary = [] bass_vals = [] trumpet_real = [] trumpet_imaginary = [] trumpet_vals = [] piano_real, piano_imaginary = SeperateArrays(piano_states, piano_real, piano_imaginary) guitar_real, guitar_imaginary = SeperateArrays(guitar_states, guitar_real, guitar_imaginary) bass_real, bass_imaginary = SeperateArrays(bass_states, bass_real, bass_imaginary) trumpet_real, trumpet_imaginary = SeperateArrays(trumpet_states, trumpet_real, trumpet_imaginary) def MusicalTransformation(real, imaginary): tune_array=[] for i in range(n+1): if(real[i-1] < 0 and imaginary[i-1] > 0): tune_array.append('c') tune_array.append('g') tune_array.append('e') if(real[i-1] < 0 and imaginary[i-1] <= 0): tune_array.append('c') tune_array.append('f') tune_array.append('g') if(real[i-1] < 0 and imaginary[i-1] > 0): tune_array.append('d') tune_array.append('f') tune_array.append('a') if(real[i-1] < 0 and imaginary[i-1] <= 0): tune_array.append('f') tune_array.append('a') tune_array.append('c') if(real[i-1] > 0 and imaginary[i-1] > 0): tune_array.append('g') tune_array.append('b') tune_array.append('d') if(real[i-1] > 0 and imaginary[i-1] < 0): tune_array.append('d') tune_array.append('f') tune_array.append('a') if(real[i-1] > 0 and imaginary[i-1] >= 0): tune_array.append('e') tune_array.append('g') tune_array.append('b') if(real[i-1] > 0 and imaginary[i-1] < 0): tune_array.append('a') tune_array.append('c') tune_array.append('b') if(real[i-1] == 0 and imaginary[i-1] == 0): tune_array.append('n') tune_array.append('n') tune_array.append('n') return tune_array tune_array_piano = MusicalTransformation(piano_real, piano_imaginary) tune_array_guitar = MusicalTransformation(guitar_real, guitar_imaginary) tune_array_bass = MusicalTransformation(bass_real, bass_imaginary) tune_array_trumpet = MusicalTransformation(trumpet_real, trumpet_imaginary) def PlayPianoTune(character, songs): if character == 'a': sound_file = "./Audio/Piano/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Piano/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Piano/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Piano/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Piano/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Piano/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Piano/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayGuitarTune(character, songs): if character == 'a': sound_file = "./Audio/Guitar/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Guitar/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Guitar/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Guitar/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Guitar/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Guitar/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Guitar/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayBassTune(character, songs): if character == 'a': sound_file = "./Audio/Bass/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Bass/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Bass/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Bass/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Bass/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Bass/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Bass/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayTrumpetTune(character, songs): if character == 'a': sound_file = "./Audio/Trumpet/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Trumpet/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Trumpet/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Trumpet/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Trumpet/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Trumpet/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Trumpet/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs piano_song = [] for i in range(len(tune_array_piano)): character = tune_array_piano[i-1] piano_song = PlayPianoTune(character, piano_song) os.remove("./pianosounds.wav") copyfile('./Audio/blank.wav','./pianosounds.wav') for i in range(len(tune_array_piano)): infiles = [piano_song[i-1], "pianosounds.wav"] outfile = "pianosounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() guitar_song = [] for i in range(len(tune_array_guitar)): character = tune_array_piano[i-1] guitar_song = PlayGuitarTune(character, guitar_song) os.remove("./guitarsounds.wav") copyfile('./Audio/blank.wav','./guitarsounds.wav') for i in range(len(tune_array_guitar)): infiles = [guitar_song[i-1], "guitarsounds.wav"] outfile = "guitarsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() bass_song = [] for i in range(len(tune_array_bass)): character = tune_array_bass[i-1] bass_song = PlayBassTune(character, bass_song) os.remove("./basssounds.wav") copyfile('./Audio/blank.wav','./basssounds.wav') for i in range(len(tune_array_bass)): infiles = [bass_song[i-1], "basssounds.wav"] outfile = "basssounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() trumpet_song = [] for i in range(len(tune_array_trumpet)): character = tune_array_trumpet[i-1] trumpet_song = PlayTrumpetTune(character, trumpet_song) os.remove("./trumpetsounds.wav") copyfile('./Audio/blank.wav','./trumpetsounds.wav') for i in range(len(tune_array_trumpet)): infiles = [trumpet_song[i-1], "trumpetsounds.wav"] outfile = "trumpetsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() sound1 = AudioSegment.from_file("./trumpetsounds.wav") sound2 = AudioSegment.from_file("./basssounds.wav") combined = sound1.overlay(sound2) combined.export("./combined.wav", format='wav') sound3 = AudioSegment.from_file("./guitarsounds.wav") sound4 = AudioSegment.from_file("./pianosounds.wav") combined2 = sound3.overlay(sound4) combined2.export("./combined2.wav", format='wav') sound5 = AudioSegment.from_file("./combined.wav") sound6 = AudioSegment.from_file("./combined2.wav") output_song = sound5.overlay(sound6) output_song.export("./output_song.wav", format='wav') sound_file = "./output_song.wav" Audio(sound_file, autoplay=True) print(tune_array_piano) a = 64 b = 65 c = 66 d = 67 e = 68 f = 69 g = 70 print(tune_array_piano[0]) streamPiano = stream.Stream() instrumentPiano = [] for i in range(18): instrumentPiano.append(note.Note(tune_array_piano[i])) streamPiano.append(instrumentPiano) streamPiano.show() a = 57 b = 58 c = 59 d = 60 e = 61 f = 62 g = 63 print(tune_array_guitar) streamGuitar = stream.Stream() instrumentGuitar = [] for i in range(18): instrumentGuitar.append(note.Note(tune_array_guitar[i])) streamGuitar.append(instrumentGuitar) streamGuitar.show() a = 50 b = 51 c = 52 d = 53 e = 54 f = 55 g = 56 print(tune_array_trumpet) streamTrumpet = stream.Stream() streamBass = stream.Stream() instrumentTrumpet = [] for i in range(18): instrumentTrumpet.append(note.Note(tune_array_trumpet[i])) streamTrumpet.append(instrumentTrumpet) streamTrumpet.show() a = 43 b = 44 c = 45 d = 46 e = 47 f = 48 g = 49 print(tune_array_bass) streamBass = stream.Stream() instrumentBass = [] for i in range(18): instrumentBass.append(note.Note(tune_array_bass[i])) streamBass.append(instrumentBass) streamBass.show() excerpt = streamPiano.measures(1, 4) excerpt.show() streamPiano.getElementsByClass('Measure').insert(0.0, instrument.Piano()) streamGuitar.getElementsByClass('Measure').insert(1.0, instrument.Guitar()) streamTrumpet.getElementsByClass('Measure').insert(2.0, instrument.Trumpet()) streamBass.getElementsByClass('Measure').insert(3.0, instrument.Bass()) s = stream.Score() s.insert(0, streamPiano) s.insert(0, streamGuitar) s.insert(0, streamTrumpet) s.insert(0, streamBass) s.show() s.show('musicxml') #this show on musescore
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
#Import general libraries (needed for functions) import numpy as np import matplotlib.pyplot as plt from IPython import display #Import Qiskit classes classes import qiskit from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error #Import the RB Functions import qiskit.ignis.verification.randomized_benchmarking as rb #Number of qubits nQ = 3 #There are 3 qubits: Q0,Q1,Q2. #Number of seeds (random sequences) nseeds = 5 #Number of Cliffords in the sequence (start, stop, steps) nCliffs = np.arange(1,200,20) #2Q RB on Q0,Q2 and 1Q RB on Q1 rb_pattern = [[0,2],[1]] #Do three times as many 1Q Cliffords length_multiplier = [1,3] rb_opts = {} rb_opts['length_vector'] = nCliffs rb_opts['nseeds'] = nseeds rb_opts['rb_pattern'] = rb_pattern rb_opts['length_multiplier'] = length_multiplier rb_circs, xdata = rb.randomized_benchmarking_seq(**rb_opts) print(rb_circs[0][0]) #Create a new circuit without the measurement qc = qiskit.QuantumCircuit(*rb_circs[0][-1].qregs,*rb_circs[0][-1].cregs) for i in rb_circs[0][-1][0:-nQ]: qc._attach(i) #The Unitary is an identity (with a global phase) backend = qiskit.Aer.get_backend('unitary_simulator') basis_gates = ['u1','u2','u3','cx'] # use U,CX for now basis_gates_str = ','.join(basis_gates) job = qiskit.execute(qc, backend=backend, basis_gates=basis_gates_str) print(np.around(job.result().get_unitary(),3)) noise_model = NoiseModel() p1Q = 0.002 p2Q = 0.01 noise_model.add_all_qubit_quantum_error(depolarizing_error(p1Q, 1), 'u2') noise_model.add_all_qubit_quantum_error(depolarizing_error(2*p1Q, 1), 'u3') noise_model.add_all_qubit_quantum_error(depolarizing_error(p2Q, 2), 'cx') #noise_model = None backend = qiskit.Aer.get_backend('qasm_simulator') basis_gates = ['u1','u2','u3','cx'] # use U,CX for now basis_gates_str = ','.join(basis_gates) shots = 200 result_list = [] qobj_list = [] import time for rb_seed,rb_circ_seed in enumerate(rb_circs): print('Compiling seed %d'%rb_seed) qobj = qiskit.compile(rb_circ_seed, backend=backend, basis_gates=basis_gates_str, shots=shots) print('Simulating seed %d'%rb_seed) job = backend.run(qobj, noise_model=noise_model, backend_options={'max_parallel_experiments': 0}) result_list.append(job.result()) qobj_list.append(qobj) print("Finished Simulating") #Create an RBFitter object with 1 seed of data rbfit = rb.fitters.RBFitter(result_list[0], xdata, rb_opts['rb_pattern']) plt.figure(figsize=(15, 6)) for i in range(2): ax = plt.subplot(1, 2, i+1) pattern_ind = i # Plot the essence by calling plot_rb_data rbfit.plot_rb_data(pattern_ind, ax=ax, add_label=True, show_plt=False) # Add title and label ax.set_title('%d Qubit RB'%(len(rb_opts['rb_pattern'][i])), fontsize=18) plt.show() rbfit = rb.fitters.RBFitter(result_list[0], xdata, rb_opts['rb_pattern']) for seed_num, data in enumerate(result_list):#range(1,len(result_list)): plt.figure(figsize=(15, 6)) axis = [plt.subplot(1, 2, 1), plt.subplot(1, 2, 2)] # Add another seed to the data rbfit.add_data([data]) for i in range(2): pattern_ind = i # Plot the essence by calling plot_rb_data rbfit.plot_rb_data(pattern_ind, ax=axis[i], add_label=True, show_plt=False) # Add title and label axis[i].set_title('%d Qubit RB - after seed %d'%(len(rb_opts['rb_pattern'][i]), seed_num), fontsize=18) # Display display.display(plt.gcf()) # Clear display after each seed and close display.clear_output(wait=True) time.sleep(1.0) plt.close() shots = 200 result_list = [] qobj_list = [] for rb_seed,rb_circ_seed in enumerate(rb_circs): print('Compiling seed %d'%rb_seed) qobj = qiskit.compile(rb_circ_seed, backend=backend, basis_gates=basis_gates_str, shots=shots) print('Simulating seed %d'%rb_seed) job = backend.run(qobj, noise_model=noise_model, backend_options={'max_parallel_experiments': 0}) result_list.append(job.result()) qobj_list.append(qobj) print("Finished Simulating") #Add this data to the previous fit rbfit.add_data(result_list) #Replot plt.figure(figsize=(15, 6)) for i in range(2): ax = plt.subplot(1, 2, i+1) pattern_ind = i # Plot the essence by calling plot_rb_data rbfit.plot_rb_data(pattern_ind, ax=ax, add_label=True, show_plt=False) # Add title and label ax.set_title('%d Qubit RB'%(len(rb_opts['rb_pattern'][i])), fontsize=18) plt.show() #Count the number of single and 2Q gates in the 2Q Cliffords gates_per_cliff = rb.rb_utils.gates_per_clifford(qobj_list,xdata[0],basis_gates,rb_opts['rb_pattern'][0]) for i in range(len(basis_gates)): print("Number of %s gates per Clifford: %f"%(basis_gates[i], np.mean([gates_per_cliff[0][i],gates_per_cliff[0][i]]))) #Prepare lists of the number of qubits and the errors ngates = np.zeros(7) ngates[0:3] = gates_per_cliff[0][0:3] ngates[3:6] = gates_per_cliff[1][0:3] ngates[6] = gates_per_cliff[0][3] gate_qubits = np.array([0,0,0,1,1,1,-1], dtype=int) gate_errs = np.zeros(len(gate_qubits)) gate_errs[[1,4]] = p1Q/2 #convert from depolarizing error to epg (1Q) gate_errs[[2,5]] = 2*p1Q/2 #convert from depolarizing error to epg (1Q) gate_errs[6] = p2Q*3/4 #convert from depolarizing error to epg (2Q) #Calculate the predicted epc pred_epc = rb.rb_utils.twoQ_clifford_error(ngates,gate_qubits,gate_errs) print("Predicted 2Q Error per Clifford: %e"%pred_epc) rb_opts2 = rb_opts.copy() rb_opts2['rb_pattern'] = [[0,1]] rb_opts2['length_multiplier'] = 1 rb_circs2, xdata2 = rb.randomized_benchmarking_seq(**rb_opts2) noise_model2 = NoiseModel() #Add T1/T2 noise to the simulation t1 = 100. t2 = 80. gate1Q = 0.1 gate2Q = 0.5 noise_model2.add_all_qubit_quantum_error(thermal_relaxation_error(t1,t2,gate1Q), 'u2') noise_model2.add_all_qubit_quantum_error(thermal_relaxation_error(t1,t2,2*gate1Q), 'u3') noise_model2.add_all_qubit_quantum_error( thermal_relaxation_error(t1,t2,gate2Q).kron(thermal_relaxation_error(t1,t2,gate2Q)), 'cx') backend = qiskit.Aer.get_backend('qasm_simulator') basis_gates = ['u1','u2','u3','cx'] # use U,CX for now basis_gates_str = ','.join(basis_gates) shots = 500 result_list2 = [] qobj_list2 = [] for rb_seed,rb_circ_seed in enumerate(rb_circs2): print('Compiling seed %d'%rb_seed) qobj = qiskit.compile(rb_circ_seed, backend=backend, basis_gates=basis_gates_str, shots=shots) print('Simulating seed %d'%rb_seed) job = backend.run(qobj, noise_model=noise_model2, backend_options={'max_parallel_experiments': 0}) result_list2.append(job.result()) qobj_list2.append(qobj) print("Finished Simulating") #Create an RBFitter object rbfit = rb.RBFitter(result_list2, xdata2, rb_opts2['rb_pattern']) plt.figure(figsize=(10, 6)) ax = plt.gca() # Plot the essence by calling plot_rb_data rbfit.plot_rb_data(0, ax=ax, add_label=True, show_plt=False) # Add title and label ax.set_title('2 Qubit RB with T1/T2 noise', fontsize=18) plt.show() #Count the number of single and 2Q gates in the 2Q Cliffords gates_per_cliff = rb.rb_utils.gates_per_clifford(qobj_list2,xdata2[0],basis_gates,rb_opts2['rb_pattern'][0]) for i in range(len(basis_gates)): print("Number of %s gates per Clifford: %f"%(basis_gates[i], np.mean([gates_per_cliff[0][i],gates_per_cliff[0][i]]))) #Prepare lists of the number of qubits and the errors ngates = np.zeros(7) ngates[0:3] = gates_per_cliff[0][0:3] ngates[3:6] = gates_per_cliff[1][0:3] ngates[6] = gates_per_cliff[0][3] gate_qubits = np.array([0,0,0,1,1,1,-1], dtype=int) gate_errs = np.zeros(len(gate_qubits)) #Here are the predicted primitive gate errors from the coherence limit gate_errs[[1,4]] = rb.rb_utils.coherence_limit(1,[t1],[t2],gate1Q) gate_errs[[2,5]] = rb.rb_utils.coherence_limit(1,[t1],[t2],2*gate1Q) gate_errs[6] = rb.rb_utils.coherence_limit(2,[t1,t1],[t2,t2],gate2Q) #Calculate the predicted epc pred_epc = rb.rb_utils.twoQ_clifford_error(ngates,gate_qubits,gate_errs) print("Predicted 2Q Error per Clifford: %e"%pred_epc)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") 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") # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots, optimization_level = 0) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) dt_now = datetime.datetime.now() print(dt_now) import pickle with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') 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/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. # pylint: disable=missing-class-docstring,missing-function-docstring """Test Counts class.""" import unittest import numpy as np from qiskit.result import counts from qiskit import exceptions from qiskit.result import utils class TestCounts(unittest.TestCase): def test_just_counts(self): raw_counts = {"0x0": 21, "0x2": 12} expected = {"0": 21, "10": 12} result = counts.Counts(raw_counts) self.assertEqual(expected, result) def test_counts_with_exta_formatting_data(self): raw_counts = {"0x0": 4, "0x2": 10} expected = {"0 0 00": 4, "0 0 10": 10} result = counts.Counts( raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 ) self.assertEqual(result, expected) def test_marginal_counts(self): raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_counts(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution(self): raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution_numpy_indices(self): raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} expected = {"00": 4, "01": 27, "10": 23} indices = np.asarray([0, 1]) counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, indices) self.assertEqual(expected, result) def test_int_outcomes(self): raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265} expected = {0: 21, 2: 12, 3: 5, 46: 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.int_outcomes() self.assertEqual(expected, result) def test_most_frequent(self): raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265} expected = "101110" counts_obj = counts.Counts(raw_counts) result = counts_obj.most_frequent() self.assertEqual(expected, result) def test_most_frequent_duplicate(self): raw_counts = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2E": 265} counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent) def test_hex_outcomes(self): raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265} expected = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2e": 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.hex_outcomes() self.assertEqual(expected, result) def test_just_int_counts(self): raw_counts = {0: 21, 2: 12} expected = {"0": 21, "10": 12} result = counts.Counts(raw_counts) self.assertEqual(expected, result) def test_int_counts_with_exta_formatting_data(self): raw_counts = {0: 4, 2: 10} expected = {"0 0 00": 4, "0 0 10": 10} result = counts.Counts( raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 ) self.assertEqual(result, expected) def test_marginal_int_counts(self): raw_counts = {0: 4, 1: 7, 2: 10, 6: 5, 9: 11, 13: 9, 14: 8} expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_counts(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution_int_counts(self): raw_counts = {0: 4, 1: 7, 2: 10, 6: 5, 9: 11, 13: 9, 14: 8} expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution_int_counts_numpy_64_bit(self): raw_counts = { 0: np.int64(4), 1: np.int64(7), 2: np.int64(10), 6: np.int64(5), 9: np.int64(11), 13: np.int64(9), 14: np.int64(8), } expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution_int_counts_numpy_8_bit(self): raw_counts = { 0: np.int8(4), 1: np.int8(7), 2: np.int8(10), 6: np.int8(5), 9: np.int8(11), 13: np.int8(9), 14: np.int8(8), } expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_int_outcomes_with_int_counts(self): raw_counts = {0: 21, 2: 12, 3: 5, 46: 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.int_outcomes() self.assertEqual(raw_counts, result) def test_most_frequent_int_counts(self): raw_counts = {0: 21, 2: 12, 3: 5, 46: 265} expected = "101110" counts_obj = counts.Counts(raw_counts) result = counts_obj.most_frequent() self.assertEqual(expected, result) def test_most_frequent_duplicate_int_counts(self): raw_counts = {0: 265, 2: 12, 3: 5, 46: 265} counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent) def test_hex_outcomes_int_counts(self): raw_counts = {0: 265, 2: 12, 3: 5, 46: 265} expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.hex_outcomes() self.assertEqual(expected, result) def test_invalid_input_type(self): self.assertRaises(TypeError, counts.Counts, {2.4: 1024}) def test_just_bitstring_counts(self): raw_counts = {"0": 21, "10": 12} expected = {"0": 21, "10": 12} result = counts.Counts(raw_counts) self.assertEqual(expected, result) def test_bistring_counts_with_exta_formatting_data(self): raw_counts = {"0": 4, "10": 10} expected = {"0 0 00": 4, "0 0 10": 10} result = counts.Counts( raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 ) self.assertEqual(result, expected) def test_marginal_bitstring_counts(self): raw_counts = {"0": 4, "1": 7, "10": 10, "110": 5, "1001": 11, "1101": 9, "1110": 8} expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_counts(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution_bitstring_counts(self): raw_counts = {"0": 4, "1": 7, "10": 10, "110": 5, "1001": 11, "1101": 9, "1110": 8} expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_int_outcomes_with_bitstring_counts(self): raw_counts = {"0": 21, "10": 12, "11": 5, "101110": 265} expected = {0: 21, 2: 12, 3: 5, 46: 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.int_outcomes() self.assertEqual(expected, result) def test_most_frequent_bitstring_counts(self): raw_counts = {"0": 21, "10": 12, "11": 5, "101110": 265} expected = "101110" counts_obj = counts.Counts(raw_counts) result = counts_obj.most_frequent() self.assertEqual(expected, result) def test_most_frequent_duplicate_bitstring_counts(self): raw_counts = {"0": 265, "10": 12, "11": 5, "101110": 265} counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent) def test_hex_outcomes_bitstring_counts(self): raw_counts = {"0": 265, "10": 12, "11": 5, "101110": 265} expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.hex_outcomes() self.assertEqual(expected, result) def test_qudit_counts(self): raw_counts = { "00": 121, "01": 109, "02": 114, "10": 113, "11": 106, "12": 114, "20": 117, "21": 104, "22": 102, } result = counts.Counts(raw_counts) self.assertEqual(raw_counts, result) def test_qudit_counts_raises_with_format(self): raw_counts = { "00": 121, "01": 109, "02": 114, "10": 113, "11": 106, "12": 114, "20": 117, "21": 104, "22": 102, } self.assertRaises(exceptions.QiskitError, counts.Counts, raw_counts, creg_sizes=[["c0", 4]]) def test_qudit_counts_hex_outcome(self): raw_counts = { "00": 121, "01": 109, "02": 114, "10": 113, "11": 106, "12": 114, "20": 117, "21": 104, "22": 102, } counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.hex_outcomes) def test_qudit_counts_int_outcome(self): raw_counts = { "00": 121, "01": 109, "02": 114, "10": 113, "11": 106, "12": 114, "20": 117, "21": 104, "22": 102, } counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.int_outcomes) def test_qudit_counts_most_frequent(self): raw_counts = { "00": 121, "01": 109, "02": 114, "10": 113, "11": 106, "12": 114, "20": 117, "21": 104, "22": 102, } counts_obj = counts.Counts(raw_counts) self.assertEqual("00", counts_obj.most_frequent()) def test_just_0b_bitstring_counts(self): raw_counts = {"0b0": 21, "0b10": 12} expected = {"0": 21, "10": 12} result = counts.Counts(raw_counts) self.assertEqual(expected, result) def test_0b_bistring_counts_with_exta_formatting_data(self): raw_counts = {"0b0": 4, "0b10": 10} expected = {"0 0 00": 4, "0 0 10": 10} result = counts.Counts( raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 ) self.assertEqual(result, expected) def test_marginal_0b_string_counts(self): raw_counts = { "0b0": 4, "0b1": 7, "0b10": 10, "0b110": 5, "0b1001": 11, "0b1101": 9, "0b1110": 8, } expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_counts(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_marginal_distribution_0b_string_counts(self): raw_counts = { "0b0": 4, "0b1": 7, "0b10": 10, "0b110": 5, "0b1001": 11, "0b1101": 9, "0b1110": 8, } expected = {"00": 4, "01": 27, "10": 23} counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) def test_int_outcomes_with_0b_bitstring_counts(self): raw_counts = {"0b0": 21, "0b10": 12, "0b11": 5, "0b101110": 265} expected = {0: 21, 2: 12, 3: 5, 46: 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.int_outcomes() self.assertEqual(expected, result) def test_most_frequent_0b_bitstring_counts(self): raw_counts = {"0b0": 21, "0b10": 12, "0b11": 5, "0b101110": 265} expected = "101110" counts_obj = counts.Counts(raw_counts) result = counts_obj.most_frequent() self.assertEqual(expected, result) def test_most_frequent_duplicate_0b_bitstring_counts(self): raw_counts = {"0b0": 265, "0b10": 12, "0b11": 5, "0b101110": 265} counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent) def test_hex_outcomes_0b_bitstring_counts(self): raw_counts = {"0b0": 265, "0b10": 12, "0b11": 5, "0b101110": 265} expected = {"0x0": 265, "0x2": 12, "0x3": 5, "0x2e": 265} counts_obj = counts.Counts(raw_counts) result = counts_obj.hex_outcomes() self.assertEqual(expected, result) def test_empty_bitstring_counts(self): raw_counts = {} expected = {} result = counts.Counts(raw_counts) self.assertEqual(expected, result) def test_empty_bistring_counts_with_exta_formatting_data(self): raw_counts = {} expected = {} result = counts.Counts( raw_counts, "test_counts", creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 ) self.assertEqual(result, expected) def test_int_outcomes_with_empty_counts(self): raw_counts = {} expected = {} counts_obj = counts.Counts(raw_counts) result = counts_obj.int_outcomes() self.assertEqual(expected, result) def test_most_frequent_empty_bitstring_counts(self): raw_counts = {} counts_obj = counts.Counts(raw_counts) self.assertRaises(exceptions.QiskitError, counts_obj.most_frequent) def test_hex_outcomes_empty_bitstring_counts(self): raw_counts = {} expected = {} counts_obj = counts.Counts(raw_counts) result = counts_obj.hex_outcomes() self.assertEqual(expected, result)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
from qiskit_ibm_runtime import QiskitRuntimeService QiskitRuntimeService.save_account(channel='ibm_quantum', token='83ab2a86232e48767228534cdae2cf55b8e8ea4e0eb1e57804268f40d7bee64692f719528e8871de617ffc35040d21bd389f4696313f46900c077c7f617a1512', overwrite=True) service = QiskitRuntimeService(instance='ibm-q/open/main') print(service.backends()) from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.measure_all() qc.draw() from qiskit_ibm_runtime import Sampler, Options, Session options = Options(optimization_level=1) with Session(service=service, backend="ibmq_qasm_simulator") as session: sampler = Sampler(session=session, options=options) job = sampler.run(circuits=qc) # foi usado 18 s dos 10 min (por conjunto de 4000 prepara-evolui-mede experimentos) job.result() # 'probabilidades' (eles chamam de quasiprobabilidades) counts = job.result().quasi_dists[0].binary_probabilities() counts from qiskit.visualization import plot_histogram plot_histogram(counts) backend = service.get_backend("ibm_osaka") with Session(service=service, backend=backend) as session: sampler = Sampler(session=session, options=options) job = sampler.run(circuits=qc) print(job.job_id()) jobr = service.job('cnvn5zzvn4c0008a6df0') jobr.result() counts = jobr.result().quasi_dists[0].binary_probabilities() counts # ? plot_histogram(counts) print(jobr.logs()) from qiskit.circuit.library import RealAmplitudes from qiskit.quantum_info import SparsePauliOp from qiskit_ibm_runtime import QiskitRuntimeService, Estimator service = QiskitRuntimeService(channel="ibm_cloud") psi1 = RealAmplitudes(num_qubits=2, reps=2) H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)]) H2 = SparsePauliOp.from_list([("IZ", 1)]) H3 = SparsePauliOp.from_list([("ZI", 1), ("ZZ", 1)]) with Session(service=service, backend="ibmq_qasm_simulator") as session: estimator = Estimator(session=session) theta1 = [0, 1, 1, 2, 3, 5] # calculate [ <psi1(theta1)|H1|psi1(theta1)> ] psi1_H1 = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta1]) print(psi1_H1.result()) # calculate [ <psi1(theta1)|H2|psi1(theta1)>, <psi1(theta1)|H3|psi1(theta1)> ] psi1_H23 = estimator.run( circuits=[psi1, psi1], observables=[H2, H3], parameter_values=[theta1]*2 ) print(psi1_H23.result())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) es_problem = driver.run() from qiskit_nature.second_q.mappers import JordanWignerMapper mapper = JordanWignerMapper() from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver numpy_solver = NumPyMinimumEigensolver() from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD ansatz = UCCSD( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, initial_state=HartreeFock( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, ), ) vqe_solver = VQE(Estimator(), ansatz, SLSQP()) vqe_solver.initial_point = [0.0] * ansatz.num_parameters from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.circuit.library import TwoLocal tl_circuit = TwoLocal( rotation_blocks=["h", "rx"], entanglement_blocks="cz", entanglement="full", reps=2, parameter_prefix="y", ) another_solver = VQE(Estimator(), tl_circuit, SLSQP()) from qiskit_nature.second_q.algorithms import GroundStateEigensolver calc = GroundStateEigensolver(mapper, vqe_solver) res = calc.solve(es_problem) print(res) calc = GroundStateEigensolver(mapper, numpy_solver) res = calc.solve(es_problem) print(res) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.mappers import DirectMapper from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis([2, 2, 2, 2]) vib_problem = driver.run(basis=basis) vib_problem.hamiltonian.truncation_order = 2 mapper = DirectMapper() solver_without_filter = NumPyMinimumEigensolver() solver_with_filter = NumPyMinimumEigensolver( filter_criterion=vib_problem.get_default_filter_criterion() ) gsc_wo = GroundStateEigensolver(mapper, solver_without_filter) result_wo = gsc_wo.solve(vib_problem) gsc_w = GroundStateEigensolver(mapper, solver_with_filter) result_w = gsc_w.solve(vib_problem) print(result_wo) print("\n\n") print(result_w) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/renatawong/classical-shadow-vqe
renatawong
# Installation of the requirements #!python -m pip install -r requirements.txt ''' (C) Renata Wong 2023 Qiskit code for testing fidelity of randomised classical shadow on the ground state energy of molecules. Procedure: 1. Choose a variational ansatz with initial parameters selected at random. 2. Generate a set of random basis change operators. 3. Apply the random operators to change bases in the ansatz. 4. Measure the ansatz in the Pauli Z basis and store the results as a shadow. 5. Obtain the expectation value of the molecular Hamiltonian from the shadow. 6. Optimize for minimum Hamiltonian expectation value. 7. Feed the calculated angles/parameters back to the ansatz. 8. Repeat steps 3-7 till the optimization is completed. 9. Output the minimized expectation value of the molecular Hamiltonian and the mean-square-root-error. Note: Below we perform calculations on the molecular Hamiltonian of H_2. To perform calculations on other molecules, you will need to specify their geometry, charge and spin to replace the values in the driver. Note: predicting_quantum_properties module comes from https://github.com/hsinyuan-huang/predicting-quantum-properties ''' from qiskit import QuantumCircuit, execute from qiskit_aer import QasmSimulator from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.mappers import BravyiKitaevMapper from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit.circuit.library import EfficientSU2 from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA import time import numpy as np from functools import partial import matplotlib.pyplot as plt from collections import Counter from predicting_quantum_properties.data_acquisition_shadow import randomized_classical_shadow from predicting_quantum_properties.prediction_shadow import estimate_exp # handle deprecation issues import qiskit_nature qiskit_nature.settings.use_pauli_sum_op = False import h5py H5PY_DEFAULT_READONLY=1 # classically obtained ground state energy EXPECTED_EIGENVALUE = -1.86 # specifying the geometry of the molecule in question driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() hamiltonian = problem.hamiltonian # electronic Hamiltonian of the system second_q_op = hamiltonian.second_q_op() # The Bravyi-Kitaev repserentation of the Fermionic Hamiltonian mapper = BravyiKitaevMapper() bkencoded_hamiltonian = mapper.map(second_q_op) print(bkencoded_hamiltonian) def process_hamiltonian(hamiltonian, derandomize = False): hamiltonian_observables = [] hamiltonian_coefficients = [] for observable in hamiltonian.paulis: op_list = [] for op_index, pauli_op in enumerate(observable): pauli_op = str(pauli_op) if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z': op_list.append((pauli_op, op_index)) hamiltonian_observables.append(op_list) hamiltonian_coefficients = hamiltonian.coeffs.real system_size = len(hamiltonian_observables[0]) # removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left # these observables are needed for estimate_exp() observables_xyze = [] for observable in hamiltonian_observables: XYZE = [] for pauli in observable: if pauli[0] != 'I': XYZE.append(pauli) observables_xyze.append(XYZE) # derandomisation procedure requires that coefficients are non-negative if derandomize == True: absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients] # removing the empty list as well # these observables are needed for derandomisation procedure observables_xyz = [] for idx, observable in enumerate(observables_xyze): if observable: observables_xyz.append(observable) else: absolute_coefficients.pop(idx) return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients return system_size, observables_xyze, hamiltonian_coefficients # process the Hamiltonian to obtain properly formatted data hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = False) system_size, observables_xyze, hamiltonian_coefficients = hamiltonian_data #print('HAMILTONIAN\n', observables_xyze) ''' VARIATIONAL ANSATZ Note that for molecules other than H_2 you may need to specify a different number of reps. ''' reps = 1 ansatz = EfficientSU2(system_size, su2_gates=['rx', 'ry'], entanglement='circular', reps=reps, skip_final_rotation_layer=False) ansatz.decompose().draw('mpl') ''' COST FUNCTION ''' def basis_change_circuit(pauli_op): # Generating circuit with just the basis change operators # # pauli_op: n-qubit Pauli operator basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits) for idx, op in enumerate(pauli_op): if op == 'X': basis_change.h(idx) elif op == 'Y': basis_change.h(idx) basis_change.p(-np.pi/2, idx) return basis_change def min_cost(): return min(cost_history) def log_cost(cost): global cost_history cost_history.append(cost) def objective_function(operators, params): backend = QasmSimulator(method='statevector', shots=1) pauli_op_dict = Counter(tuple(x) for x in operators) shadow = [] for pauli_op in pauli_op_dict: qc = ansatz.bind_parameters(params) qc = qc.compose(basis_change_circuit(pauli_op)) qc.measure(reversed(range(system_size)), range(system_size)) result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result() counts = result.get_counts() # generate a separate circuit for each basis change Pauli operator output_str = list(list(counts.keys())[list(counts.values()).index(1)]) output = [int(i) for i in output_str] eigenvals = [x+1 if x == 0 else x-2 for x in output] snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)] shadow.append(snapshot) cost = 0.0 for term, weight in zip(observables_xyze, hamiltonian_coefficients): sum_product, match_count = estimate_exp(shadow, term) if match_count != 0: exp_val = sum_product / match_count cost += weight * exp_val log_cost(cost) return cost ''' RUNNING EXPERIMENTS ''' start_time = time.time() rmse_errors = [] print('NUMBER OF OPERATORS | RANDOMISED OPERATORS | AVERAGE RMSE ERROR\n') measurement_range = [50, 100, 200, 600, 1000, 1600] for num_operators in measurement_range: basis_change = randomized_classical_shadow(num_operators, system_size) tuples = (tuple(pauli) for pauli in basis_change) counts = Counter(tuples) optimizer = SPSA(maxiter=2000) cost_function = partial(objective_function, basis_change) expectation_values = [] num_experiments = 5 for iteration in range(num_experiments): cost_history = [] params = np.random.rand(ansatz.num_parameters) result = optimizer.minimize(fun=cost_function, x0=params) minimal_cost = min_cost() expectation_values.append(minimal_cost) print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, minimal_cost)) rmse_randomised_cs = np.sqrt(np.sum([(expectation_values[i] - EXPECTED_EIGENVALUE)**2 for i in range(num_experiments)])/num_experiments) rmse_errors.append(rmse_randomised_cs) print('{} | {} | {}'.format(num_operators, counts, rmse_randomised_cs)) elapsed_time = time.time() - start_time print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time))) points = measurement_range num_points = len(measurement_range) plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='SPSA(maxiter=2000)') plt.xlabel('Number of measurements') plt.ylabel('Average RMSE error') plt.legend(loc=1)
https://github.com/dkp-quantum/Tutorials
dkp-quantum
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import * from qiskit.visualization import * import numpy as np # Create a quantum register with 2 qubits q = QuantumRegister(2,'q') # Form a quantum circuit # Note that the circuit name is optional qc = QuantumCircuit(q,name="first_qc") # Display the quantum circuit qc.draw() # Add a Hadamard gate on qubit 0, putting this in superposition. qc.h(0) # Add a CX (CNOT) gate on control qubit 0 # and target qubit 1 to create an entangled state. qc.cx(0, 1) qc.draw() # Create a classical register with 2 bits c = ClassicalRegister(2,'c') meas = QuantumCircuit(q,c,name="first_m") meas.barrier(q) meas.measure(q, c) meas.draw() # Quantum circuits can be added with + operations # Add two pre-defined circuits qc_all=qc+meas qc_all.draw() # Draw the quantum circuit in a different (slightly better) format qc_all.draw(output='mpl') # Create the quantum circuit with the measurement in one go. qc_all = QuantumCircuit(q,c,name="2q_all") qc_all.h(0) qc_all.cx(0,1) qc_all.barrier() qc_all.measure(0,0) qc_all.measure(1,1) qc_all.draw(output='mpl') # Use Aer's qasm_simulator backend_q = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator. job_sim1 = execute(qc_all, backend_q, shots=4096) job_sim1.status() # Grab the results from the job. result_sim1 = job_sim1.result() result_sim1 result_sim1.get_counts(qc_all) plot_histogram(result_sim1.get_counts(qc_all)) # Use Aer's statevector_simulator backend_sv = Aer.get_backend('statevector_simulator') # Execute the circuit on the statevector simulator. # It is important to note that the measurement has been excluded job_sim2 = execute(qc, backend_sv) # Grab the results from the job. result_sim2 = job_sim2.result() # Output the entire result result_sim2 # See output state as a vector outputstate = result_sim2.get_statevector(qc, decimals=5) print(outputstate) # Visualize density matrix plot_state_city(outputstate) # Create the quantum circuit with the measurement in one go. qc_3 = QuantumCircuit(3,3,name="qc_bloch") qc_3.x(1) qc_3.h(2) qc_3.barrier() qc_3.draw(output='mpl') # Execute the circuit on the statevector simulator. # It is important to note that the measurement has been excluded job_sim_bloch = execute(qc_3, backend_sv) # Grab the results from the job. result_sim_bloch = job_sim_bloch.result() # See output state as a vector output_bloch = result_sim_bloch.get_statevector(qc_3, decimals=5) # Draw on the Bloch sphere plot_bloch_multivector(output_bloch) # Use Aer's unitary_simulator backend_u = Aer.get_backend('unitary_simulator') # Execute the circuit on the unitary simulator. job_usim = execute(qc, backend_u) # Grab the results from the job. result_usim = job_usim.result() result_usim # Output the unitary matrix unitary = result_usim.get_unitary(qc) print('%s\n' % unitary) # Create the quantum circuit with the measurement in one go. qc_ex1 = QuantumCircuit(q,c,name="ex1") # Put the first qubit in equal superposition qc_ex1.h(0) # Rest of the circuit qc_ex1.x(1) qc_ex1.cx(0,1) qc_ex1.barrier() qc_ex1.measure(0,0) qc_ex1.measure(1,1) qc_ex1.draw(output='mpl') # Execute the circuit on the qasm simulator. job_ex1 = execute(qc_ex1, backend_q, shots=4096) job_ex1.status() # Grab the results from the job. result_ex1 = job_ex1.result() result_ex1.get_counts(qc_ex1) plot_histogram(result_ex1.get_counts(qc_ex1)) # Or get the histogram in one go plot_histogram(job_ex1.result().get_counts(qc_ex1)) # Create a quantum register with 3 qubits q3 = QuantumRegister(3,'q') # Create a classical register with 3 qubits c3 = ClassicalRegister(3,'c') # Create the quantum circuit with the measurement in one go. qc_ex2 = QuantumCircuit(q3,c3,name="ex1") qc_ex2.ry(2*np.pi/3,0) qc_ex2.cx(0,1) qc_ex2.cx(1,2) qc_ex2.barrier() qc_ex2.measure(q3,c3) qc_ex2.draw(output='mpl') # Execute the circuit on the qasm simulator. job_ex2 = execute(qc_ex2, backend_q, shots=4096) # Grab the results from the job. result_ex2 = job_ex2.result() plot_histogram(result_ex2.get_counts(qc_ex2)) # Create a quantum register with 3 qubits q3 = QuantumRegister(3,'q') # Create a classical register with 3 qubits c3 = ClassicalRegister(3,'c') # Create the quantum circuit without a Toffoli gate qc_toff = QuantumCircuit(q3,c3,name="ex1") qc_toff.ry(2*np.pi/3,0) qc_toff.h(1) qc_toff.h(2) qc_toff.barrier() qc_toff.measure(q3,c3) qc_toff.draw(output='mpl') # Execute the circuit on the qasm simulator. job_toff = execute(qc_toff, backend_q, shots=4096) # Grab the results from the job. result_toff = job_toff.result() plot_histogram(result_toff.get_counts(qc_toff)) # Now, add a Toffoli gate qc_toff = QuantumCircuit(q3,c3,name="ex1") qc_toff.ry(2*np.pi/3,0) qc_toff.h(1) qc_toff.h(2) qc_toff.ccx(1,2,0) qc_toff.barrier() qc_toff.measure(q3,c3) qc_toff.draw(output='mpl') # Execute the circuit on the qasm simulator. job_toff = execute(qc_toff, backend_q, shots=4096) # Grab the results from the job. result_toff = job_toff.result() plot_histogram(result_toff.get_counts(qc_toff)) IBMQ.disable_account() provider = IBMQ.enable_account('IBM_TOKEN') # provider = IBMQ.get_provider(hub='ibm-q-research') provider.backends() from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor from qiskit.tools.visualization import plot_gate_map, plot_error_map # Retrieve IBM Quantum device information backend_overview() # Let's get two quantum devices as an example backend_qx2 = provider.get_backend('ibmqx2') backend_vigo = provider.get_backend('ibmq_vigo') backend_monitor(backend_qx2) plot_error_map(backend_qx2) backend_monitor(backend_vigo) plot_error_map(backend_vigo) ![sdc2](jupyter_img/superdensecoding2.png)# Create a 5-qubit GHZ state (i.e. (|00000> + |11111>)/sqrt(2)) q5 = QuantumRegister(5,'q') c5 = ClassicalRegister(5,'c') ghz5= QuantumCircuit(q5,c5) ghz5.h(0) for i in range(1,5): ghz5.cx(0,i) ghz5.barrier() ghz5.measure(q5,c5) ghz5.draw(output='mpl') # Run the 5-qubit GHZ experiment on a 5-qubit device (try vigo) job_exp1 = execute(ghz5, backend=backend_vigo, shots=4096) job_monitor(job_exp1) # Grab experimental results result_vigo = job_exp1.result() counts_vigo = result_vigo.get_counts(ghz5) # Let's also try the same experiment on the 14-qubit device. job_exp2 = execute(ghz5, backend=provider.get_backend('ibmq_16_melbourne'), shots=4096) job_monitor(job_exp2) # Grab experimental results result_mel = job_exp2.result() counts_mel = result_mel.get_counts(ghz5) # Now, compare to theory by running it on qasm_simulator job_qasm = execute(ghz5,backend=backend_q) result_qasm = job_qasm.result() counts_qasm = result_qasm.get_counts(ghz5) # Plot both experimental and ideal results plot_histogram([counts_qasm,counts_vigo,counts_mel], color=['black','green','blue'], legend=['QASM','Vigo','Melbourne'],figsize = [20,8])
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) ### replaced x gate ### qc.x(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### replaced x gate ### qc.x(1) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import execute from qiskit import BasicAer q = QuantumRegister(4) c = ClassicalRegister(4) backend = BasicAer.get_backend('qasm_simulator') training_set = [[0, 1], [0.78861006, 0.61489363]] labels = [0, 1] test_set = [[-0.549, 0.836], [0.053 , 0.999]] test_angles = [4.30417579487669/2, 3.0357101997648965/2] training_angle = 1.3245021469658966/4 def prepare_state(q, c, angles): ancilla_qubit = q[0] index_qubit = q[1] data_qubit = q[2] class_qubit = q[3] qc = QuantumCircuit(q, c) # Put the ancilla and the index qubits into uniform superposition qc.h(ancilla_qubit) qc.h(index_qubit) # Prepare the test vector qc.cx(ancilla_qubit, data_qubit) qc.u3(-angles[0], 0, 0, data_qubit) qc.cx(ancilla_qubit, data_qubit) qc.u3(angles[0], 0, 0, data_qubit) # Flip the ancilla qubit > this moves the input # vector to the |0> state of the ancilla qc.x(ancilla_qubit) qc.barrier() # Prepare the first training vector # [0,1] -> class 0 # We can prepare this with a Toffoli qc.ccx(ancilla_qubit, index_qubit, data_qubit) # Flip the index qubit > moves the first training vector to the # |0> state of the index qubit qc.x(index_qubit) qc.barrier() # Prepare the second training vector # [0.78861, 0.61489] -> class 1 qc.ccx(ancilla_qubit, index_qubit, data_qubit) qc.cx(index_qubit, data_qubit) qc.u3(angles[1], 0, 0, data_qubit) qc.cx(index_qubit, data_qubit) qc.u3(-angles[1], 0, 0, data_qubit) qc.ccx(ancilla_qubit, index_qubit, data_qubit) qc.cx(index_qubit, data_qubit) qc.u3(-angles[1], 0, 0, data_qubit) qc.cx(index_qubit, data_qubit) qc.u3(angles[1], 0, 0, data_qubit) qc.barrier() # Flip the class label for training vector #2 qc.cx(index_qubit, class_qubit) qc.barrier() return qc from qiskit.tools.visualization import circuit_drawer angles = [test_angles[0], training_angle] state_preparation_0 = prepare_state(q, c, angles) circuit_drawer(state_preparation_0) def interfere_data_and_test_instances(qc, q, c, angles): qc.h(q[0]) qc.barrier() qc.measure(q, c) return qc import matplotlib.pyplot as plt import numpy as np %matplotlib inline x = np.linspace(-2, 2, 100) plt.xlim(-2, 2) plt.ylim(0, 1.1) plt.plot(x, 1-x**2/4) def postselect(result_counts): total_samples = sum(result_counts.values()) # define lambda function that retrieves only results where the ancilla is in the |0> state post_select = lambda counts: [(state, occurences) for state, occurences in counts.items() if state[-1] == '0'] # perform the postselection postselection = dict(post_select(result_counts)) postselected_samples = sum(postselection.values()) print(f'Ancilla post-selection probability was found to be {postselected_samples/total_samples}') retrieve_class = lambda binary_class: [occurences for state, occurences in postselection.items() if state[0] == str(binary_class)] prob_class0 = sum(retrieve_class(0))/postselected_samples prob_class1 = sum(retrieve_class(1))/postselected_samples print('Probability for class 0 is', prob_class0) print('Probability for class 1 is', prob_class1) qc0 = interfere_data_and_test_instances(state_preparation_0, q, c, angles) job = execute(qc0, backend) result = job.result() postselect(result.get_counts(qc0)) angles = [test_angles[1], training_angle] state_preparation_1 = prepare_state(q, c, angles) qc1 = interfere_data_and_test_instances(state_preparation_1, q, c, angles) job = execute(qc1, backend) result = job.result() postselect(result.get_counts(qc1))
https://github.com/grossiM/Qiskit_workshop1019
grossiM
#initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.tools.visualization import plot_histogram def phase_oracle(circuit, register): circuit.cz(qr[2],qr[0]) circuit.cz(qr[2],qr[1]) def n_controlled_Z(circuit, controls, target): """Implement a Z gate with multiple controls""" if (len(controls) > 2): raise ValueError('The controlled Z with more than 2 controls is not implemented') elif (len(controls) == 1): circuit.h(target) circuit.cx(controls[0], target) circuit.h(target) elif (len(controls) == 2): circuit.h(target) circuit.ccx(controls[0], controls[1], target) circuit.h(target) def inversion_about_average(circuit, register, n, barriers): """Apply inversion about the average step of Grover's algorithm.""" circuit.h(register) circuit.x(register) if barriers: circuit.barrier() n_controlled_Z(circuit, [register[j] for j in range(n-1)], register[n-1]) if barriers: circuit.barrier() circuit.x(register) circuit.h(register) barriers = True qr = QuantumRegister(3) cr = ClassicalRegister(3) groverCircuit = QuantumCircuit(qr,cr) groverCircuit.h(qr) if barriers: groverCircuit.barrier() phase_oracle(groverCircuit, qr) if barriers: groverCircuit.barrier() inversion_about_average(groverCircuit, qr, 3, barriers) if barriers: groverCircuit.barrier() groverCircuit.measure(qr,cr) groverCircuit.draw(output="mpl") backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(groverCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits IBMQ.load_account() IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor shots = 1024 job = execute(groverCircuit, backend=backend, shots=shots) job_monitor(job, interval = 2) # Get the results from the computation results = job.result() answer = results.get_counts(groverCircuit) plot_histogram(answer) import qiskit qiskit.__qiskit_version__
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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
from qiskit import * from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector from qiskit.quantum_info import Statevector from qiskit.extensions import * from qiskit.quantum_info import random_unitary import matplotlib.pyplot as plt %matplotlib inline import numpy as np import math from math import pi, sqrt from scipy.special import rel_entr from random import seed from random import random import cmath import os from qiskit.circuit import Parameter import sys sys.path.append('../Pyfiles') from circuits import * #Possible Bin bins_list=[]; for i in range(76): bins_list.append((i)/75) #Center of the Bean bins_x=[] for i in range(75): bins_x.append(bins_list[1]+bins_list[i]) def P_harr(l,u,N): return (1-l)**(N-1)-(1-u)**(N-1) #Harr historgram P_harr_hist=[] for i in range(75): P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],16)) #Imaginary j=(-1)**(1/2) backend = Aer.get_backend('qasm_simulator') nshot=1000 nparam=2000 fidelity=[] for x in range(nparam): qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr) theta=[]; for y in range(80): theta.append(2*pi*random()) qc=circuit9(qc,qr,theta,3,1) qc.measure(qr[:],cr[:]) job = execute(qc, backend, shots=nshot) result = job.result() count =result.get_counts() if '0000' in count and '1' in count: ratio=count['0000']/nshot elif '0000' in count and '1' not in count: ratio=count['0000']/nshot else: ratio=0 fidelity.append(ratio) weights = np.ones_like(fidelity)/float(len(fidelity)) plt.hist(fidelity, bins=bins_list, weights=weights, range=[0, 1], label='Circuit 1') plt.plot(bins_x, P_harr_hist, label='Harr') plt.legend(loc='upper right') plt.show() # example of calculating the kl divergence (relative entropy) with scipy P_1_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0] kl_pq = rel_entr(P_1_hist, P_harr_hist) print('KL(P || Q): %.3f nats' % sum(kl_pq)) list_of_circuit = [circuit1,circuit2,circuit3,circuit4,circuit5,circuit6,circuit7,circuit8,circuit9,circuit10,circuit11,circuit12,circuit13,circuit14,circuit15,circuit16,circuit17,circuit18,circuit19] backend = Aer.get_backend('qasm_simulator') arr = [] for kk in range(19): arr.append([]) for lo in [1,2,3,4,5]: nshot=1000 nparam=2000 fidelity=[] for x in range(nparam): qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr) theta=[]; for y in range(500): theta.append(2*pi*random()) qc=list_of_circuit[kk](qc,qr,theta,lo,1) qc.measure(qr[:],cr[:]) job = execute(qc, backend, shots=nshot) result = job.result() count =result.get_counts() if '0000' in count and '1' in count: ratio=count['0000']/nshot elif '0000' in count and '1' not in count: ratio=count['0000']/nshot else: ratio=0 fidelity.append(ratio) weights = np.ones_like(fidelity)/float(len(fidelity)) # example of calculating the kl divergence (relative entropy) with scipy P_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0] kl_pq = rel_entr(P_hist, P_harr_hist) arr[kk].append(sum(kl_pq)) print(kk,'cir',lo,'lay') import sys import numpy numpy.set_printoptions(threshold=sys.maxsize) np.savetxt("express_nshot1000_nparam2000.txt",express) express import pandas as pd import matplotlib.pyplot as plt #loading dataset x = [i+1 for i in range(19)] y = [i[0] for i in arr] plt.plot(x, y, 'o', color='red', label='L=1'); x = [i+1 for i in range(19)] y = [i[1] for i in arr] plt.plot(x, y, 'o', color='blue', label='L=2'); x = [i+1 for i in range(19)] y = [i[2] for i in arr] plt.plot(x, y, 'o', color='black', label='L=3'); x = [i+1 for i in range(19)] y = [i[3] for i in arr] plt.plot(x, y, 'o', color='green', label='L=4'); x = [i+1 for i in range(19)] y = [i[3] for i in arr] plt.plot(x, y, 'o', color='purple', label='L=5'); plt.legend(loc='upper right') plt.yscale('log',base=10) plt.xlabel('Circuit ID') plt.ylabel('Expressibility') # Create names on the x axis plt.xticks([i+1 for i in range(19)]) plt.show() x = [str(i+1) for i in range(19)] x_ticks_labels = ['9','1','2','16','3','18','10','12','15','17','4','11','7','8','19','5','13','14','6'] xarr = np.array(x) ind = np.where(xarr.reshape(xarr.size, 1) == np.array(x_ticks_labels))[1] fig, ax = plt.subplots(1,1) y = [i[0] for i in arr] ax.scatter(ind,y, marker="o", color='red', label='L=1') y = [i[1] for i in arr] ax.scatter(ind,y, marker="o", color='blue', label='L=2') y = [i[2] for i in arr] ax.scatter(ind,y, marker="o", color='black', label='L=3') y = [i[3] for i in arr] ax.scatter(ind,y, marker="o", color='green', label='L=4') y = [i[4] for i in arr] ax.scatter(ind,y, marker="o", color='purple', label='L=5') ax.set_yscale('log',base=10) ax.set_xlabel('Circuit ID') ax.set_ylabel('Expressibility') ax.legend(loc='upper right') ax.set_xticks(range(len(x_ticks_labels))) ax.set_xticklabels(x_ticks_labels) plt.show() fig from matplotlib import pyplot as plt fig.savefig('express_nshot1000_nparam2000.png') list_of_circuit = [circuit1,circuit2,circuit3,circuit4,circuit5,circuit6,circuit7,circuit8,circuit9,circuit10,circuit11,circuit12,circuit13,circuit14,circuit15,circuit16,circuit17,circuit18,circuit19] backend = Aer.get_backend('qasm_simulator') arr = [] for kk in range(19): arr.append([]) for lo in [1,2,3,4,5]: nshot=10000 nparam=1000 fidelity=[] for x in range(nparam): qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr) theta=[]; for y in range(500): theta.append(2*pi*random()) qc=list_of_circuit[kk](qc,qr,theta,lo,1) qc.measure(qr[:],cr[:]) job = execute(qc, backend, shots=nshot) result = job.result() count =result.get_counts() if '0000' in count and '1' in count: ratio=count['0000']/nshot elif '0000' in count and '1' not in count: ratio=count['0000']/nshot else: ratio=0 fidelity.append(ratio) weights = np.ones_like(fidelity)/float(len(fidelity)) # example of calculating the kl divergence (relative entropy) with scipy P_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0] kl_pq = rel_entr(P_hist, P_harr_hist) arr[kk].append(sum(kl_pq)) print(kk,'cir',lo,'lay') express express=[[0.32952413239340933, 0.2160076560690873, 0.21764729834615873, 0.2473835588095912, 0.24225112795339898], [0.32696068662224353, 0.02882892743034554, 0.016267808316341933, 0.011239533562489743, 0.014454756871595335], [0.2724963267277256, 0.09297432646189611, 0.05316589878004338, 0.015713919742898073, 0.024985709696968308], [0.13368059415831227, 0.04064900653499141, 0.010705050297397748, 0.013853567790054458, 0.005871642903255154], [0.06736311068291166, 0.018156334236215592, 0.01063201904450228, 0.013316433532184285, 0.007592151156475834], [0.009458920213652083, 0.008379672440371308, 0.010342492342456355, 0.006491253689230598, 0.006360265144835441], [0.11252639719416441, 0.048734485611284246, 0.02917920621977864, 0.021220914498718095, 0.011322409296335365], [0.07799698630987113, 0.03461538963835257, 0.02645406983833787, 0.009609047546796293, 0.010314541867701806], [0.7416977310427298, 0.4023390066678401, 0.04364507668153466, 0.0120927672656568, 0.01312193911083145], [0.2568922048986469, 0.159877856023638, 0.14981483475374258, 0.11517099082521957, 0.14284391643493405], [0.15798258034579774, 0.015098001400060396, 0.011383645396280426, 0.010105335417854225, 0.005632643410627778], [0.19446925387256803, 0.031175656437504834, 0.02084429521271306, 0.01343313112097519, 0.00768059915246622], [0.09061768972578448, 0.011526900417017642, 0.008189880893093129, 0.0060108893015350506, 0.011751397567911099], [0.018799262840916854, 0.007136143406884642, 0.007623092145230341, 0.009053624288535378, 0.007663290417292582], [0.19746628980579164, 0.15281958598891646, 0.1355063400118548, 0.15111662634669093, 0.11741954724324753], [0.2684937151020319, 0.09697128618178347, 0.05370640870529413, 0.032238736633842385, 0.023082433062011888], [0.14026071817411356, 0.047939490546422714, 0.021117783500337883, 0.015818882293649358, 0.008967458429476547], [0.21391972052843847, 0.07307155307919132, 0.02627846142683268, 0.020869197694583997, 0.010954254599580318], [0.07137805144811141, 0.01173518527289049, 0.014645535174778783, 0.008417810099715662, 0.006455244968957593]] import sys import numpy numpy.set_printoptions(threshold=sys.maxsize) np.savetxt("express_nshot10000_nparam1000.txt",express) x = [str(i+1) for i in range(19)] x_ticks_labels = ['9','1','2','16','3','18','10','12','15','17','4','11','7','8','19','5','13','14','6'] xarr = np.array(x) ind = np.where(xarr.reshape(xarr.size, 1) == np.array(x_ticks_labels))[1] fig, ax = plt.subplots(1,1) y = [i[0] for i in arr] ax.scatter(ind,y, marker="o", color='red', label='L=1') y = [i[1] for i in arr] ax.scatter(ind,y, marker="o", color='blue', label='L=2') y = [i[2] for i in arr] ax.scatter(ind,y, marker="o", color='black', label='L=3') y = [i[3] for i in arr] ax.scatter(ind,y, marker="o", color='green', label='L=4') y = [i[4] for i in arr] ax.scatter(ind,y, marker="o", color='purple', label='L=5') ax.set_yscale('log',base=10) ax.set_xlabel('Circuit ID') ax.set_ylabel('Expressibility') ax.legend(loc='upper right') ax.set_xticks(range(len(x_ticks_labels))) ax.set_xticklabels(x_ticks_labels) plt.show() plt.plot(express[12], marker="o") plt.ylim(0,0.1) plt.plot(express[14], marker="o") plt.ylim(0,0.21) from matplotlib import pyplot as plt fig.savefig('express_nshot10000_nparam1000.png')
https://github.com/Advanced-Research-Centre/QPULBA
Advanced-Research-Centre
from qiskit import QuantumCircuit import numpy as np import random from qiskit import Aer, execute qubits = 17 circ = QuantumCircuit(qubits) simulator = Aer.get_backend('statevector_simulator') def display(circ): sim_res = execute(circ, simulator).result() statevector = sim_res.get_statevector(circ) print("============ State Vector ============") for i in statevector: print(i) print("============..............============") # initialize for q in range(0,qubits): ang = np.pi * random.random() circ.ry(ang,q) display(circ)
https://github.com/pedroripper/qiskit_tutoriais
pedroripper
from qiskit import * %matplotlib inline # Para facilitar a visualização dos nossos circuitos podemos usar .barrier() para criar # "separadores" nos circuitos # Essas barras tem uma outra função que pode ser vista no futuro, mas por enquanto podemos # usar apenas para separar partes do circuito qc = QuantumCircuit(2,2) qc.x(0) qc.y(0) qc.z(0) qc.x(1) qc.y(0) qc.z(1) qc.draw(output='mpl') # Agora vamos separar essa parte qc.barrier() qc.draw(output='mpl') # Com isso podemos continuar a segunda parte do circuito qc.x(0) qc.y(0) qc.z(0) qc.x(1) qc.y(0) qc.z(1) qc.draw(output='mpl')
https://github.com/drnickallgood/simonqiskit
drnickallgood
import sys import logging import matplotlib.pyplot as plt import numpy as np import operator import itertools #from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, IBMQ from qiskit.providers.ibmq import least_busy from collections import OrderedDict # AER is for simulators from qiskit import Aer from qiskit import QuantumCircuit from qiskit import ClassicalRegister from qiskit import QuantumRegister from qiskit import execute from qiskit import IBMQ #from qiskit.providers.ibmq.managed import IBMQJobManager from qiskit.tools.monitor import job_monitor from qiskit.tools.visualization import plot_histogram from qiskit.tools.visualization import circuit_drawer from sympy import Matrix, pprint, MatrixSymbol, expand, mod_inverse unitary_sim = Aer.get_backend('unitary_simulator') n = 2 # Generate circuit #qr = QuantumRegister(2*n,'q') qr = QuantumRegister(2*n) #cr = ClassicalRegister(n,'c') cr = ClassicalRegister(n) simonCircuit = QuantumCircuit(qr,cr) uni_list = list() def example(): result2 = execute(simonCircuita, unitary_sim).result() unitary2 = result2.get_unitary(simonCircuita) if np.all((unitary2 == x) for x in uni_list): print("Duplicate") else: print("No duplicate") uni_list.append(unitary2) simonCircuit.h(qr[0]) simonCircuit.h(qr[1]) simonCircuit.cx(qr[0],qr[2]) simonCircuit.x(qr[3]) result1 = execute(simonCircuit, unitary_sim).result() unitary1 = result1.get_unitary(simonCircuit) uni_list.append(unitary1) print(len(uni_list)) # Generate circuit #qra = QuantumRegister(2*n,'q') qra = QuantumRegister(2*n) #cra = ClassicalRegister(n,'c') cra = ClassicalRegister(n) simonCircuita = QuantumCircuit(qra,cra) simonCircuita.h(qra[0]) simonCircuita.h(qra[1]) example() print(len(uni_list))
https://github.com/psasanka1729/nisq-grover-qiskit-floquet-model
psasanka1729
import sys from qiskit import* #from qiskit import Aer import qiskit.quantum_info as qi import numpy as np #from math import pi #import matplotlib.pyplot as plt import re L = 4; qc = QuantumCircuit(L) qc.mcx([i for i in range(L-1)],L-1) qc.draw("mpl",style="clifford") trans_qc = transpile(qc, basis_gates = ['u1','rx','cx'], optimization_level = 3) #trans_qc = transpile(qc, basis_gates = ['rz','cx','h'], optimization_level = 3) #trans_qc.draw("mpl") trans_qc.draw("mpl") #len(trans_qc) def extract_gate_details(gate_index, gate_instruction_string): gate_string = str(gate_instruction_string[gate_index]) gate_as_list = [] # u1 gate. if "u1" in gate_string: # Extract the number using a more specific pattern number_match = re.search(r"params=\[([-\d.]+)\]", gate_string) angle = number_match.group(1) # '0.09817477042468103' # Extract the qubit index using a tailored pattern qubit_index_match = re.search(r"Qubit\(.*?, (\d+)\)", gate_string) qubit_acted_on = qubit_index_match.group(1) # '4' gate_as_list.append(["u1",angle,qubit_acted_on]) # rz gate. elif "rz" in gate_string: # Extract the number using a more specific pattern number_match = re.search(r"params=\[([-\d.]+)\]", gate_string) angle = number_match.group(1) # '0.09817477042468103' # Extract the qubit index using a tailored pattern qubit_index_match = re.search(r"Qubit\(.*?, (\d+)\)", gate_string) qubit_acted_on = qubit_index_match.group(1) # '4' gate_as_list.append(["rz",angle,qubit_acted_on]) # rx gate. elif "rx" in gate_string: # Extract the number using a more specific pattern number_match = re.search(r"params=\[([-\d.]+)\]", gate_string) angle = number_match.group(1) # '0.09817477042468103' # Extract the qubit index using a tailored pattern qubit_index_match = re.search(r"Qubit\(.*?, (\d+)\)", gate_string) qubit_acted_on = qubit_index_match.group(1) # '4' gate_as_list.append(["rx",angle,qubit_acted_on]) # controlled gate. elif "cx" in gate_string: match = re.search(r"(\d+)(?=\), Qubit\(QuantumRegister)", gate_string) if match: control_qubit = int(match.group()) match = re.search(r"(\d+)(?=\)\), clbits=\(\))", gate_string) if match: target_qubit = int(match.group()) gate_as_list.append(["cx",control_qubit,target_qubit]) # hadamard gate. elif "h" in gate_string: match = re.search(r"(\d+)(?=\),\), clbits=\(\))", string) if match: qubit_acted_on = int(match.group(1)) gate_as_list.append(["h", qubit_acted_on, qubit_acted_on ]) else: print("Kant") return gate_as_list trans_qc[2] trans_qc[5] # search for qubits string = str(trans_qc[0]) match = re.search(r"(\d+)(?=\),\), clbits=\(\))", string) int(match.group(1)) file = open('gates_list_'+str(L)+'.txt', 'w') # U_0. for i in range(L): # gate qubit qubt. file.write("x" + "\t" + str(i) + "\t" + str(i) + "\n") file.write("h" + "\t" + str(L-1) + "\t" + str(L-1) + "\n") for i in range(len(trans_qc)): print(i) gate_as_list = extract_gate_details(i,trans_qc)[0] print(gate_as_list) file.write(gate_as_list[0] + "\t" + str(gate_as_list[1]) + "\t" + str(gate_as_list[2]) + "\n") file.write("h" + "\t" + str(L-1) + "\t" + str(L-1) + "\n") for i in range(L): # gate qubit qubt. file.write("x" + "\t" + str(i) + "\t" + str(i) + "\n") # U_x. for i in range(L-1): file.write("h" + "\t" + str(i) + "\t" + str(i) + "\n") for i in range(L-1): file.write("x" + "\t" + str(i) + "\t" + str(i) + "\n") file.write("z" + "\t" + str(L-1) + "\t" + str(L-1) + "\n") for i in range(len(trans_qc)): gate_as_list = extract_gate_details(i,trans_qc)[0] file.write(gate_as_list[0] + "\t" + str(gate_as_list[1]) + "\t" + str(gate_as_list[2]) + "\n") file.write("z" + "\t" + str(L-1) + "\t" + str(L-1) + "\n") for i in range(L-1): file.write("x" + "\t" + str(i) + "\t" + str(i) + "\n") for i in range(L-1): file.write("h" + "\t" + str(i) + "\t" + str(i) + "\n") file.close()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] for _ in range(100): depths.append( transpile( ghz, backend, layout_method='trivial' # Fixed layout mapped in circuit order ).depth() ) plt.figure(figsize=(8, 6)) plt.hist(depths, align='left', color='#AC557C') plt.xlabel('Depth', fontsize=14) plt.ylabel('Counts', fontsize=14);
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### replaced x gate ### qc.x(1) return qc