repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
DRA-chaos
!pip install qiskit # check if CUDA is available import torch train_on_gpu = torch.cuda.is_available() if not train_on_gpu: print('CUDA is not available. Training on CPU ...') else: print('CUDA is available! Training on GPU ...') import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import qiskit from qiskit import transpile, assemble from qiskit.visualization import * import numpy as np import torch from torch.autograd import Function import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute from qiskit.circuit import Parameter from qiskit import Aer from tqdm import tqdm from matplotlib import pyplot as plt %matplotlib inline def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QuantumCircuit: """ This class provides a simple interface for interaction with the quantum circuit """ def __init__(self, n_qubits, backend, shots): # --- Circuit definition --- self._circuit = qiskit.QuantumCircuit(n_qubits) all_qubits = [i for i in range(n_qubits)] self.theta = qiskit.circuit.Parameter('theta') self._circuit.h(all_qubits) self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() # --------------------------- self.backend = backend self.shots = shots def run(self, thetas): t_qc = transpile(self._circuit, self.backend) qobj = assemble(t_qc, shots=self.shots, parameter_binds = [{self.theta: theta} for theta in thetas]) job = self.backend.run(qobj) result = job.result().get_counts() counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probabilities for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation]) class HybridFunction(Function): """ Hybrid quantum - classical function definition """ @staticmethod def forward(ctx, input, quantum_circuit, shift): """ Forward pass computation """ ctx.shift = shift ctx.quantum_circuit = quantum_circuit expectation_z = ctx.quantum_circuit.run(input[0].tolist()) result = torch.tensor([expectation_z]) ctx.save_for_backward(input, result) return result @staticmethod def backward(ctx, grad_output): """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None class Hybrid(nn.Module): """ Hybrid quantum - classical layer definition """ def __init__(self, backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(1, backend, shots) self.shift = shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) len(cifar_trainset) from torch.utils.data import DataLoader, random_split #cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) labels = cifar_trainset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_trainset.targets = labels[idx] cifar_trainset.data = cifar_trainset.data[idx] cifar_trainset, valid = random_split(cifar_trainset,[150,50]) train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid, batch_size=1, shuffle=True) @torch.no_grad() def get_all_preds(model, train_loader): all_preds = torch.tensor([]) for batch in train_loader: images, labels = batch preds = model(images) all_preds = torch.cat( (all_preds, preds) ,dim=0 ) return all_preds import numpy as np import matplotlib.pyplot as plt n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 2)) while n_samples_show > 0: images, targets = data_iter.__next__() images=images.squeeze() axes[n_samples_show - 1].imshow(images[0].numpy(), cmap='gray') axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform) labels = cifar_testset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_testset.targets = labels[idx] cifar_testset.data = cifar_testset.data[idx] test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=False) len(cifar_testset) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(500, 500) self.fc2 = nn.Linear(500, 1) self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(1, -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.hybrid(x) return torch.cat((x, 1 - x), -1) %matplotlib inline import matplotlib.pyplot as plt model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model.eval() with torch.no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model(data) pred = output.argmax(dim=1, keepdim=True) data=data.squeeze() axes[count].imshow(data[0].numpy().squeeze(), cmap='gray') axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title('Predicted {}'.format(pred.item())) count += 1 model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 10 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 7 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 8 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 9 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 6 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0004) loss_func = nn.NLLLoss() epochs = 6 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0003) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 7 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.SGD(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 10 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 15 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.01) loss_func = nn.NLLLoss() epochs = 15 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 15 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 10 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 3 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 7 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 10 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 15 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0008) loss_func = nn.NLLLoss() epochs = 3 loss_list = [] loss_list_V = [] #training the model model.train() for epoch in range(epochs): train_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() train_loss.append(loss.item()) loss_list.append(sum(train_loss)/len(train_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Validate the model model.eval() for epoch in range(epochs): valid_loss = [] for batch_idx, (data, target) in enumerate(valid_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss validation_loss = loss_func(output, target) # Backward pass validation_loss.backward() # Optimize the weights optimizer.step() valid_loss.append(validation_loss.item()) loss_list_V.append(sum(valid_loss)/len(valid_loss)) #print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1])) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, loss_list[-1], loss_list_V[-1])) #Now plotting the training graph plt.plot(loss_list,label='Training Loss') plt.plot(loss_list_V,label='Validation Loss') plt.legend() plt.show() total_loss=[] model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) )
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. from typing import Optional, Tuple, List, Union from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit import Gate, Instruction, Qubit, InstructionSet from qiskit.extensions import XGate, CU1Gate from dc_qiskit_algorithms.Qft import QuantumFourierTransformGate from . import Qft as qft class DraperAdderGate(Gate): def __init__(self, input_a, input_b, length=None): """ The Draper adder (arXiv:quant-ph/0008033), provide a and b and make sure to define a size of a register that can hold a or b :param input_a: integer a :param input_b: integer b :param length: size of qubit registers :return: tuple of the circuit and the length of the register """ a_01s = "{0:b}".format(input_a) b_01s = "{0:b}".format(input_b) length = DraperAdderGate.compute_length(input_a, input_b, length) a_01s = a_01s.zfill(length) b_01s = b_01s.zfill(length) super().__init__("add_draper", num_qubits=2*length, params=[input_a, input_b]) self.a_01s = a_01s self.b_01s = b_01s def _define(self): q = QuantumRegister(len(self.a_01s) + len(self.b_01s), "q") qc = QuantumCircuit(q, name=self.name) a = q[0:len(self.a_01s)] b = q[len(self.a_01s):] for i, c in enumerate(self.a_01s): if c == '1': qc.append(XGate(), [a[i]], []) for i, c in enumerate(self.b_01s): if c == '1': qc.append(XGate(), [b[i]], []) qc.append(QuantumFourierTransformGate(len(a)), a, []) for b_index in reversed(range(len(b))): theta_index = 1 for a_index in reversed(range(b_index + 1)): qc.append(CU1Gate(qft.get_theta(theta_index)), [b[b_index], a[a_index]], []) theta_index += 1 qc.append(QuantumFourierTransformGate(len(a)).inverse(), a, []) self.definition = qc def inverse(self): return super().inverse() @staticmethod def compute_length(input_a, input_b, length=None): a_01s = "{0:b}".format(input_a) b_01s = "{0:b}".format(input_b) length = max(len(a_01s), len(b_01s), length if length is not None else 0) return length def add_draper(self, input_a, input_b, qubits, length=None): # type: (QuantumCircuit, int, int, Union[QuantumRegister, List[Qubit]], Optional[int]) -> InstructionSet if isinstance(qubits, QuantumRegister): qubits = list(qubits) return self.append(DraperAdderGate(input_a, input_b, length), qubits, []) QuantumCircuit.add_draper = add_draper
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. # pylint: disable=invalid-name """Test QuantumCircuit.compose().""" import unittest import numpy as np from qiskit import transpile from qiskit.pulse import Schedule from qiskit.circuit import ( QuantumRegister, ClassicalRegister, Clbit, QuantumCircuit, Qubit, Parameter, Gate, Instruction, CASE_DEFAULT, SwitchCaseOp, ) from qiskit.circuit.library import HGate, RZGate, CXGate, CCXGate, TwoLocal from qiskit.circuit.classical import expr from qiskit.test import QiskitTestCase class TestCircuitCompose(QiskitTestCase): """Test composition of two circuits.""" def setUp(self): super().setUp() qreg1 = QuantumRegister(3, "lqr_1") qreg2 = QuantumRegister(2, "lqr_2") creg = ClassicalRegister(2, "lcr") self.circuit_left = QuantumCircuit(qreg1, qreg2, creg) self.circuit_left.h(qreg1[0]) self.circuit_left.x(qreg1[1]) self.circuit_left.p(0.1, qreg1[2]) self.circuit_left.cx(qreg2[0], qreg2[1]) self.left_qubit0 = qreg1[0] self.left_qubit1 = qreg1[1] self.left_qubit2 = qreg1[2] self.left_qubit3 = qreg2[0] self.left_qubit4 = qreg2[1] self.left_clbit0 = creg[0] self.left_clbit1 = creg[1] self.condition = (creg, 3) def test_compose_inorder(self): """Composing two circuits of the same width, default order. ┌───┐ lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>──┤ X ├─── rqr_1: |0>──┼──┤ X ├ ┌─┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ P(0.1) ├ + rqr_2: |0>──┼──┤ Y ├ = └────────┘ ┌─┴─┐└───┘ lqr_2_0: |0>────■───── rqr_3: |0>┤ X ├───── ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>──┤ X ├─── rqr_4: |0>─────┤ Z ├ └───┘ └───┘ lcr_0: 0 ═══════════ lcr_1: 0 ═══════════ ┌───┐ lqr_1_0: |0>──┤ H ├─────■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>──┤ X ├─────┼──┤ X ├ ┌─┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ P(0.1) ├──┼──┤ Y ├ └────────┘┌─┴─┐└───┘ lqr_2_0: |0>────■─────┤ X ├───── ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>──┤ X ├────────┤ Z ├ └───┘ └───┘ lcr_0: 0 ═══════════════════════ lcr_1: 0 ═══════════════════════ """ qreg = QuantumRegister(5, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit3) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.z(self.left_qubit4) circuit_composed = self.circuit_left.compose(circuit_right, inplace=False) self.assertEqual(circuit_composed, circuit_expected) def test_compose_inorder_unusual_types(self): """Test that composition works in order, using Numpy integer types as well as regular integer types. In general, it should be permissible to use any of the same `QubitSpecifier` types (or similar for `Clbit`) that `QuantumCircuit.append` uses.""" qreg = QuantumRegister(5, "rqr") creg = ClassicalRegister(2, "rcr") circuit_right = QuantumCircuit(qreg, creg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_right.measure([0, 1], [0, 1]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit3) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.z(self.left_qubit4) circuit_expected.measure(self.left_qubit0, self.left_clbit0) circuit_expected.measure(self.left_qubit1, self.left_clbit1) circuit_composed = self.circuit_left.compose(circuit_right, np.arange(5), slice(0, 2)) self.assertEqual(circuit_composed, circuit_expected) def test_compose_inorder_inplace(self): """Composing two circuits of the same width, default order, inplace. ┌───┐ lqr_1_0: |0>───┤ H ├─── rqr_0: |0>──■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>───┤ X ├─── rqr_1: |0>──┼──┤ X ├ ┌──┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ U1(0.1) ├ + rqr_2: |0>──┼──┤ Y ├ = └─────────┘ ┌─┴─┐└───┘ lqr_2_0: |0>─────■───── rqr_3: |0>┤ X ├───── ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>───┤ X ├─── rqr_4: |0>─────┤ Z ├ └───┘ └───┘ lcr_0: 0 ═══════════ lcr_1: 0 ═══════════ ┌───┐ lqr_1_0: |0>───┤ H ├─────■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>───┤ X ├─────┼──┤ X ├ ┌──┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ U1(0.1) ├──┼──┤ Y ├ └─────────┘┌─┴─┐└───┘ lqr_2_0: |0>─────■─────┤ X ├───── ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>───┤ X ├────────┤ Z ├ └───┘ └───┘ lcr_0: 0 ════════════════════════ lcr_1: 0 ════════════════════════ """ qreg = QuantumRegister(5, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit3) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.z(self.left_qubit4) # inplace circuit_left = self.circuit_left.copy() circuit_left.compose(circuit_right, inplace=True) self.assertEqual(circuit_left, circuit_expected) def test_compose_inorder_smaller(self): """Composing with a smaller RHS dag, default order. ┌───┐ ┌─────┐ lqr_1_0: |0>───┤ H ├─── rqr_0: |0>──■──┤ Tdg ├ ├───┤ ┌─┴─┐└─────┘ lqr_1_1: |0>───┤ X ├─── rqr_1: |0>┤ X ├─────── ┌──┴───┴──┐ └───┘ lqr_1_2: |0>┤ U1(0.1) ├ + = └─────────┘ lqr_2_0: |0>─────■───── ┌─┴─┐ lqr_2_1: |0>───┤ X ├─── └───┘ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ ┌───┐ ┌─────┐ lqr_1_0: |0>───┤ H ├─────■──┤ Tdg ├ ├───┤ ┌─┴─┐└─────┘ lqr_1_1: |0>───┤ X ├───┤ X ├─────── ┌──┴───┴──┐└───┘ lqr_1_2: |0>┤ U1(0.1) ├──────────── └─────────┘ lqr_2_0: |0>─────■───────────────── ┌─┴─┐ lqr_2_1: |0>───┤ X ├─────────────── └───┘ lcr_0: 0 ══════════════════════════ lcr_1: 0 ══════════════════════════ """ qreg = QuantumRegister(2, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[1]) circuit_right.tdg(qreg[0]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit1) circuit_expected.tdg(self.left_qubit0) circuit_composed = self.circuit_left.compose(circuit_right) self.assertEqual(circuit_composed, circuit_expected) def test_compose_permuted(self): """Composing two dags of the same width, permuted wires. ┌───┐ lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>──┤ X ├─── rqr_1: |0>──┼──┤ X ├ ┌─┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ P(0.1) ├ rqr_2: |0>──┼──┤ Y ├ └────────┘ ┌─┴─┐└───┘ lqr_2_0: |0>────■───── + rqr_3: |0>┤ X ├───── = ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>──┤ X ├─── rqr_4: |0>─────┤ Z ├ └───┘ └───┘ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ ┌───┐ ┌───┐ lqr_1_0: |0>──┤ H ├───┤ Z ├ ├───┤ ├───┤ lqr_1_1: |0>──┤ X ├───┤ X ├ ┌─┴───┴──┐├───┤ lqr_1_2: |0>┤ P(0.1) ├┤ Y ├ └────────┘└───┘ lqr_2_0: |0>────■───────■── ┌─┴─┐ ┌─┴─┐ lqr_2_1: |0>──┤ X ├───┤ X ├ └───┘ └───┘ lcr_0: 0 ══════════════════ lcr_1: 0 ══════════════════ """ qreg = QuantumRegister(5, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_expected = self.circuit_left.copy() circuit_expected.z(self.left_qubit0) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.cx(self.left_qubit3, self.left_qubit4) # permuted wiring circuit_composed = self.circuit_left.compose( circuit_right, qubits=[ self.left_qubit3, self.left_qubit1, self.left_qubit2, self.left_qubit4, self.left_qubit0, ], inplace=False, ) self.assertEqual(circuit_composed, circuit_expected) def test_compose_permuted_smaller(self): """Composing with a smaller RHS dag, and permuted wires. Compose using indices. ┌───┐ ┌─────┐ lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├ ├───┤ ┌─┴─┐└─────┘ lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├─────── ┌─┴───┴──┐ └───┘ lqr_1_2: |0>┤ P(0.1) ├ + = └────────┘ lqr_2_0: |0>────■───── ┌─┴─┐ lqr_2_1: |0>──┤ X ├─── └───┘ lcr_0: 0 ═════════════ lcr_1: 0 ═════════════ ┌───┐ lqr_1_0: |0>──┤ H ├─────────────── ├───┤ lqr_1_1: |0>──┤ X ├─────────────── ┌─┴───┴──┐┌───┐ lqr_1_2: |0>┤ P(0.1) ├┤ X ├─────── └────────┘└─┬─┘┌─────┐ lqr_2_0: |0>────■───────■──┤ Tdg ├ ┌─┴─┐ └─────┘ lqr_2_1: |0>──┤ X ├─────────────── └───┘ lcr_0: 0 ═════════════════════════ lcr_1: 0 ═════════════════════════ """ qreg = QuantumRegister(2, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[1]) circuit_right.tdg(qreg[0]) # permuted wiring of subset circuit_composed = self.circuit_left.compose(circuit_right, qubits=[3, 2]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit3, self.left_qubit2) circuit_expected.tdg(self.left_qubit3) self.assertEqual(circuit_composed, circuit_expected) def test_compose_classical(self): """Composing on classical bits. ┌───┐ ┌─────┐┌─┐ lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├┤M├ ├───┤ ┌─┴─┐└─┬─┬─┘└╥┘ lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├──┤M├───╫─ ┌─┴───┴──┐ └───┘ └╥┘ ║ lqr_1_2: |0>┤ P(0.1) ├ + rcr_0: 0 ════════╬════╩═ = └────────┘ ║ lqr_2_0: |0>────■───── rcr_1: 0 ════════╩══════ ┌─┴─┐ lqr_2_1: |0>──┤ X ├─── └───┘ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ ┌───┐ lqr_1_0: |0>──┤ H ├────────────────── ├───┤ ┌─────┐┌─┐ lqr_1_1: |0>──┤ X ├─────■──┤ Tdg ├┤M├ ┌─┴───┴──┐ │ └─────┘└╥┘ lqr_1_2: |0>┤ P(0.1) ├──┼──────────╫─ └────────┘ │ ║ lqr_2_0: |0>────■───────┼──────────╫─ ┌─┴─┐ ┌─┴─┐ ┌─┐ ║ lqr_2_1: |0>──┤ X ├───┤ X ├──┤M├───╫─ └───┘ └───┘ └╥┘ ║ lcr_0: 0 ══════════════════╩════╬═ ║ lcr_1: 0 ═══════════════════════╩═ """ qreg = QuantumRegister(2, "rqr") creg = ClassicalRegister(2, "rcr") circuit_right = QuantumCircuit(qreg, creg) circuit_right.cx(qreg[0], qreg[1]) circuit_right.tdg(qreg[0]) circuit_right.measure(qreg, creg) # permuted subset of qubits and clbits circuit_composed = self.circuit_left.compose(circuit_right, qubits=[1, 4], clbits=[1, 0]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit1, self.left_qubit4) circuit_expected.tdg(self.left_qubit1) circuit_expected.measure(self.left_qubit4, self.left_clbit0) circuit_expected.measure(self.left_qubit1, self.left_clbit1) self.assertEqual(circuit_composed, circuit_expected) def test_compose_conditional(self): """Composing on classical bits. ┌───┐ ┌───┐ ┌─┐ lqr_1_0: |0>──┤ H ├─── rqr_0: ────────┤ H ├─┤M├─── ├───┤ ┌───┐ └─┬─┘ └╥┘┌─┐ lqr_1_1: |0>──┤ X ├─── rqr_1: ─┤ X ├────┼────╫─┤M├ ┌─┴───┴──┐ └─┬─┘ │ ║ └╥┘ lqr_1_2: |0>┤ P(0.1) ├ + ┌──┴──┐┌──┴──┐ ║ ║ └────────┘ rcr_0: ╡ ╞╡ ╞═╩══╬═ lqr_2_0: |0>────■───── │ = 3 ││ = 3 │ ║ ┌─┴─┐ rcr_1: ╡ ╞╡ ╞════╩═ lqr_2_1: |0>──┤ X ├─── └─────┘└─────┘ └───┘ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ ┌───┐ lqr_1_0: ──┤ H ├─────────────────────── ├───┤ ┌───┐ ┌─┐ lqr_1_1: ──┤ X ├───────────┤ H ├────┤M├ ┌─┴───┴──┐ └─┬─┘ └╥┘ lqr_1_2: ┤ P(0.1) ├──────────┼───────╫─ └────────┘ │ ║ lqr_2_0: ────■───────────────┼───────╫─ ┌─┴─┐ ┌───┐ │ ┌─┐ ║ lqr_2_1: ──┤ X ├────┤ X ├────┼───┤M├─╫─ └───┘ └─┬─┘ │ └╥┘ ║ ┌──┴──┐┌──┴──┐ ║ ║ lcr_0: ════════════╡ ╞╡ ╞═╬══╩═ │ = 3 ││ = 3 │ ║ lcr_1: ════════════╡ ╞╡ ╞═╩════ └─────┘└─────┘ """ qreg = QuantumRegister(2, "rqr") creg = ClassicalRegister(2, "rcr") circuit_right = QuantumCircuit(qreg, creg) circuit_right.x(qreg[1]).c_if(creg, 3) circuit_right.h(qreg[0]).c_if(creg, 3) circuit_right.measure(qreg, creg) # permuted subset of qubits and clbits circuit_composed = self.circuit_left.compose(circuit_right, qubits=[1, 4], clbits=[0, 1]) circuit_expected = self.circuit_left.copy() circuit_expected.x(self.left_qubit4).c_if(*self.condition) circuit_expected.h(self.left_qubit1).c_if(*self.condition) circuit_expected.measure(self.left_qubit1, self.left_clbit0) circuit_expected.measure(self.left_qubit4, self.left_clbit1) self.assertEqual(circuit_composed, circuit_expected) def test_compose_conditional_no_match(self): """Test that compose correctly maps registers in conditions to the new circuit, even when there are no matching registers in the destination circuit. Regression test of gh-6583 and gh-6584.""" right = QuantumCircuit(QuantumRegister(3), ClassicalRegister(1), ClassicalRegister(1)) right.h(1) right.cx(1, 2) right.cx(0, 1) right.h(0) right.measure([0, 1], [0, 1]) right.z(2).c_if(right.cregs[0], 1) right.x(2).c_if(right.cregs[1], 1) test = QuantumCircuit(3, 3).compose(right, range(3), range(2)) z = next(ins.operation for ins in test.data[::-1] if ins.operation.name == "z") x = next(ins.operation for ins in test.data[::-1] if ins.operation.name == "x") # The registers should have been mapped, including the bits inside them. Unlike the # previous test, there are no matching registers in the destination circuit, so the # composition needs to add new registers (bit groupings) over the existing mapped bits. self.assertIsNot(z.condition, None) self.assertIsInstance(z.condition[0], ClassicalRegister) self.assertEqual(len(z.condition[0]), len(right.cregs[0])) self.assertIs(z.condition[0][0], test.clbits[0]) self.assertEqual(z.condition[1], 1) self.assertIsNot(x.condition, None) self.assertIsInstance(x.condition[0], ClassicalRegister) self.assertEqual(len(x.condition[0]), len(right.cregs[1])) self.assertEqual(z.condition[1], 1) self.assertIs(x.condition[0][0], test.clbits[1]) def test_compose_switch_match(self): """Test that composition containing a `switch` with a register that matches proceeds correctly.""" case_0 = QuantumCircuit(1, 2) case_0.x(0) case_1 = QuantumCircuit(1, 2) case_1.z(0) case_default = QuantumCircuit(1, 2) cr = ClassicalRegister(2, "target") right = QuantumCircuit(QuantumRegister(1), cr) right.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [0], [0, 1]) test = QuantumCircuit(QuantumRegister(3), cr, ClassicalRegister(2)).compose( right, [1], [0, 1] ) expected = test.copy_empty_like() expected.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [1], [0, 1]) self.assertEqual(test, expected) def test_compose_switch_no_match(self): """Test that composition containing a `switch` with a register that matches proceeds correctly.""" case_0 = QuantumCircuit(1, 2) case_0.x(0) case_1 = QuantumCircuit(1, 2) case_1.z(0) case_default = QuantumCircuit(1, 2) cr = ClassicalRegister(2, "target") right = QuantumCircuit(QuantumRegister(1), cr) right.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [0], [0, 1]) test = QuantumCircuit(3, 3).compose(right, [1], [0, 1]) self.assertEqual(len(test.data), 1) self.assertIsInstance(test.data[0].operation, SwitchCaseOp) target = test.data[0].operation.target self.assertIn(target, test.cregs) self.assertEqual(list(target), test.clbits[0:2]) def test_compose_gate(self): """Composing with a gate. ┌───┐ ┌───┐ ┌───┐ lqr_1_0: ──┤ H ├─── lqr_1_0: ──┤ H ├────┤ X ├ ├───┤ ├───┤ └─┬─┘ lqr_1_1: ──┤ X ├─── lqr_1_1: ──┤ X ├──────┼─── ┌─┴───┴──┐ ───■─── ┌─┴───┴──┐ │ lqr_1_2: ┤ P(0.1) ├ + ┌─┴─┐ = lqr_1_2: ┤ P(0.1) ├───┼─── └────────┘ ─┤ X ├─ └────────┘ │ lqr_2_0: ────■───── └───┘ lqr_2_0: ────■────────┼── ┌─┴─┐ ┌─┴─┐ │ lqr_2_1: ──┤ X ├─── lqr_2_1: ──┤ X ├──────■─── └───┘ └───┘ lcr_0: 0 ══════════ lcr_0: 0 ═════════════════ lcr_1: 0 ══════════ lcr_1: 0 ═════════════════ """ circuit_composed = self.circuit_left.compose(CXGate(), qubits=[4, 0]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit4, self.left_qubit0) self.assertEqual(circuit_composed, circuit_expected) def test_compose_calibrations(self): """Test that composing two circuits updates calibrations.""" circ_left = QuantumCircuit(1) circ_left.add_calibration("h", [0], None) circ_right = QuantumCircuit(1) circ_right.add_calibration("rx", [0], None) circ = circ_left.compose(circ_right) self.assertEqual(len(circ.calibrations), 2) self.assertEqual(len(circ_left.calibrations), 1) circ_left = QuantumCircuit(1) circ_left.add_calibration("h", [0], None) circ_right = QuantumCircuit(1) circ_right.add_calibration("h", [1], None) circ = circ_left.compose(circ_right) self.assertEqual(len(circ.calibrations), 1) self.assertEqual(len(circ.calibrations["h"]), 2) self.assertEqual(len(circ_left.calibrations), 1) # Ensure that transpiled _calibration is defaultdict qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc = transpile(qc, None, basis_gates=["h", "cx"], coupling_map=[[0, 1], [1, 0]]) qc.add_calibration("cx", [0, 1], Schedule()) def test_compose_one_liner(self): """Test building a circuit in one line, for fun.""" circ = QuantumCircuit(3) h = HGate() rz = RZGate(0.1) cx = CXGate() ccx = CCXGate() circ = circ.compose(h, [0]).compose(cx, [0, 2]).compose(ccx, [2, 1, 0]).compose(rz, [1]) expected = QuantumCircuit(3) expected.h(0) expected.cx(0, 2) expected.ccx(2, 1, 0) expected.rz(0.1, 1) self.assertEqual(circ, expected) def test_compose_global_phase(self): """Composing with global phase.""" circ1 = QuantumCircuit(1, global_phase=1) circ1.rz(0.5, 0) circ2 = QuantumCircuit(1, global_phase=2) circ3 = QuantumCircuit(1, global_phase=3) circ4 = circ1.compose(circ2).compose(circ3) self.assertEqual( circ4.global_phase, circ1.global_phase + circ2.global_phase + circ3.global_phase ) def test_compose_front_circuit(self): """Test composing a circuit at the front of a circuit.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) other = QuantumCircuit(2) other.cz(1, 0) other.z(1) output = qc.compose(other, front=True) expected = QuantumCircuit(2) expected.cz(1, 0) expected.z(1) expected.h(0) expected.cx(0, 1) self.assertEqual(output, expected) def test_compose_front_gate(self): """Test composing a gate at the front of a circuit.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) output = qc.compose(CXGate(), [1, 0], front=True) expected = QuantumCircuit(2) expected.cx(1, 0) expected.h(0) expected.cx(0, 1) self.assertEqual(output, expected) def test_compose_adds_parameters(self): """Test the composed circuit contains all parameters.""" a, b = Parameter("a"), Parameter("b") qc_a = QuantumCircuit(1) qc_a.rx(a, 0) qc_b = QuantumCircuit(1) qc_b.rx(b, 0) with self.subTest("compose with other circuit out-of-place"): qc_1 = qc_a.compose(qc_b) self.assertEqual(qc_1.parameters, {a, b}) with self.subTest("compose with other instruction out-of-place"): instr_b = qc_b.to_instruction() qc_2 = qc_a.compose(instr_b, [0]) self.assertEqual(qc_2.parameters, {a, b}) with self.subTest("compose with other circuit in-place"): qc_a.compose(qc_b, inplace=True) self.assertEqual(qc_a.parameters, {a, b}) def test_wrapped_compose(self): """Test wrapping the circuit upon composition works.""" qc_a = QuantumCircuit(1) qc_a.x(0) qc_b = QuantumCircuit(1, name="B") qc_b.h(0) qc_a.compose(qc_b, wrap=True, inplace=True) self.assertDictEqual(qc_a.count_ops(), {"B": 1, "x": 1}) self.assertDictEqual(qc_a.decompose().count_ops(), {"h": 1, "u3": 1}) def test_wrapping_unitary_circuit(self): """Test a unitary circuit will be wrapped as Gate, else as Instruction.""" qc_init = QuantumCircuit(1) qc_init.x(0) qc_unitary = QuantumCircuit(1, name="a") qc_unitary.ry(0.23, 0) qc_nonunitary = QuantumCircuit(1) qc_nonunitary.reset(0) with self.subTest("wrapping a unitary circuit"): qc = qc_init.compose(qc_unitary, wrap=True) self.assertIsInstance(qc.data[1].operation, Gate) with self.subTest("wrapping a non-unitary circuit"): qc = qc_init.compose(qc_nonunitary, wrap=True) self.assertIsInstance(qc.data[1].operation, Instruction) def test_single_bit_condition(self): """Test that compose can correctly handle circuits that contain conditions on single bits. This is a regression test of the bug that broke qiskit-experiments in gh-7653.""" base = QuantumCircuit(1, 1) base.x(0).c_if(0, True) test = QuantumCircuit(1, 1).compose(base) self.assertIsNot(base.clbits[0], test.clbits[0]) self.assertEqual(base, test) self.assertIs(test.data[0].operation.condition[0], test.clbits[0]) def test_condition_mapping_ifelseop(self): """Test that the condition in an `IfElseOp` is correctly mapped to a new set of bits and registers.""" base_loose = Clbit() base_creg = ClassicalRegister(2) base_qreg = QuantumRegister(1) base = QuantumCircuit(base_qreg, [base_loose], base_creg) with base.if_test((base_loose, True)): base.x(0) with base.if_test((base_creg, 3)): base.x(0) test_loose = Clbit() test_creg = ClassicalRegister(2) test_qreg = QuantumRegister(1) test = QuantumCircuit(test_qreg, [test_loose], test_creg).compose(base) bit_instruction = test.data[0].operation reg_instruction = test.data[1].operation self.assertIs(bit_instruction.condition[0], test_loose) self.assertEqual(bit_instruction.condition, (test_loose, True)) self.assertIs(reg_instruction.condition[0], test_creg) self.assertEqual(reg_instruction.condition, (test_creg, 3)) def test_condition_mapping_whileloopop(self): """Test that the condition in a `WhileLoopOp` is correctly mapped to a new set of bits and registers.""" base_loose = Clbit() base_creg = ClassicalRegister(2) base_qreg = QuantumRegister(1) base = QuantumCircuit(base_qreg, [base_loose], base_creg) with base.while_loop((base_loose, True)): base.x(0) with base.while_loop((base_creg, 3)): base.x(0) test_loose = Clbit() test_creg = ClassicalRegister(2) test_qreg = QuantumRegister(1) test = QuantumCircuit(test_qreg, [test_loose], test_creg).compose(base) bit_instruction = test.data[0].operation reg_instruction = test.data[1].operation self.assertIs(bit_instruction.condition[0], test_loose) self.assertEqual(bit_instruction.condition, (test_loose, True)) self.assertIs(reg_instruction.condition[0], test_creg) self.assertEqual(reg_instruction.condition, (test_creg, 3)) def test_compose_no_clbits_in_one(self): """Test combining a circuit with cregs to one without""" ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx") qc = QuantumCircuit(2) qc.measure_all() out = ansatz.compose(qc) self.assertEqual(out.clbits, qc.clbits) def test_compose_no_clbits_in_one_inplace(self): """Test combining a circuit with cregs to one without inplace""" ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx") qc = QuantumCircuit(2) qc.measure_all() ansatz.compose(qc, inplace=True) self.assertEqual(ansatz.clbits, qc.clbits) def test_compose_no_clbits_in_one_multireg(self): """Test combining a circuit with cregs to one without, multi cregs""" ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx") qa = QuantumRegister(2, "q") ca = ClassicalRegister(2, "a") cb = ClassicalRegister(2, "b") qc = QuantumCircuit(qa, ca, cb) qc.measure(0, cb[1]) out = ansatz.compose(qc) self.assertEqual(out.clbits, qc.clbits) self.assertEqual(out.cregs, qc.cregs) def test_compose_noclbits_registerless(self): """Combining a circuit with cregs to one without, registerless case""" inner = QuantumCircuit([Qubit(), Qubit()], [Clbit(), Clbit()]) inner.measure([0, 1], [0, 1]) outer = QuantumCircuit(2) outer.compose(inner, inplace=True) self.assertEqual(outer.clbits, inner.clbits) self.assertEqual(outer.cregs, []) def test_expr_condition_is_mapped(self): """Test that an expression in a condition involving several registers is mapped correctly to the destination circuit.""" inner = QuantumCircuit(1) inner.x(0) a_src = ClassicalRegister(2, "a_src") b_src = ClassicalRegister(2, "b_src") c_src = ClassicalRegister(name="c_src", bits=list(a_src) + list(b_src)) source = QuantumCircuit(QuantumRegister(1), a_src, b_src, c_src) test_1 = lambda: expr.lift(a_src[0]) test_2 = lambda: expr.logic_not(b_src[1]) test_3 = lambda: expr.logic_and(expr.bit_and(b_src, 2), expr.less(c_src, 7)) source.if_test(test_1(), inner.copy(), [0], []) source.if_else(test_2(), inner.copy(), inner.copy(), [0], []) source.while_loop(test_3(), inner.copy(), [0], []) a_dest = ClassicalRegister(2, "a_dest") b_dest = ClassicalRegister(2, "b_dest") dest = QuantumCircuit(QuantumRegister(1), a_dest, b_dest).compose(source) # Check that the input conditions weren't mutated. for in_condition, instruction in zip((test_1, test_2, test_3), source.data): self.assertEqual(in_condition(), instruction.operation.condition) # Should be `a_dest`, `b_dest` and an added one to account for `c_src`. self.assertEqual(len(dest.cregs), 3) mapped_reg = dest.cregs[-1] expected = QuantumCircuit(dest.qregs[0], a_dest, b_dest, mapped_reg) expected.if_test(expr.lift(a_dest[0]), inner.copy(), [0], []) expected.if_else(expr.logic_not(b_dest[1]), inner.copy(), inner.copy(), [0], []) expected.while_loop( expr.logic_and(expr.bit_and(b_dest, 2), expr.less(mapped_reg, 7)), inner.copy(), [0], [] ) self.assertEqual(dest, expected) def test_expr_target_is_mapped(self): """Test that an expression in a switch statement's target is mapping correctly to the destination circuit.""" inner1 = QuantumCircuit(1) inner1.x(0) inner2 = QuantumCircuit(1) inner2.z(0) a_src = ClassicalRegister(2, "a_src") b_src = ClassicalRegister(2, "b_src") c_src = ClassicalRegister(name="c_src", bits=list(a_src) + list(b_src)) source = QuantumCircuit(QuantumRegister(1), a_src, b_src, c_src) test_1 = lambda: expr.lift(a_src[0]) test_2 = lambda: expr.logic_not(b_src[1]) test_3 = lambda: expr.lift(b_src) test_4 = lambda: expr.bit_and(c_src, 7) source.switch(test_1(), [(False, inner1.copy()), (True, inner2.copy())], [0], []) source.switch(test_2(), [(False, inner1.copy()), (True, inner2.copy())], [0], []) source.switch(test_3(), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], []) source.switch(test_4(), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], []) a_dest = ClassicalRegister(2, "a_dest") b_dest = ClassicalRegister(2, "b_dest") dest = QuantumCircuit(QuantumRegister(1), a_dest, b_dest).compose(source) # Check that the input expressions weren't mutated. for in_target, instruction in zip((test_1, test_2, test_3, test_4), source.data): self.assertEqual(in_target(), instruction.operation.target) # Should be `a_dest`, `b_dest` and an added one to account for `c_src`. self.assertEqual(len(dest.cregs), 3) mapped_reg = dest.cregs[-1] expected = QuantumCircuit(dest.qregs[0], a_dest, b_dest, mapped_reg) expected.switch( expr.lift(a_dest[0]), [(False, inner1.copy()), (True, inner2.copy())], [0], [] ) expected.switch( expr.logic_not(b_dest[1]), [(False, inner1.copy()), (True, inner2.copy())], [0], [] ) expected.switch( expr.lift(b_dest), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], [] ) expected.switch( expr.bit_and(mapped_reg, 7), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], [], ) self.assertEqual(dest, expected) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] gate_counts = [] non_local_gate_counts = [] levels = [str(x) for x in range(4)] for level in range(4): circ = transpile(ghz, backend, optimization_level=level) depths.append(circ.depth()) gate_counts.append(sum(circ.count_ops().values())) non_local_gate_counts.append(circ.num_nonlocal_gates()) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.bar(levels, depths, label='Depth') ax1.set_xlabel("Optimization Level") ax1.set_ylabel("Depth") ax1.set_title("Output Circuit Depth") ax2.bar(levels, gate_counts, label='Number of Circuit Operations') ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates') ax2.set_xlabel("Optimization Level") ax2.set_ylabel("Number of gates") ax2.legend() ax2.set_title("Number of output circuit gates") fig.tight_layout() plt.show()
https://github.com/IlliaOvcharenko/quantum-search
IlliaOvcharenko
import sys, os sys.path.append(os.getcwd()) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from qiskit import QuantumCircuit # from qiskit.primitives.sampler import Sampler from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import (QiskitRuntimeService, SamplerV2 as Sampler) from fire import Fire def main(): ibm_token = open("credentials/ibm-token.txt").read().replace("\n", "") ibm_quantum_service = QiskitRuntimeService(channel="ibm_quantum", token=ibm_token) # print(ibm_quantum_service.backends(simulator=True)) qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) # qc.draw("mpl") # plt.savefig("figs/test-qc.png", bbox_inches="tight") qc_measured = qc.measure_all(inplace=False) # qc_measured.draw("mpl") # plt.savefig("figs/test-qc-measured.png", bbox_inches="tight") # sampler = Sampler() # job = sampler.run(qc_measured, shots=1) # result = job.result() # print(result) backend = ibm_quantum_service.least_busy(operational=True, simulator=False) print(backend) pm = generate_preset_pass_manager(backend=backend, optimization_level=1) qc_measured_opt = pm.run(qc_measured) sampler = Sampler(backend=backend) job = sampler.run([qc_measured_opt], shots=10) print(f"Job ID is {job.job_id()}") pub_result = job.result()[0] print(pub_result) if __name__ == "__main__": Fire(main)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test hardcoded decomposition rules and matrix definitions for standard gates.""" import inspect import numpy as np from ddt import ddt, data, idata, unpack from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.circuit import ParameterVector, Gate, ControlledGate from qiskit.circuit.library import standard_gates from qiskit.circuit.library import ( HGate, CHGate, IGate, RGate, RXGate, CRXGate, RYGate, CRYGate, RZGate, CRZGate, SGate, SdgGate, CSwapGate, TGate, TdgGate, U1Gate, CU1Gate, U2Gate, U3Gate, CU3Gate, XGate, CXGate, ECRGate, CCXGate, YGate, CYGate, ZGate, CZGate, RYYGate, PhaseGate, CPhaseGate, UGate, CUGate, SXGate, SXdgGate, CSXGate, RVGate, XXMinusYYGate, ) from qiskit.circuit.library.standard_gates.equivalence_library import ( StandardEquivalenceLibrary as std_eqlib, ) from .gate_utils import _get_free_params class TestGateDefinitions(QiskitTestCase): """Test the decomposition of a gate in terms of other gates yields the equivalent matrix as the hardcoded matrix definition up to a global phase.""" def test_ch_definition(self): # TODO: expand this to all gates """Test ch gate matrix and definition.""" circ = QuantumCircuit(2) circ.ch(0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_ccx_definition(self): """Test ccx gate matrix and definition.""" circ = QuantumCircuit(3) circ.ccx(0, 1, 2) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_crz_definition(self): """Test crz gate matrix and definition.""" circ = QuantumCircuit(2) circ.crz(1, 0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cry_definition(self): """Test cry gate matrix and definition.""" circ = QuantumCircuit(2) circ.cry(1, 0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_crx_definition(self): """Test crx gate matrix and definition.""" circ = QuantumCircuit(2) circ.crx(1, 0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cswap_definition(self): """Test cswap gate matrix and definition.""" circ = QuantumCircuit(3) circ.cswap(0, 1, 2) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cu1_definition(self): """Test cu1 gate matrix and definition.""" circ = QuantumCircuit(2) circ.append(CU1Gate(1), [0, 1]) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cu3_definition(self): """Test cu3 gate matrix and definition.""" circ = QuantumCircuit(2) circ.append(CU3Gate(1, 1, 1), [0, 1]) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cx_definition(self): """Test cx gate matrix and definition.""" circ = QuantumCircuit(2) circ.cx(0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_ecr_definition(self): """Test ecr gate matrix and definition.""" circ = QuantumCircuit(2) circ.ecr(0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_rv_definition(self): """Test R(v) gate to_matrix and definition.""" qreg = QuantumRegister(1) circ = QuantumCircuit(qreg) vec = np.array([0.1, 0.2, 0.3], dtype=float) circ.rv(*vec, 0) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_rv_r_equiv(self): """Test R(v) gate is equivalent to R gate.""" theta = np.pi / 5 phi = np.pi / 3 rgate = RGate(theta, phi) axis = np.array([np.cos(phi), np.sin(phi), 0]) # RGate axis rotvec = theta * axis rv = RVGate(*rotvec) rg_matrix = rgate.to_matrix() rv_matrix = rv.to_matrix() np.testing.assert_array_max_ulp(rg_matrix.real, rv_matrix.real, 4) np.testing.assert_array_max_ulp(rg_matrix.imag, rv_matrix.imag, 4) def test_rv_zero(self): """Test R(v) gate with zero vector returns identity""" rv = RVGate(0, 0, 0) self.assertTrue(np.array_equal(rv.to_matrix(), np.array([[1, 0], [0, 1]]))) def test_xx_minus_yy_definition(self): """Test XX-YY gate decomposition.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXMinusYYGate(theta, beta) circuit = QuantumCircuit(2) circuit.append(gate, [0, 1]) decomposed_circuit = circuit.decompose() self.assertTrue(len(decomposed_circuit) > len(circuit)) self.assertTrue(Operator(circuit).equiv(Operator(decomposed_circuit), atol=1e-7)) @ddt class TestStandardGates(QiskitTestCase): """Standard Extension Test.""" @unpack @data( *inspect.getmembers( standard_gates, predicate=lambda value: (inspect.isclass(value) and issubclass(value, Gate)), ) ) def test_definition_parameters(self, class_name, gate_class): """Verify definitions from standard library include correct parameters.""" free_params = _get_free_params(gate_class) n_params = len(free_params) param_vector = ParameterVector("th", n_params) if class_name in ("MCPhaseGate", "MCU1Gate"): param_vector = param_vector[:-1] gate = gate_class(*param_vector, num_ctrl_qubits=2) elif class_name in ("MCXGate", "MCXGrayCode", "MCXRecursive", "MCXVChain"): num_ctrl_qubits = 2 param_vector = param_vector[:-1] gate = gate_class(num_ctrl_qubits, *param_vector) elif class_name == "MSGate": num_qubits = 2 param_vector = param_vector[:-1] gate = gate_class(num_qubits, *param_vector) else: gate = gate_class(*param_vector) if gate.definition is not None: self.assertEqual(gate.definition.parameters, set(param_vector)) @unpack @data( *inspect.getmembers( standard_gates, predicate=lambda value: (inspect.isclass(value) and issubclass(value, Gate)), ) ) def test_inverse(self, class_name, gate_class): """Verify self-inverse pair yield identity for all standard gates.""" free_params = _get_free_params(gate_class) n_params = len(free_params) float_vector = [0.1 + 0.1 * i for i in range(n_params)] if class_name in ("MCPhaseGate", "MCU1Gate"): float_vector = float_vector[:-1] gate = gate_class(*float_vector, num_ctrl_qubits=2) elif class_name in ("MCXGate", "MCXGrayCode", "MCXRecursive", "MCXVChain"): num_ctrl_qubits = 3 float_vector = float_vector[:-1] gate = gate_class(num_ctrl_qubits, *float_vector) elif class_name == "PauliGate": pauli_string = "IXYZ" gate = gate_class(pauli_string) else: gate = gate_class(*float_vector) from qiskit.quantum_info.operators.predicates import is_identity_matrix self.assertTrue(is_identity_matrix(Operator(gate).dot(gate.inverse()).data)) if gate.definition is not None: self.assertTrue(is_identity_matrix(Operator(gate).dot(gate.definition.inverse()).data)) self.assertTrue(is_identity_matrix(Operator(gate).dot(gate.inverse().definition).data)) @ddt class TestGateEquivalenceEqual(QiskitTestCase): """Test the decomposition of a gate in terms of other gates yields the same matrix as the hardcoded matrix definition.""" class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() exclude = { "ControlledGate", "DiagonalGate", "UCGate", "MCGupDiag", "MCU1Gate", "UnitaryGate", "HamiltonianGate", "MCPhaseGate", "UCPauliRotGate", "SingleQubitUnitary", "MCXGate", "VariadicZeroParamGate", "ClassicalFunction", "ClassicalElement", "StatePreparation", "LinearFunction", "PermutationGate", "Commuting2qBlock", "PauliEvolutionGate", "_U0Gate", "_DefinedGate", } # Amazingly, Python's scoping rules for class bodies means that this is the closest we can get # to a "natural" comprehension or functional iterable definition: # https://docs.python.org/3/reference/executionmodel.html#resolution-of-names @idata(filter(lambda x, exclude=exclude: x.__name__ not in exclude, class_list)) def test_equivalence_phase(self, gate_class): """Test that the equivalent circuits from the equivalency_library have equal matrix representations""" n_params = len(_get_free_params(gate_class)) params = [0.1 * i for i in range(1, n_params + 1)] if gate_class.__name__ == "RXXGate": params = [np.pi / 2] if gate_class.__name__ in ["MSGate"]: params[0] = 2 if gate_class.__name__ in ["PauliGate"]: params = ["IXYZ"] if gate_class.__name__ in ["BooleanExpression"]: params = ["x | y"] gate = gate_class(*params) equiv_lib_list = std_eqlib.get_entry(gate) for ieq, equivalency in enumerate(equiv_lib_list): with self.subTest(msg=gate.name + "_" + str(ieq)): op1 = Operator(gate) op2 = Operator(equivalency) self.assertEqual(op1, op2) @ddt class TestStandardEquivalenceLibrary(QiskitTestCase): """Standard Extension Test.""" @data( HGate, CHGate, IGate, RGate, RXGate, CRXGate, RYGate, CRYGate, RZGate, CRZGate, SGate, SdgGate, CSwapGate, TGate, TdgGate, U1Gate, CU1Gate, U2Gate, U3Gate, CU3Gate, XGate, CXGate, ECRGate, CCXGate, YGate, CYGate, ZGate, CZGate, RYYGate, PhaseGate, CPhaseGate, UGate, CUGate, SXGate, SXdgGate, CSXGate, ) def test_definition_parameters(self, gate_class): """Verify decompositions from standard equivalence library match definitions.""" n_params = len(_get_free_params(gate_class)) param_vector = ParameterVector("th", n_params) float_vector = [0.1 * i for i in range(n_params)] param_gate = gate_class(*param_vector) float_gate = gate_class(*float_vector) param_entry = std_eqlib.get_entry(param_gate) float_entry = std_eqlib.get_entry(float_gate) if not param_gate.definition or not param_gate.definition.data: return self.assertGreaterEqual(len(param_entry), 1) self.assertGreaterEqual(len(float_entry), 1) param_qc = QuantumCircuit(param_gate.num_qubits) float_qc = QuantumCircuit(float_gate.num_qubits) param_qc.append(param_gate, param_qc.qregs[0]) float_qc.append(float_gate, float_qc.qregs[0]) self.assertTrue(any(equiv == param_qc.decompose() for equiv in param_entry)) self.assertTrue(any(equiv == float_qc.decompose() for equiv in float_entry))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel line = LineLattice(2) fermi = FermiHubbardModel.uniform_parameters(line, 2.0, 4.0, 3.0) print(fermi.second_q_ops()) # Note: the trailing `s` from qiskit_nature.second_q.hamiltonians.lattices import LineLattice from qiskit_nature.second_q.hamiltonians import FermiHubbardModel line = LineLattice(2) fermi = FermiHubbardModel(line.uniform_parameters(2.0, 4.0), 3.0) print(fermi.second_q_op()) # Note: NO trailing `s` import numpy as np from qiskit_nature.problems.second_quantization.lattice.models import FermiHubbardModel interaction = np.array([[4.0, 2.0], [2.0, 4.0]]) fermi = FermiHubbardModel.from_parameters(interaction, 3.0) print(fermi.second_q_ops()) # Note: the trailing `s` import numpy as np from qiskit_nature.second_q.hamiltonians.lattices import Lattice from qiskit_nature.second_q.hamiltonians import FermiHubbardModel interaction = np.array([[4.0, 2.0], [2.0, 4.0]]) lattice = Lattice.from_adjacency_matrix(interaction) fermi = FermiHubbardModel(lattice, 3.0) print(fermi.second_q_op()) # Note: NO trailing `s` from qiskit_nature.problems.second_quantization.lattice.lattices import LineLattice from qiskit_nature.problems.second_quantization.lattice.models import IsingModel line = LineLattice(2) ising = IsingModel.uniform_parameters(line, 2.0, 4.0) print(ising.second_q_ops()) # Note: the trailing `s` from qiskit_nature.second_q.hamiltonians.lattices import LineLattice from qiskit_nature.second_q.hamiltonians import IsingModel line = LineLattice(2) ising = IsingModel(line.uniform_parameters(2.0, 4.0)) print(ising.second_q_op()) # Note: NO trailing `s` import numpy as np from qiskit_nature.problems.second_quantization.lattice.models import IsingModel interaction = np.array([[4.0, 2.0], [2.0, 4.0]]) ising = IsingModel.from_parameters(interaction) print(ising.second_q_ops()) # Note: the trailing `s` import numpy as np from qiskit_nature.second_q.hamiltonians.lattices import Lattice from qiskit_nature.second_q.hamiltonians import IsingModel interaction = np.array([[4.0, 2.0], [2.0, 4.0]]) lattice = Lattice.from_adjacency_matrix(interaction) ising = IsingModel(lattice) print(ising.second_q_op()) # Note: NO trailing `s` import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.opflow import I, X, Y, Z print(I, X, Y, Z) print(1.5 * I) print(2.5 * X) print(X + 2.0 * Y) print(X^Y^Z) print(X @ Y @ Z) print((X + Y) @ (Y + Z)) print((X + Y) ^ (Y + Z)) (I, X) 2.0 * X^Y^Z print(1.1 * ((1.2 * X)^(Y + (1.3 * Z)))) from qiskit.opflow import (StateFn, Zero, One, Plus, Minus, H, DictStateFn, VectorStateFn, CircuitStateFn, OperatorStateFn) print(Zero, One) print(Plus, Minus) print(Zero.eval('0')) print(Zero.eval('1')) print(One.eval('1')) print(Plus.eval('0')) print(Minus.eval('1')) One.adjoint() ~One (2.0 + 3.0j) * Zero print(Zero + One) import math v_zero_one = (Zero + One) / math.sqrt(2) print(v_zero_one) print(Plus + Minus) print(~One @ One) (~One @ One).eval() (~v_zero_one @ v_zero_one).eval() (~Minus @ One).eval() print((~One).compose(One)) (~One).eval(One) print(Zero^Plus) print((Zero^Plus).to_circuit_op()) print(600 * ((One^5) + (Zero^5))) print((One^Zero)^3) print(((Plus^Minus)^2).to_matrix_op()) print(((Plus^One)^2).to_circuit_op()) print(((Plus^One)^2).to_matrix_op().sample()) print(StateFn({'0':1})) print(StateFn({'0':1}) == Zero) print(StateFn([0,1,1,0])) from qiskit.circuit.library import RealAmplitudes print(StateFn(RealAmplitudes(2))) from qiskit.opflow import X, Y, Z, I, CX, T, H, S, PrimitiveOp X print(X.eval('0')) X.eval('0').eval('1') print(CX) print(CX.to_matrix().real) # The imaginary part vanishes. CX.eval('01') # 01 is the one in decimal. We get the first column. CX.eval('01').eval('11') # This returns element with (zero-based) index (1, 3) print(X @ One) (X @ One).eval() X.eval(One) print(((~One^2) @ (CX.eval('01'))).eval()) print(((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2) print((((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2) @ (Minus^5)) print(((H^I^I)@(X^I^I)@Zero)) print(~One @ Minus) from qiskit.opflow import ListOp print((~ListOp([One, Zero]) @ ListOp([One, Zero]))) print((~ListOp([One, Zero]) @ ListOp([One, Zero])).reduce()) print(StateFn(Z).adjoint()) StateFn(Z).adjoint() print(StateFn(Z).adjoint().eval(Zero)) print(StateFn(Z).adjoint().eval(One)) print(StateFn(Z).adjoint().eval(Plus)) import numpy as np from qiskit.opflow import I, X, Y, Z, H, CX, Zero, ListOp, PauliExpectation, PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki from qiskit.circuit import Parameter from qiskit import Aer two_qubit_H2 = (-1.0523732 * I^I) + \ (0.39793742 * I^Z) + \ (-0.3979374 * Z^I) + \ (-0.0112801 * Z^Z) + \ (0.18093119 * X^X) print(two_qubit_H2) evo_time = Parameter('θ') evolution_op = (evo_time*two_qubit_H2).exp_i() print(evolution_op) # Note, EvolvedOps print as exponentiations print(repr(evolution_op)) h2_measurement = StateFn(two_qubit_H2).adjoint() print(h2_measurement) bell = CX @ (I ^ H) @ Zero print(bell) evo_and_meas = h2_measurement @ evolution_op @ bell print(evo_and_meas) trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas) # We can also set trotter_mode='suzuki' or leave it empty to default to first order Trotterization. print(trotterized_op) bound = trotterized_op.bind_parameters({evo_time: .5}) bound[1].to_circuit().draw() # Note that XX was the only non-diagonal measurement in our H2 Observable print(PauliExpectation(group_paulis=False).convert(h2_measurement)) print(PauliExpectation().convert(h2_measurement)) diagonalized_meas_op = PauliExpectation().convert(trotterized_op) print(diagonalized_meas_op) evo_time_points = list(range(8)) h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: evo_time_points}) h2_trotter_expectations.eval() sampler = CircuitSampler(backend=Aer.get_backend('aer_simulator')) # sampler.quantum_instance.run_config.shots = 1000 sampled_trotter_exp_op = sampler.convert(h2_trotter_expectations) sampled_trotter_energies = sampled_trotter_exp_op.eval() print('Sampled Trotterized energies:\n {}'.format(np.real(sampled_trotter_energies))) print('Before:\n') print(h2_trotter_expectations.reduce()[0][0]) print('\nAfter:\n') print(sampled_trotter_exp_op[0][0]) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/arthurfaria/QC_basic_agorithms_qiskit
arthurfaria
import matplotlib as mpl import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(1,1) # Alice prepares qubit in state |+> qc.h(0) qc.barrier() # Alice now sends the qubit to Bob # who measures it in the X-basis qc.h(0) qc.measure(0,0) # Draw and simulate circuit display(qc.draw()) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(assemble(qc)) plot_histogram(job.result().get_counts()) qc = QuantumCircuit(1,1) # Alice prepares qubit in state |+> qc.h(0) # Alice now sends the qubit to Bob # but Eve intercepts and tries to read it qc.measure(0, 0) qc.barrier() # Eve then passes this on to Bob # who measures it in the X-basis qc.h(0) qc.measure(0,0) # Draw and simulate circuit display(qc.draw()) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(assemble(qc)) plot_histogram(job.result().get_counts()) n = 100 ## Step 1 # Alice generates bits. alice_bits = np.random.randint(0,2,n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = np.random.randint(0,2,n) # Function to compare the bits & bases generated by alice, and then 'encode' the message. Basically determines the state of the qubit/photon to send. def encode_message(bits, bases): message = [] for i in range(n): qc = QuantumCircuit(1,1) if bases[i] == 0: # Prepare qubit in Z-basis if bits[i] == 0: pass else: qc.x(0) else: # Prepare qubit in X-basis if bits[i] == 0: qc.h(0) else: qc.x(0) qc.h(0) qc.barrier() message.append(qc) return message # Alice computes the encoded message using the function defined above. message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = np.random.randint(0,2,n) # Function to decode the message sent by alice by comparing qubit/photon states with Bob's generated bases. def measure_message(message, bases): backend = Aer.get_backend('aer_simulator') measurements = [] for q in range(n): if bases[q] == 0: # measuring in Z-basis message[q].measure(0,0) if bases[q] == 1: # measuring in X-basis message[q].h(0) message[q].measure(0,0) aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(message[q], shots=1, memory=True) result = aer_sim.run(qobj).result() measured_bit = int(result.get_memory()[0]) measurements.append(measured_bit) return measurements # Decode the message according to his bases bob_results = measure_message(message, bob_bases) ## Step 4 # Function to perform sifting i.e. disregard the bits for which Bob's & A;ice's bases didnot match. def remove_garbage(a_bases, b_bases, bits): good_bits = [] for q in range(n): if a_bases[q] == b_bases[q]: # If both used the same basis, add # this to the list of 'good' bits good_bits.append(bits[q]) return good_bits # Performing sifting for Alice's and Bob's bits. alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) bob_key = remove_garbage(alice_bases, bob_bases, bob_results) print("Alice's key after sifting (without interception)", alice_key) print("Bob's key after sifting (without interception) ", bob_key) # # Step 5 # # Function for parameter estimation i.e. determining the error rate by comparing subsets taen from both Alice's key & Bob's key. # def sample_bits(bits, selection): # sample = [] # for i in selection: # # use np.mod to make sure the # # bit we sample is always in # # the list range # i = np.mod(i, len(bits)) # # pop(i) removes the element of the # # list at index 'i' # sample.append(bits.pop(i)) # return sample # # Performing parameter estimation & disregarding the bits used for comparison from Alice's & Bob's key. # sample_size = 15 # bit_selection = np.random.randint(0,n,size=sample_size) # bob_sample = sample_bits(bob_key, bit_selection) # alice_sample = sample_bits(alice_key, bit_selection) num = 0 for i in range(0,len(bob_key)): if alice_key[i] == bob_key[i]: num = num + 1 matching_bits = (num/len(bob_key))*100 print(matching_bits,"% of the bits match.") ## Step 1 alice_bits = np.random.randint(2, size=n) ## Step 2 alice_bases = np.random.randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interception!! eve_bases = np.random.randint(2, size=n) intercepted_message = measure_message(message, eve_bases) ## Step 3 bob_bases = np.random.randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) print("Alice's key after sifting (with interception)", alice_key) print("Bob's key after sifting (with interception) ", bob_key) # ## Step 5 # sample_size = 15 # bit_selection = np.random.randint(n, size=sample_size) # bob_sample = sample_bits(bob_key, bit_selection) # alice_sample = sample_bits(alice_key, bit_selection) num = 0 for i in range(0,len(bob_key)): if alice_key[i] == bob_key[i]: num = num + 1 matching_bits = (num/len(bob_key))*100 print(matching_bits,"% of the bits match.") plt.rcParams['axes.linewidth'] = 2 mpl.rcParams['font.family'] = ['Georgia'] plt.figure(figsize=(10.5,6)) ax=plt.axes() ax.set_title('') ax.set_xlabel('$n$ (Number of bits drawn from the sifted keys for determining error rate)',fontsize = 18,labelpad=10) ax.set_ylabel(r'$P(Eve\ detected)$',fontsize = 18,labelpad=10) ax.xaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on') ax.yaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on') ax.tick_params(axis='x', labelsize=20) ax.tick_params(axis='y', labelsize=20) ax. xaxis. label. set_size(20) ax. yaxis. label. set_size(20) n = 30 x = np.arange(n+1) y = 1 - 0.75**x ax.plot(x,y,color = plt.cm.rainbow(np.linspace(0, 1, 5))[0], marker = "s", markerfacecolor='r')
https://github.com/Javihaus/Quantum-Machinel-Leaning
Javihaus
from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram from qiskit_textbook.widgets import binary_widget binary_widget(nbits=5) n = 8 n_q = n n_b = n qc_output = QuantumCircuit(n_q,n_b) for j in range(n): qc_output.measure(j,j) qc_output.draw(output='mpl') counts = execute(qc_output,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) qc_encode = QuantumCircuit(n) qc_encode.x(7) qc_encode.draw(output='mpl') qc = qc_encode + qc_output qc.draw(output='mpl',justify='none') counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) qc_encode = QuantumCircuit(n) qc_encode.x(1) qc_encode.x(5) qc_encode.draw(output='mpl') qc_cnot = QuantumCircuit(2) qc_cnot.cx(0,1) qc_cnot.draw(output='mpl') qc = QuantumCircuit(2,2) qc.x(0) qc.cx(0,1) qc.measure(0,0) qc.measure(1,1) qc.draw(output='mpl') qc_ha = QuantumCircuit(4,2) # encode inputs in qubits 0 and 1 qc_ha.x(0) # For a=0, remove this line. For a=1, leave it. qc_ha.x(1) # For b=0, remove 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) qc_ha.barrier() # extract outputs qc_ha.measure(2,0) # extract XOR value qc_ha.measure(3,1) qc_ha.draw(output='mpl') 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(outpu='mpl') counts = execute(qc_ha,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) import qiskit qiskit.__qiskit_version__
https://github.com/anirban-m/qiskit-superstaq
anirban-m
""" Creates and simulates a bell circuit. Example Output: job has successfully run {'00': 52, '11': 48} """ import qiskit import qiskit_superstaq as qss # SuperstaQ token retrieved through API token = "insert api token" # Create provider using authorization token superstaq = qss.superstaq_provider.SuperstaQProvider(token) # Retrieve backend from superstaq provider backend = superstaq.get_backend("ibmq_qasm_simulator") # Standard bell circuit qc = qiskit.QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) # Submit job to backend job = backend.run(qc, shots=100) # Get job status print(job.status().value) # Get result of job result = job.result() # Print job counts print(result.get_counts())
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
rodneyosodo
from qiskit.ml.datasets import * from qiskit import QuantumCircuit from qiskit.aqua.components.optimizers import COBYLA, ADAM, SPSA, SLSQP, POWELL, L_BFGS_B, TNC, AQGD from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes, ZFeatureMap, PauliFeatureMap from qiskit.quantum_info import Statevector import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import normalize from sklearn.model_selection import train_test_split from sklearn.utils import shuffle import warnings warnings.filterwarnings("ignore") %matplotlib inline # constants n = 4 RANDOM_STATE = 42 LR = 1e-3 class_labels = ['yes', 'no'] def normalizeData(DATA_PATH = "../../Data/Processed/data.csv"): """ Normalizes the data """ # Reads the data data = pd.read_csv(DATA_PATH) data = shuffle(data, random_state=RANDOM_STATE) X, Y = data[['sex', 'cp', 'exang', 'oldpeak']].values, data['num'].values # normalize the data X = normalize(X) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=RANDOM_STATE) return X_train, X_test, Y_train, Y_test X_train, X_test, Y_train, Y_test = normalizeData() feature_map = ZZFeatureMap(n, reps=1) feature_map.draw(output="mpl", filename="../../Output/Figures/ZZFeaturemap.png") feature_map = ZFeatureMap(n, reps=1) feature_map.draw(output="mpl", filename="../../Output/Figures/ZFeaturemap.png") feature_map = PauliFeatureMap(n, reps=1) feature_map.draw(output="mpl", filename="../../Output/Figures/PauliFeaturemap.png") var_form = RealAmplitudes(n, reps=1) var_form.draw(output="mpl", filename="../../Output/Figures/RealAmplitudes.png") sv = Statevector.from_label('0' * n) feature_map = ZZFeatureMap(n, reps=1) feature_map.barrier() var_form = RealAmplitudes(n, reps=1) circuit = feature_map.combine(var_form) circuit.draw(output="mpl", filename="../../Output/Figures/overallcircuit.png") def get_data_dict(params, x): parameters = {} for i, p in enumerate(feature_map.ordered_parameters): parameters[p] = x[i] for i, p in enumerate(var_form.ordered_parameters): parameters[p] = params[i] return parameters def assign_label(bit_string, class_labels): hamming_weight = sum([int(k) for k in list(bit_string)]) is_odd_parity = hamming_weight & 1 if is_odd_parity: return class_labels[1] else: return class_labels[0] data = X_train[0] params = np.array([0.1, 1.2, 0.02, 0.1, 0.1, 1.2, 0.02, 0.1]) circ_ = circuit.assign_parameters(get_data_dict(params, data)) circ_.draw(plot_barriers=True, output="mpl", filename="../../Output/Figures/parameterisedcircuit.png")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXDebugging from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXDebugging())
https://github.com/qiskit-community/qiskit-quantinuum-provider
qiskit-community
# 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. # Copyright 2019-2020 Quantinuum, Intl. (www.quantinuum.com) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Quantinuum TestCase for testing backends.""" from qiskit import execute from qiskit import QuantumCircuit from qiskit.providers.jobstatus import JobStatus from qiskit.providers.models import BackendStatus from qiskit.test import QiskitTestCase from qiskit_quantinuum import Quantinuum from qiskit_quantinuum import QuantinuumProvider from qiskit_quantinuum import QuantinuumJob from qiskit_quantinuum import QuantinuumBackend from qiskit_quantinuum.api import QuantinuumClient from .decorators import online_test class QuantinuumBackendTestCase(QiskitTestCase): """Test case for Quantinuum backend. Members: proivder_cls (BaseProvider): provider to be used in this test case. api_cls (QuantinuumClient): api to be used in this test case backend_cls (BaseBackend): backend to be used in this test case. Its instantiation can be further customized by overriding the ``_get_backend`` function. backend_name (str): name of backend to be used in tests. """ provider_cls = QuantinuumProvider api_cls = QuantinuumClient backend_cls = QuantinuumBackend backend_name = 'H1-1SC' def setUp(self): super().setUp() self.circuit = QuantumCircuit(4) self.circuit.h(0) self.circuit.cx(0, 1) self.circuit.h(0) self.circuit.cp(1.0, 0, 1) self.circuit.toffoli(0, 1, 2) self.circuit.toffoli(1, 2, 3) self.circuit.x(0) self.circuit.y(0) self.circuit.z(0) self.circuit.cx(0, 1) self.circuit.h(0) self.circuit.s(0) self.circuit.sdg(0) self.circuit.t(0) self.circuit.tdg(0) self.circuit.rx(1.0, 0) self.circuit.ry(1.0, 0) self.circuit.rz(1.0, 0) self.circuit.cz(0, 1) self.circuit.cy(0, 2) self.circuit.ch(0, 3) self.circuit.ccx(0, 1, 2) self.circuit.crz(1.0, 0, 1) self.circuit.crx(1.0, 0, 1) self.circuit.cry(1.0, 0, 1) self.circuit.cp(1.0, 0, 1) self.circuit.cu(1.0, 2.0, 3.0, 0.0, 0, 1) self.circuit.measure_all() def test_configuration(self): """Test backend.configuration().""" pass def test_properties(self): """Test backend.properties().""" pass @online_test def test_provider(self): """Test backend.provider().""" Quantinuum.load_account() backend = Quantinuum.get_backend(self.backend_name) provider = backend.provider() self.assertEqual(provider, self.provider_cls()) @online_test def test_status(self): """Test backend.status().""" Quantinuum.load_account() backend = Quantinuum.get_backend(self.backend_name) status = backend.status() self.assertIsInstance(status, BackendStatus) @online_test def test_name(self): """Test backend.name().""" Quantinuum.load_account() backend = Quantinuum.get_backend(self.backend_name) name = backend.name() self.assertEqual(name, self.backend_name) @online_test def _submit_job(self): """Helper method to submit job and return job instance""" Quantinuum.load_account() backend = Quantinuum.get_backend(self.backend_name) return execute(self.circuit, backend) @online_test def test_submit_job(self): """Test running a single circuit.""" Quantinuum.load_account() job = self._submit_job() self.assertIsInstance(job, QuantinuumJob) @online_test def test_get_job_result(self): """Test get result of job""" Quantinuum.load_account() job = self._submit_job() result = job.result() self.assertEqual(result.success, True) return result @online_test def test_get_job_status(self): """Test get status of job""" job = self._submit_job() Quantinuum.load_account() status = job.status() self.assertIsInstance(status, JobStatus) def test_get_job_error_message(self): """Test get error message of job""" pass @online_test def test_get_creation_date(self): """Test get creation date of job""" Quantinuum.load_account() job = self._submit_job() creation_date = job.creation_date() self.assertIsNotNone(creation_date) @online_test def test_get_job_id(self): """Test get id of job""" Quantinuum.load_account() job = self._submit_job() job_id = job.job_id() self.assertIsNotNone(job_id) @online_test def test_job_with_id(self): """Test creating a job with an id.""" Quantinuum.load_account() backend = Quantinuum.get_backend(self.backend_name) job = self._submit_job() job_id = job.job_id() credentials = backend.provider().credentials job_created_with_id = QuantinuumJob(backend, job_id, self.api_cls(credentials)) result = job_created_with_id.result() self.assertEqual(result.success, True) return result
https://github.com/sjana01/QiskitNotebooks
sjana01
import numpy as np ket0 = np.array([1,0]) ket1 = np.array([0,1]) ket0/2 + ket1/2 M1 = np.array([ [1, 1], [0, 0] ]) M2 = np.array([ [1, 1], [1, 0] ]) M1/2 + M2/2 print("product of M1 with ket0: ", np.matmul(M1,ket0)) print("product of M1 and M2: \n",np.matmul(M1,M2)) from qiskit.quantum_info import Statevector u = Statevector([1/np.sqrt(2), 1/np.sqrt(2)]) v = Statevector([(1+2.j)/3, -2/3]) display(u.draw('latex')) display(u.draw('text')) display(v.draw('latex')) w = Statevector([1/3,2/3]) display(v.is_valid()) display(w.is_valid()) v = Statevector([(1+2.j)/3, -2/3]) v.measure() from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt stat = v.sample_counts(10000) display(stat) plot_histogram(stat) from qiskit.quantum_info import Operator t = np.sqrt(2) X = Operator([[0,1],[1,0]]) Y = Operator([[0,-1.j],[1.j,0]]) Z = Operator([[1,0],[0,-1]]) H = Operator([[1/t, 1/t],[1/t, -1/t]]) S = Operator([[1,0],[0,1.j]]) T = Operator([[1,0],[0,(1+1.j)/t]]) v = Statevector([1,0]) display(v.evolve(X).draw('latex')) display(v.evolve(Y).draw('latex')) display(v.evolve(H).draw('latex')) display(v.evolve(S).draw('latex')) from qiskit import QuantumCircuit # initiate an instance of the class qc = QuantumCircuit(1) ## A QuantumCircuit with 1 qubits qc.h(0) qc.t(0) qc.h(0) qc.t(0) qc.z(0) qc.draw() ket0 = Statevector([1,0]) v = ket0.evolve(qc) v.draw('latex') stat = v.sample_counts(5000) plot_histogram(stat) ket0 = Statevector([1,0]) ket1 = Statevector([0,1]) ket01 = ket0.tensor(ket1) display(ket01.draw('latex')) # Another quick way to define the common states zero = Statevector.from_label('0') one = Statevector.from_label('1') plus = Statevector.from_label('+') minus = Statevector.from_label('-') i_state = 1/np.sqrt(2) * (zero + 1.j * one) psi = minus.tensor(i_state) psi.draw('latex') X.tensor(Z) psi_1 = psi.evolve(T^X) display(psi_1.draw('latex')) CNOT = Operator([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0] ]) psi_2 = psi.evolve(CNOT) display(psi_2.draw('latex')) # SOLUTION phi_plus = plus.tensor(zero).evolve(CNOT) phi_minus = minus.tensor(zero).evolve(CNOT) psi_plus = plus.tensor(one).evolve(CNOT) psi_minus = minus.tensor(one).evolve(CNOT) display(phi_plus.draw('latex')) display(phi_minus.draw('latex')) display(psi_plus.draw('latex')) display(psi_minus.draw('latex')) W = Statevector([0,1,1,0,1,0,0,0]/np.sqrt(3)) display(W.draw('latex')) result, new_statevector = W.measure([0]) print(f"Measured: {result} \n New Statevector:") display(new_statevector.draw('latex')) result, new_statevector = W.measure([1]) print(f"Measured: {result} \n New Statevector:") display(new_statevector.draw('latex')) I = Operator([[1,0],[0,1]]) W1 = W.evolve(I^I^H) display(W1.draw('latex')) result, new_statevector = W1.measure([0]) print(f"Measured: {result} \n New Statevector:") display(new_statevector.draw('latex')) W1.probabilities([0]) import qiskit.tools.jupyter %qiskit_version_table from qiskit import QuantumCircuit qc = QuantumCircuit(1) qc.h(0) qc.s(0) qc.h(0) qc.t(0) qc.draw() from qiskit import QuantumRegister u = QuantumRegister(1, "u") qc = QuantumCircuit(u) qc.y(0) qc.s(0) qc.h(0) qc.t(0) qc.x(0) qc.draw() from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister X = QuantumRegister(1, "x") Y = QuantumRegister(1, "y") A = ClassicalRegister(1, "a") B = ClassicalRegister(1, "b") qc = QuantumCircuit(Y,X,B,A) qc.h(Y) qc.cx(Y,X) qc.measure(Y,B) qc.measure(X,A) qc.draw() from qiskit import transpile from qiskit_aer import AerSimulator simulator = AerSimulator() qc_simulator = simulator.run(transpile(qc,simulator), shots=1000) statistics = qc_simulator.result().get_counts() plot_histogram(statistics) # Circuit circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.measure_all() from qiskit import Aer # Transpile for simulator simulator = Aer.get_backend('aer_simulator') circ = transpile(circ, simulator) # Run and get counts result = simulator.run(circ).result() counts = result.get_counts(circ) plot_histogram(counts, title='Bell-State counts') # Run and get memory result = simulator.run(circ, shots=10, memory=True).result() memory = result.get_memory(circ) memory Aer.backends()
https://github.com/Advanced-Research-Centre/QPULBA
Advanced-Research-Centre
import numpy as np import random from qiskit import QuantumCircuit, Aer, execute from math import log2 import sys #===================================================================================================================== simulator = Aer.get_backend('statevector_simulator') emulator = Aer.get_backend('qasm_simulator') def disp_isv(circ, msg="", all=True, precision=1e-8): sim_res = execute(circ, simulator).result() statevector = sim_res.get_statevector(circ) qb = int(log2(len(statevector))) print("\n============ State Vector ============", msg) s = 0 for i in statevector: if (all == True): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb)) else: if (abs(i) > precision): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb)) s = s+1 print("============..............============") return #===================================================================================================================== qcirc = QuantumCircuit(3,1) qcirc.h(0) qcirc.h(1) disp_isv(qcirc, "Step 1", all=False, precision=1e-4) qcirc.ccx(0,1,2) disp_isv(qcirc, "Step 2", all=False, precision=1e-4) qcirc.measure(2, 0) print(qcirc.draw()) for i in range(0,4): disp_isv(qcirc, "Step 3 Try "+str(i+1), all=False, precision=1e-4) # job = execute(qcirc, emulator, shots=1024) # hist = job.result().get_counts() #===================================================================================================================== # (qeait) D:\GoogleDrive\RESEARCH\0 - Programs\QPULBA>python qpostselect.py # # ============ State Vector ============ Step 1 # (+0.50000+0.00000j) |000> # (+0.50000+0.00000j) |001> # (+0.50000+0.00000j) |010> # (+0.50000+0.00000j) |011> # ============..............============ # # ============ State Vector ============ Step 2 # (+0.50000+0.00000j) |000> # (+0.50000+0.00000j) |001> # (+0.50000+0.00000j) |010> # (+0.50000+0.00000j) |111> # ============..............============ # ┌───┐ # q_0: ┤ H ├──■───── # ├───┤ │ # q_1: ┤ H ├──■───── # └───┘┌─┴─┐┌─┐ # q_2: ─────┤ X ├┤M├ # └───┘└╥┘ # c: 1/═══════════╩═ # 0 # # ============ State Vector ============ Step 3 Try 1 # (+0.57735+0.00000j) |000> # (+0.57735+0.00000j) |001> # (+0.57735+0.00000j) |010> # ============..............============ # # ============ State Vector ============ Step 3 Try 2 # (+1.00000+0.00000j) |111> # ============..............============ # # ============ State Vector ============ Step 3 Try 3 # (+0.57735+0.00000j) |000> # (+0.57735+0.00000j) |001> # (+0.57735+0.00000j) |010> # ============..............============ # # ============ State Vector ============ Step 3 Try 4 # (+0.57735+0.00000j) |000> # (+0.57735+0.00000j) |001> # (+0.57735+0.00000j) |010> # ============..............============ #=====================================================================================================================
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qr = QuantumRegister(3) qc = QuantumCircuit(qr) c3h_gate = HGate().control(2) qc.append(c3h_gate, qr) qc.draw('mpl')
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
import qiskit import numpy as np import networkx as nx import matplotlib.pyplot as plt from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from tsp_qaoa import marina_solution G=nx.Graph() i=1 G.add_node(i,pos=(i,i)) G.add_node(2,pos=(2,2)) G.add_node(3,pos=(1,0)) G.add_edge(1,2,weight=20.5) G.add_edge(1,3,weight=9.8) pos=nx.get_node_attributes(G,'pos') nx.draw(G,pos) labels = nx.get_edge_attributes(G,'weight') nx.draw_networkx_edge_labels(G,pos,edge_labels=labels) def append_zz_term(qc,q1,q2,gamma): qc.cx(q1,q2) qc.rz(2*gamma,q2) qc.cx(q1,q2) def get_cost_circuit(G,gamma): N=G.number_of_nodes() qc=QuantumCircuit(N,N) for i,j in G.edges(): append_zz_term(qc,i,j,gamma) return qc #print(get_cost_circuit(G,0.5)) def append_x_term(qc,q1,beta): qc.rx(2*beta,q1) def get_mixer_operator(G,beta): N=G.number_of_nodes() qc=QuantumCircuit(N,N) for n in G.nodes(): append_x_term(qc,n,beta) return qc #print(get_mixer_operator(G,0.5)) def get_QAOA_circuit(G,beta,gamma): assert(len(beta)==len(gamma)) N=G.number_of_nodes() qc=QuantumCircuit(N,N) qc.h(range(N)) p=len(beta) #aplicamos las p rotaciones for i in range(p): qc=qc.compose(get_cost_circuit(G,gamma[i])) qc=qc.compose(get_mixer_operator(G,beta[i])) qc.barrier(range(N)) qc.measure(range(N),range(N)) return qc print(get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6])) def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} qc=get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6]) backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend) result=job.result() print(invert_counts(result.get_counts())) def maxcut_obj(x,G): cut=0 for i,j in G.edges(): if x[i]!=x[j]: cut = cut-1 return cut print(maxcut_obj("00011",G)) def compute_maxcut_energy(counts,G): energy=0 get_counts=0 total_counts=0 for meas, meas_count in counts.items(): obj_for_meas=maxcut_obj(meas,G) energy+=obj_for_meas*meas_count total_counts+=meas_count return energy/total_counts def get_black_box_objective(G,p): backend=Aer.get_backend('qasm_simulator') def f(theta): beta=theta[:p] gamma=theta[p:] qc=get_QAOA_circuit(G,beta,gamma) counts=execute(qc,backend,seed_simulator=10).result().get_counts() return compute_maxcut_energy(invert_counts(counts),G) return f p=5 obj=get_black_box_objective(G,p) init_point=np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1])#([2,2,1,1,1,1,1,1,1,1]) res_sample=minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) res_sample from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo cantidad_ciudades = 4 pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) pos=nx.spring_layout(G) nx.draw(G,pos) labels = nx.get_edge_attributes(G,'weight') nx.draw_networkx_edge_labels(G,pos,edge_labels=labels) G pos=nx.get_node_attributes(G,'weight') pos labels = nx.get_edge_attributes(G,'weight') labels def funcion_costo(multiplicador_lagrange, cantidad_ciudades, pesos, conexiones ): N = G.number_of_nodes() N_square = N^2 # restriccion 1 for i in range(cantidad_ciudades): cur = sI(N_square) for j in range(num_cities): cur -= D(i, j) ret += cur**2 # retorna el indice de qubit por conversion al problema def quibit_indice(i, l, N): return i * N + l from qiskit.quantum_info.operators import Operator, Pauli # Create an operator XX = Operator(Pauli(label='XX')) # Add to a circuit circ = QuantumCircuit(2, 2) circ.append(XX, [0, 1]) circ.measure([0,1], [0,1]) circ.draw('mpl') # Add to a circuit circ = QuantumCircuit(2, 2) circ.append(a, [0]) #circ.measure([0,1], [0,1]) circ.draw('mpl') a = I - ( 0.5*(I+ Z))**2 a = Operator(a) a.is_unitary() print(I @ Z)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
https://github.com/usamisaori/qLipschitz
usamisaori
import numpy as np from qiskit import QuantumCircuit def createInputCircuit(data): qubits_num = len(data) qcircuit = QuantumCircuit(qubits_num, qubits_num) qubits = qcircuit.qubits for i, d in enumerate(data): qcircuit.rx(d * np.pi, qubits[i]) return qcircuit def createModelCircuit(params): qubits_num = len(params[0]) qcircuit = QuantumCircuit(qubits_num, qubits_num) qubits = qcircuit.qubits for i in range(qubits_num): qcircuit.u3(*params[0][i], qubits[i]) for i in range(qubits_num - 1): qcircuit.cz(qubits[i], qubits[i + 1]) qcircuit.cz(qubits[0], qubits[qubits_num - 1]) for i in range(qubits_num): qcircuit.u3(*params[1][i], qubits[i]) return qcircuit def createCircuit(params, data): input_circuit = createInputCircuit(data) model_circuit = createModelCircuit(params) full_circuit = input_circuit.compose(model_circuit) return full_circuit from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.utils import insert_noise from qiskit.providers.aer.noise import pauli_error, depolarizing_error def createNoiseModel(p, errorType): # QuantumError objects if errorType == 'bit_flip': error = pauli_error([('X', p), ('I', 1 - p)]) elif errorType == 'phase_flip': error = pauli_error([('Z', p), ('I', 1 - p)]) elif errorType == 'depolarizing': error = depolarizing_error(p, num_qubits=1) ## two-qubits quantumError objects if errorType == 'depolarizing': error_2qubits = depolarizing_error(p, num_qubits=2) else: error_2qubits = error.tensor(error) # Add errors to noise model noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, ['u3']) noise_model.add_all_qubit_quantum_error(error_2qubits, ['cz']) return noise_model def createNoisyModelCircuit(params, p, errorType): noise_model = createNoiseModel(p, errorType) model_circuit = createModelCircuit(params) return insert_noise(model_circuit, noise_model)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Needed for functions import numpy as np import time # Import QISKit classes import qiskit from qiskit import QuantumRegister, QuantumCircuit, Aer from qiskit.quantum_info import state_fidelity from qiskit.tools.qi.qi import outer # Tomography functions from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter # Process tomography of a Hadamard gate q = QuantumRegister(1) circ = QuantumCircuit(q) circ.h(q[0]) # Run circuit on unitary simulator to find ideal unitary job = qiskit.execute(circ, Aer.get_backend('unitary_simulator')) ideal_unitary = job.result().get_unitary(circ) # convert to Choi-matrix in column-major convention choi_ideal = outer(ideal_unitary.ravel(order='F')) # Generate process tomography circuits and run on qasm simulator qpt_circs = process_tomography_circuits(circ, q) job = qiskit.execute(qpt_circs, Aer.get_backend('qasm_simulator'), shots=4000) # Extract tomography data so that counts are indexed by measurement configuration qpt_tomo = ProcessTomographyFitter(job.result(), qpt_circs) qpt_tomo.data # MLE Least-Squares tomographic reconstruction t = time.time() choi_lstsq = qpt_tomo.fit(method='lstsq') print('Least-Sq Fitter') print('fit time:', time.time() - t) print('fit fidelity:', state_fidelity(choi_ideal / 2, choi_lstsq / 2)) # CVXOPT Semidefinite-Program tomographic reconstruction t = time.time() choi_cvx = qpt_tomo.fit(method='cvx') print('\nCVXOPT Fitter') print('fit time:', time.time() - t) print('fit fidelity:', state_fidelity(choi_ideal / 2, choi_cvx / 2)) # Process tomography of a Hadamard gate q = QuantumRegister(2) circ = QuantumCircuit(q) circ.swap(q[0], q[1]) # Ideal channel is a unitary ideal_unitary = np.eye(2) choi_ideal = outer(ideal_unitary.ravel(order='F')) # Generate process tomography circuits and run on qasm simulator # We use the optional prepared_qubits kwarg to specify that the prepared qubit was different to measured qubit qpt_circs = process_tomography_circuits(circ, q[1], prepared_qubits=q[0]) job = qiskit.execute(qpt_circs, Aer.get_backend('qasm_simulator'), shots=2000) # Extract tomography data so that counts are indexed by measurement configuration qpt_tomo = ProcessTomographyFitter(job.result(), qpt_circs) qpt_tomo.data # Least-Squares tomographic reconstruction t = time.time() choi_lstsq = qpt_tomo.fit(method='lstsq') print('Least-Sq Fitter') print('fit time:', time.time() - t) print('fit fidelity:', state_fidelity(choi_ideal / 2, choi_lstsq / 2)) # CVXOPT Semidefinite-Program tomographic reconstruction t = time.time() choi_cvx = qpt_tomo.fit(method='cvx') print('\nCVXOPT Fitter') print('fit time:', time.time() - t) print('fit fidelity:', state_fidelity(choi_ideal / 2, choi_cvx / 2)) # Bell-state entangling circuit q = QuantumRegister(2) circ = QuantumCircuit(q) circ.h(q[0]) circ.cx(q[0], q[1]) # Run circuit on unitary simulator to find ideal unitary job = qiskit.execute(circ, Aer.get_backend('unitary_simulator')) ideal_unitary = job.result().get_unitary(circ) # convert to Choi-matrix in column-major convention choi_ideal = outer(ideal_unitary.ravel(order='F')) # Generate process tomography circuits and run on qasm simulator qpt_circs = process_tomography_circuits(circ, q) job = qiskit.execute(qpt_circs, Aer.get_backend('qasm_simulator'), shots=2000) # Extract tomography data so that counts are indexed by measurement configuration qpt_tomo = ProcessTomographyFitter(job.result(), qpt_circs) t = time.time() choi_lstsq = qpt_tomo.fit(method='lstsq') print('Least-Sq Fitter') print('fit time:', time.time() - t) print('fit fidelity:', state_fidelity(choi_ideal / 4, choi_lstsq / 4)) t = time.time() choi_cvx = qpt_tomo.fit(method='cvx') print('\nCVXOPT Fitter') print('fit time:', time.time() - t) print('fit fidelity:', state_fidelity(choi_ideal / 4, choi_cvx / 4)) # Process tomography of a Hadamard gate q = QuantumRegister(1) circ = QuantumCircuit(q) circ.h(q[0]) # Run circuit on unitary simulator to find ideal unitary job = qiskit.execute(circ, Aer.get_backend('unitary_simulator')) ideal_unitary = job.result().get_unitary(circ) # convert to Choi-matrix in column-major convention choi_ideal = outer(ideal_unitary.ravel(order='F')) # Generate process tomography circuits and run on qasm simulator qpt_circs = process_tomography_circuits(circ, q, prep_labels='SIC', prep_basis='SIC') job = qiskit.execute(qpt_circs, Aer.get_backend('qasm_simulator'), shots=2000) # Extract tomography data so that counts are indexed by measurement configuration qpt_tomo = ProcessTomographyFitter(job.result(), qpt_circs, prep_basis='SIC') qpt_tomo.data # MLE Least-Squares tomographic reconstruction t = time.time() choi_lstsq = qpt_tomo.fit(method='lstsq') print('Least-Sq Fitter') print('fit time:', time.time() - t) print('fit fidelity:', state_fidelity(choi_ideal / 2, choi_lstsq / 2)) # CVXOPT Semidefinite-Program tomographic reconstruction t = time.time() choi_cvx = qpt_tomo.fit(method='cvx') print('\nCVXOPT Fitter') print('fit time:', time.time() - t) print('fit fidelity:', state_fidelity(choi_ideal / 2, choi_cvx / 2))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. qiskit_chemistry_dict = { 'problem': {'random_seed': 50}, 'driver': {'name': 'PYQUANTE'}, 'PYQUANTE': {'atoms': '', 'basis': 'sto3g'}, 'operator': {'name': 'hamiltonian', 'qubit_mapping': 'jordan_wigner', 'two_qubit_reduction': False}, 'algorithm': {'name': ''}, 'optimizer': {'name': 'COBYLA', 'maxiter': 10000 }, 'variational_form': {'name': 'UCCSD'}, 'initial_state': {'name': 'HartreeFock'} } molecule = 'H .0 .0 -{0}; H .0 .0 {0}' algorithms = ['VQE', 'ExactEigensolver'] transformations = ['full', 'particle_hole'] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 20 # Number of steps to increase by energies = np.empty([len(transformations), len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) eval_counts = np.empty([len(transformations), steps+1]) print('Processing step __', end='') for i in range(steps+1): print('\b\b{:2d}'.format(i), end='', flush=True) d = start + i*by/steps qiskit_chemistry_dict['PYQUANTE']['atoms'] = molecule.format(d/2) for j in range(len(algorithms)): qiskit_chemistry_dict['algorithm']['name'] = algorithms[j] for k in range(len(transformations)): qiskit_chemistry_dict['operator']['transformation'] = transformations[k] solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[k][j][i] = result['energy'] hf_energies[i] = result['hf_energy'] if algorithms[j] == 'VQE': eval_counts[k][i] = result['algorithm_retvals']['eval_count'] distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print('VQE num evaluations:', eval_counts) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): for k in range(len(transformations)): pylab.plot(distances, energies[k][j], label=algorithms[j]+' + '+transformations[k]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy') pylab.legend(loc='upper right') pylab.plot(distances, np.subtract(hf_energies, energies[0][1]), label='Hartree-Fock') for k in range(len(transformations)): pylab.plot(distances, np.subtract(energies[k][0], energies[k][1]), label='VQE + '+transformations[k]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper left') for k in range(len(transformations)): pylab.plot(distances, eval_counts[k], '-o', label='VQE + ' + transformations[k]) pylab.xlabel('Interatomic distance') pylab.ylabel('Evaluations') pylab.title('VQE number of evaluations') pylab.legend(loc='upper left')
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import sys sys.path.insert(1, '..') # sets the import path to the parent folder import time import datetime import numpy as np from matplotlib import pyplot as plt import qiskit from qiskit import * from qiskit.opflow import X,Z,I from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA from qiskit.opflow import CircuitSampler from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis from qiskit.ignis.mitigation.measurement import complete_meas_cal from scipy import sparse import scipy.sparse.linalg.eigen.arpack as arp from modules.utils import * anti = -1 L = 5 num_trash = 2 name = "ibmq_antiferro-1D-load_bogota-no-optimize" # remove test at the end when running on a real device filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle" print("filename: ", filename, "notebook name: ", name) # where to get the simulated thetas values from? needs to contain a thetas_mitigated array filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_simu_thetas-loss-cost_run2.npz' load = False recompute = False # whether or not to recompute Magnetization, makes sense on device IBMQ.load_account() # this then automatically loads your saved account provider = IBMQ.get_provider(hub='ibm-q-research') device = provider.backend.ibmq_bogota print(device) backend = device #backend = qiskit.providers.aer.AerSimulator.from_backend(device) coupling_map = device.configuration().coupling_map noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates #aqua_globals.random_seed = seed qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed coupling_map=coupling_map, # noise_model=noise_model, measurement_error_mitigation_cls= CompleteMeasFitter, cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes ) basis_gates # Very important, at the moment poorly coded so it needs to come back to this instance all the time ansatz = qiskit.circuit.library.TwoLocal(L,rotation_blocks="ry", entanglement_blocks='cz', entanglement="sca", reps=1) ansatz.draw("mpl") ansatz = qiskit.transpile(ansatz, backend) ansatz.draw("mpl") L = 5 num_trash = 2 anti = -1 VQE_params = np.load(filename + ".npz", allow_pickle=True) pick = np.arange(0,len(VQE_params['gx_list']),3) gx_list = VQE_params['gx_list'][pick] gz_list = VQE_params['gz_list'][pick] opt_params = VQE_params['opt_params'][pick] Qmags = VQE_params["Qmag"][pick] Qen = VQE_params["Qen"][pick] Sen = VQE_params["Sen"][pick] Smags = VQE_params["Smag"][pick] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) if load: temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] verbose=1 if recompute: mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) Qen_executed=np.zeros(len(opt_params), dtype="complex") Qmags_executed=np.zeros(len(opt_params), dtype="complex") for j in range(len(opt_params)): t0 = datetime.datetime.now() gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = ansatz.assign_parameters(opt_params[j]) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags_executed[j] = CircuitSampler(qi).convert(meas_outcome).eval() #https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit #e_outcome = ~StateFn(H) @ StateFn(state) #Qen_executed[j] = CircuitSampler(qi).convert(e_outcome).eval() init_state, E, ham = ising_groundstate(L, anti, np.float64(gx), np.float64(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results print(f"{j+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}") np.savez("data/" + name + "executed_mags-Es.npz",Qmags=Qmags_executed, Qen=Qen_executed, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig, axs = plt.subplots(ncols=2, figsize=(10,5)) ax = axs[0] ax.plot(gx_list, Qmags,"x--", label="noisy VQE simu") ax.plot(gx_list, Smags,"x--", label="ED") ax.set_xscale("log") if recompute: ax.plot(gx_list, Qmags_executed,"x--", label="IBMQ") ax.legend() ############################################################################## ### II - Training ########################################################### ############################################################################## # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1, nums_trash=[1,2]): result = [] nums_compressed = list(range(L)) for trashqubit in nums_trash: nums_compressed.remove(trashqubit) if nums_trash == None: #old way nums_compressed = list(range(L))[:L-num_trash] nums_trash = list(range(L))[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz", nums_trash = [1,2]): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] if nums_trash == None: nums_trash = list(range(L))[-num_trash:] circ = qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, skip_final_rotation_layer=True ).assign_parameters(thetas[:-num_trash]) if insert_barriers: circ.barrier() for i in nums_trash: circ.ry(thetas[i], i) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True): qreg = QuantumRegister(L, 'q') creg = ClassicalRegister(num_trash, 'c') circ = QuantumCircuit(qreg, creg) circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=False)#.assign_parameters(thetas) # difference to bind? if measurement: for i in range(num_trash): circ.measure(qreg[L-i-1], creg[i]) if init_state is not None: if vqe: circ = ansatz.assign_parameters(init_state) + circ # needs to have ansatz defined somewhere in the script else: circ.initialize(init_state, qreg) return circ def feature_encoding(thetas, x): """ thetas: parameters to be optimized, x: Ising model parameter (eg. field) """ new_thetas = [] thetas = thetas.reshape((-1,2)) for theta in thetas: new_thetas.append(theta[0] * x + theta[1]) return new_thetas def calibrate_circuit(L, num_trash,shots=1000): qreg = QuantumRegister(L, 'q') # obtain calibration matrix qubit_list = [L-i-1 for i in range(num_trash)] # only need to calibrate the trash qubits circlabel = f'mcal_{datetime.datetime.now()}' meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel=circlabel) cal_job = backend.run(meas_calibs, shots=shots) #, noise_model=noise_model cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel=circlabel) print(circlabel, meas_fitter.cal_matrix) return meas_fitter def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100, meas_fitter = None): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) tcirc = qiskit.transpile(circ, backend) # Execute the circuit job_sim = backend.run(tcirc, shots=shots) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible result = job_sim.result() # Results without mitigation counts = result.get_counts() if meas_fitter != None: # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(result) counts = mitigated_results.get_counts(0) return counts meas_fitter = calibrate_circuit(L, num_trash) phis = opt_params # translate to Rikes naming gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ if vqe: init_state = phis[p] else: J, gx, gz = p init_state, _ = ising_groundstate(L, J, gx, gz) if param_encoding: thetas = feature_encoding(thetas, x) out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter) cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0) return cost/shots def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None): """ Optimizes circuit """ cost = 0. n_samples = len(ising_params) for i, p in enumerate(ising_params): if param_encoding: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i], meas_fitter=meas_fitter) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, meas_fitter=meas_fitter) return cost/n_samples def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None, meas_fitter=None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (2*L+2) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x))) counts, values, accepted = [], [], [] def store_intermediate_result(eval_count, parameters, mean, std, ac): # counts.append(eval_count) values.append(mean) accepted.append(ac) # Initialize optimizer if pick_optimizer == "cobyla": optimizer = COBYLA(maxiter=max_iter, tol=0.0001) if pick_optimizer == "adam" or pick_optimizer == "ADAM": optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter) # optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08) if pick_optimizer == "spsa" or pick_optimizer == None: optimizer = SPSA(maxiter=max_iter, #blocking=True, callback=store_intermediate_result, learning_rate=0.3, perturbation=0.1 ) # recommended from qiskit (first iteraction takes quite long) # to reduce time figure out optimal learning rate and perturbation in advance start_time = time.time() ret = optimizer.optimize( num_vars=len(thetas), objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted def run_inference(thetas, shots=1000, L=5, meas_fitter=None): points = 50 J = -1.0 x,y = np.meshgrid(gx_vals, gz_vals) cost = np.zeros((len(gx_vals) * len(gz_vals))) Smags = np.zeros((len(gx_vals) * len(gz_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost phys_params = [-1] thetas_opt_raw = np.load(filename_simulated_thetas, allow_pickle=True)["thetas_mitigated"] # Inference cost_raw = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost_raw[i] = cost_function_single(thetas_opt_raw, L, num_trash, i, shots=shots, meas_fitter=None) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {p[0]:.2f}, gz = {p[1]:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") thetas_opt_raw = thetas_opt_mitigated.copy() cost_raw = cost_mitigated.copy() thetas_opt_mitigated = np.load(filename_simulated_thetas, allow_pickle=True)["thetas_mitigated"] # Inference cost_mitigated = np.zeros((len(gx_vals))) shots = 1000 for i,p in enumerate(list(zip(gxs, gzs))): t0 = datetime.datetime.now() cost_mitigated[i] = cost_function_single(thetas_opt_mitigated, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something if not i%verbose: print(f"{i+1} / {len(opt_params)}, gx = {p[0]:.2f}, gz = {p[1]:.2f}, time : {verbose*(datetime.datetime.now() - t0)}") np.savez("data/" + name + "_thetas-loss-cost_run2", cost_mitigated=cost_mitigated, thetas_mitigated=thetas_opt_mitigated, cost_raw=cost_raw, thetas_raw=thetas_opt_raw, ) fig, axs = plt.subplots(ncols=2,figsize=(12,5)) ax = axs[0] ax.set_title("Raw results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_raw"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, Qmags,"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta") ax = axs[1] ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, Qmags,"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta") fig, ax = plt.subplots(ncols=1,figsize=(6,5)) ax.set_title("Mitigated results") cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_raw"] ax.plot(gx_list, cost,".:", label="raw output") ax.plot(gx_list, abs(Qmags),"x--", color="tab:orange", label="Qmag") ax.set_xscale("log") for p in phys_params: ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) circuit = dag_to_circuit(dag) circuit.draw('mpl')
https://github.com/baronefr/perceptron-dqa
baronefr
import numpy as np from tqdm import tqdm import qiskit.quantum_info as qi from qiskit import QuantumCircuit, QuantumRegister, AncillaRegister GPU = True from importlib.util import find_spec if GPU: if find_spec('cupy') is not None: import cupy as ncp else: print('Selected device is GPU but cupy is not installed, falling back to numpy') import numpy as ncp else: import numpy as ncp #################################### #### GET PERCEPTRON HAMILTONIAN #### #################################### def kronecker_prod(operators): result = operators[0] for op in operators[1:]: result = np.kron(result, op) return result def ReLU(x): return x * (x > 0) def H_perc_nobatch(data, labels): n_data, n = data.shape sigma_z = np.diag([1., -1.]) identity = np.diag([1., 1.]) h_perc = np.zeros((2**n, 2**n), dtype='float32') for i in tqdm(range(n_data), desc='Constructing H_perc'): op = np.zeros((2**n, 2**n), dtype='float32') for j in range(n): op += kronecker_prod([identity]*j+[data[i, j] * sigma_z]+[identity]*(n-j-1)) h_perc += ReLU(-labels[i]*op) del op return (h_perc / np.sqrt(n)).astype('complex') def H_perc_diag(data, labels): ## ASSUMING H_PERC IS DIAGONAL, WHICH IS IN THE COMPUTATIONAL BASIS ## n_data, n = data.shape identity = np.ones((2,), 'float32') sigma_z = np.array([1., -1.]) h_perc = np.zeros((2**n,), dtype='float32') for i in tqdm(range(n_data), desc='Constructing H_perc'): op = np.zeros((2**n,), dtype='float32') for j in range(n): op += kronecker_prod([identity]*j+[data[i, j] * sigma_z]+[identity]*(n-j-1)) h_perc += ReLU(-labels[i]*op) del op return ncp.array((h_perc / np.sqrt(n)).astype('complex128')) ######################## ##### LOSS TRACKER ##### ######################## class LossTracker: def __init__(self, num_qubits, num_ancillae, init_state): self.n_qubits = num_qubits self.n_ancillae = num_ancillae if type(init_state) is qi.Statevector: self._statevecs = [init_state] elif type(init_state) is QuantumCircuit: self._statevecs = [qi.Statevector.from_instruction(init_state)] else: print('type', type(init_state), 'of init_state is not valid') self._h_perc = None self._little_endian = True self._statevecs_arr = None def track(self, qc, compose=True): if compose: # create a copy of the current circuit internally self.current_qc = QuantumCircuit(QuantumRegister(self.n_qubits), AncillaRegister(self.n_ancillae)) # compose the circuit if type(qc) is list: for circuit in qc: self.current_qc.compose(circuit, inplace=True) elif type(qc) is QuantumCircuit: self.current_qc.compose(qc, inplace=True) else: print('Error: type of qc is', type(qc)) return else: self.current_qc = qc # track the state self._statevecs.append(self._statevecs[-1].evolve(self.current_qc)) del self.current_qc @property def statevecs(self): return self._statevecs @statevecs.setter def set_statevecs(self, value): self._statevecs = [value] @property def h_perc(self): return self._h_perc def reset(self, num_qubits=None, num_ancillae=None): self._statevecs.clear() self._statevecs_arr = None if num_qubits: self.n_qubits = num_qubits if num_ancillae: self.n_ancillae = num_ancillae def finalize(self): ## convert statevectors to arrays, keep only qubits of interest arr_list = [] for state in tqdm(self._statevecs, desc='finalizing LossTracker'): out_red = qi.partial_trace(state, range(self.n_qubits, self.n_qubits + self.n_ancillae)) prob, st_all = ncp.linalg.eigh(ncp.array(out_red.data)) idx = ncp.argmax(prob) arr_list.append(st_all[:, idx].copy()) del out_red, prob, st_all, idx self._statevecs_arr = ncp.stack(arr_list) del arr_list def finalize_opt(self): ## instead of tracing outs qubit we can simply modify the hamiltonian by putting ## identities on the ancillary qubits, remembering that qiskit uses little endians. self._statevecs_arr = ncp.array(np.stack([state.data for state in self._statevecs])) def __loss(self, statevec, h_perc): return ncp.vdot(statevec, h_perc * statevec) def get_losses(self, data, little_endian=True, labels=None): if len(self._statevecs) == 0: print('Error: no statevectors has been tracked down, please call track() before') return if labels is None: labels = np.ones((data.shape[0],)) if self._statevecs_arr is None: print('LossTracker was not finalized, finalizing...') self.finalize() print('Done!') if self._h_perc is None or self._little_endian != little_endian: if little_endian: self._h_perc = H_perc_diag(data, labels) else: # invert data components if the circuit was constructed in big endian mode # NOT SURE IF THIS WORKS self._h_perc = H_perc_diag(data[:,::-1], labels) self._little_endian = little_endian result = ncp.real_if_close(ncp.apply_along_axis(self.__loss, axis=1, arr=self._statevecs_arr, h_perc=self._h_perc)) if type(result) is np.ndarray: return result else: return result.get() def get_losses_opt(self, data, little_endian=True, labels=None): if len(self._statevecs) == 0: print('Error: no statevectors has been tracked down, please call track() before') return if labels is None: labels = np.ones((data.shape[0],)) if self._statevecs_arr is None: print('LossTracker was not finalized, finalizing...') self.finalize_opt() print('Done!') if self._h_perc is None or self._little_endian != little_endian: if little_endian: self._h_perc = kronecker_prod([ncp.ones((2,))]*self.n_ancillae + [H_perc_diag(data, labels)]) else: # invert data components if the circuit was constructed in big endian mode # NOT SURE IF THIS WORKS self._h_perc = kronecker_prod([ncp.ones((2,))]*self.n_ancillae + [H_perc_diag(data[:,::-1], labels)]) self._little_endian = little_endian result = ncp.real_if_close(ncp.apply_along_axis(self.__loss, axis=1, arr=self._statevecs_arr, h_perc=self._h_perc)) if type(result) is np.ndarray: return result else: return result.get() def get_edensity(self, data, little_endian=True, opt=True, labels=None): if opt: losses = self.get_losses_opt(data, little_endian=little_endian, labels=labels) else: losses = self.get_losses(data, little_endian=little_endian, labels=labels) e0 = np.real_if_close(np.sort(self._h_perc if type(self._h_perc) is np.ndarray else self._h_perc.get())[0]) self.e0 = e0 return (losses-e0) / data.shape[1] if __name__ == '__main__': # example code def your_evolution(p, num_qubits, num_ancillae): # implement yout evolution here qc = QuantumCircuit(num_qubits+num_ancillae) if p == 1: qc.h(range(num_qubits)) if p == 2: qc.h(range(num_qubits)) qc.x(range(num_qubits, num_qubits+num_ancillae)) if p == 3: qc.x( 3) if p == 4: qc.x(2) return qc N_data = 3 N_feat = 4 data = np.array([[1., 1., 1., 1.], [1., -1., 1., -1.], [1., -1., 1., 1.]]) labels = np.ones((N_data, )) P = 4 num_qubits = 4 num_ancillae = 2 qc_tot = QuantumCircuit(num_qubits + num_ancillae) loss_tracker = LossTracker(num_qubits, num_ancillae, init_state=qc_tot) # apply evoltion for p in range(P): qc = your_evolution(p+1, num_qubits, num_ancillae) loss_tracker.track(qc, compose=True) qc_tot = qc_tot.compose(qc) qc_tot.draw() print(loss_tracker.get_losses(data, little_endian=True))
https://github.com/NTU-ALComLab/SliQSim-Qiskit-Interface
NTU-ALComLab
# Import tools from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute from qiskit_sliqsim_provider import SliQSimProvider # Initiate SliQSim Provider provider = SliQSimProvider() # Construct a quantum circuit: 2-qubit bell-state qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr, cr) # Read a circuit from a .qasm file # qc = QuantumCircuit.from_qasm_file("../SliQSim/examples/bell_state.qasm") # Get the backend of sampling simulation backend = provider.get_backend('sampling') # Get the backend of statevector simulation # backend = provider.get_backend('all_amplitude') # Execute simulation job = execute(qc, backend=backend, shots=1024, optimization_level=0) # Obtain and print the results result = job.result() print(result.get_counts(qc)) # print(result.get_statevector(qc))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qr = QuantumRegister(3) qc = QuantumCircuit(qr) c3h_gate = HGate().control(2) qc.append(c3h_gate, qr) qc.draw('mpl')
https://github.com/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, 200e-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 General Gaussian Waveform # Helper function that returns a lifted Gaussian symbolic equation. def lifted_gaussian( t: sym.Symbol, center, t_zero, sigma, ) -> sym.Expr: t_shifted = (t - center).expand() t_offset = (t_zero - center).expand() gauss = sym.exp(-((t_shifted / sigma) ** 2) / 2) offset = sym.exp(-((t_offset / sigma) ** 2) / 2) return (gauss - offset) / (1 - offset) # Structure for Constructing New Pulse Waveform _t, _duration, _amp, _sigma, _angle = sym.symbols("t, duration, amp, sigma, angle") _center = _duration / 2 envelope_expr = ( _amp * sym.exp(sym.I * _angle) * lifted_gaussian(_t, _center, _duration + 1, _sigma) ) gaussian_pulse = pulse.ScalableSymbolicPulse( pulse_type="Gaussian", duration=160, amp=0.3, angle=0, parameters={"sigma": 40}, envelope=envelope_expr, constraints=_sigma > 0, valid_amp_conditions=sym.Abs(_amp) <= 1.0, ) gaussian_pulse.draw() # 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 # However we can equivalently use our own custom defined symbolic pulse special_pulse = pulse.Drag( duration=160, 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 sim_func(params): 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=y0, t_eval=t_linspace, signals=signals, rtol=rtol, atol=atol, convert_results=False, method='jax_odeint' ) return results.y.data fast_func = jit(vmap(sim_func)) batchsize = 400 amp_vals = jnp.linspace(0.0, 0.99, batchsize, dtype=jnp.float64).reshape(-1, 1) sigma_vals = jnp.linspace(1, 40, batchsize, dtype=jnp.int8).reshape(-1, 1) freq_vals = jnp.linspace(0.0, 0.99, batchsize, dtype=jnp.float64).reshape(-1, 1) * 1e6 batch_params = jnp.concatenate((amp_vals, sigma_vals, freq_vals), axis=-1) print(f"Batched Params Shape: {batch_params.shape}") res = fast_func(batch_params) print(res) print(res.shape) # Timing the fast jit + vmap batched simulation %timeit fast_func(batch_params).block_until_ready # Timing a standard simulation without jitting or vmapping %timeit sim_func(batch_params[200])
https://github.com/QuTech-Delft/quantuminspire
QuTech-Delft
""" Quantum Inspire SDK Copyright 2022 QuTech Delft 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 https://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 copy import unittest from unittest.mock import Mock import numpy as np import qiskit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.compiler import assemble, transpile from qiskit.circuit import Instruction from quantuminspire.qiskit.circuit_parser import CircuitToString from quantuminspire.qiskit.backend_qx import QuantumInspireBackend from quantuminspire.qiskit.measurements import Measurements from quantuminspire.exceptions import ApiError class TestQiCircuitToString(unittest.TestCase): @staticmethod def _generate_cqasm_from_circuit(circuit, full_state_projection=True, transpile_first=False): run_config_dict = {'shots': 25, 'memory': True} configuration = copy.copy(QuantumInspireBackend.DEFAULT_CONFIGURATION) if transpile_first: # qiskit transpiler expects coupling map configuration.simulator = False configuration.coupling_map = [[0, 1], [0, 2], [1, 3], [2, 3]] backend = QuantumInspireBackend(Mock(), Mock(), configuration) if transpile_first: circuit = transpile(circuit, backend=backend) qobj = assemble(circuit, backend, **run_config_dict) experiment = qobj.experiments[0] measurements = Measurements.from_experiment(experiment) result = backend._generate_cqasm(experiment, measurements, full_state_projection) return result @staticmethod def _generate_cqasm_from_instructions(instructions, number_of_qubits=2, full_state_projection=True): """ Needed to create invalid qiskit circuits for triggering Exceptions """ experiment_dict = {'instructions': instructions, 'header': {'n_qubits': number_of_qubits, 'memory_slots': number_of_qubits, 'compiled_circuit_qasm': ''}, 'config': {'coupling_map': 'all-to-all', 'basis_gates': 'x,y,z,h,rx,ry,rz,s,cx,ccx,p,id,snapshot', 'n_qubits': number_of_qubits}} experiment = qiskit.qobj.QasmQobjExperiment.from_dict(experiment_dict) for instruction in experiment.instructions: if hasattr(instruction, 'params'): # convert params to params used in qiskit instructions qiskit_instruction = Instruction('dummy', 0, 0, instruction.params) instruction.params = qiskit_instruction.params measurements = Measurements.from_experiment(experiment) simulator = QuantumInspireBackend(Mock(), Mock()) result = simulator._generate_cqasm(experiment, measurements, full_state_projection) return result def test_generate_cqasm_with_entangle_algorithm(self): q = QuantumRegister(2) b = ClassicalRegister(2) circuit = QuantumCircuit(q, b) circuit.h(q[0]) circuit.cx(q[0], q[1]) circuit.measure(q[0], b[0]) circuit.measure(q[1], b[1]) result = self._generate_cqasm_from_circuit(circuit) expected = "version 1.0\n" \ "# cQASM generated by QI backend for Qiskit\n" \ "qubits 2\n" \ "H q[0]\n" \ "CNOT q[0], q[1]\n" self.assertEqual(result, expected) def test_generate_cqasm_correct_output_controlled_z(self): qc = QuantumCircuit(2, 2) qc.cz(0, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('CZ q[0], q[1]\n' in result) def test_generate_cqasm_correct_output_conditional_controlled_z(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.cz(0, 1).c_if(c, 14) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[0]\nC-CZ b[0,1,2,3], q[0], q[1]\nnot b[0]\n' in result) def test_generate_cqasm_correct_output_controlled_not(self): qc = QuantumCircuit(2, 2) qc.cx(0, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('CNOT q[0], q[1]\n' in result) def test_generate_cqasm_correct_output_conditional_controlled_not(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.cx(0, 1).c_if(c, 14) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[0]\nC-CNOT b[0,1,2,3], q[0], q[1]\nnot b[0]\n' in result) def test_generate_cqasm_correct_output_toffoli(self): qc = QuantumCircuit(3, 3) qc.ccx(0, 1, 2) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Toffoli q[0], q[1], q[2]\n' in result) def test_generate_cqasm_correct_output_conditional_toffoli(self): q = QuantumRegister(8, "q") c = ClassicalRegister(8, "c") qc = QuantumCircuit(q, c, name="test") qc.ccx(0, 1, 2).c_if(c, 14) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[0,4,5,6,7]\nC-Toffoli b[0,1,2,3,4,5,6,7], q[0], q[1], q[2]\nnot b[0,4,5,6,7]\n' in result) def test_generate_cqasm_correct_output_measure(self): qc = QuantumCircuit(2, 2) qc.measure(0, 0) result = self._generate_cqasm_from_circuit(qc) measure_line = 'measure q[0]\n' self.assertTrue(measure_line not in result) def test_generate_cqasm_correct_output_measure_q0_non_fsp(self): qc = QuantumCircuit(2, 2) qc.measure(0, 0) result = self._generate_cqasm_from_circuit(qc, False) measure_line = 'measure q[0]\n' self.assertTrue(measure_line in result) def test_generate_cqasm_correct_output_measure_q1_non_fsp(self): qc = QuantumCircuit(2, 2) qc.measure(1, 0) result = self._generate_cqasm_from_circuit(qc, False) measure_line = 'measure q[1]\n' self.assertTrue(measure_line in result) def test_generate_cqasm_correct_output_hadamard(self): qc = QuantumCircuit(2, 2) qc.h(0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('H q[0]\n' in result) def test_generate_cqasm_correct_output_conditional_hadamard(self): q = QuantumRegister(8, "q") c = ClassicalRegister(8, "c") qc = QuantumCircuit(q, c, name="test") qc.h(0).c_if(c, 14) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[0,4,5,6,7]\nC-H b[0,1,2,3,4,5,6,7], q[0]\nnot b[0,4,5,6,7]\n' in result) def test_generate_cqasm_correct_output_barrier(self): qc = QuantumCircuit(2, 2) qc.barrier(0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('barrier q[0]\n' in result) def test_generate_cqasm_correct_output_barrier_multiple_qubits(self): q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(4, "q2") c1 = ClassicalRegister(2, "c1") c2 = ClassicalRegister(4, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.barrier(q1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('barrier q[0,1]\n' in result) qc.barrier(q2) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('barrier q[2,3,4,5]\n' in result) def test_generate_cqasm_correct_output_barrier_all_qubits(self): q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(4, "q2") c1 = ClassicalRegister(2, "c1") c2 = ClassicalRegister(4, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.barrier() result = self._generate_cqasm_from_circuit(qc) self.assertTrue('barrier q[0,1,2,3,4,5]\n' in result) def test_generate_cqasm_correct_output_delay_all_qubits(self): q1 = QuantumRegister(1, "q1") q2 = QuantumRegister(2, "q2") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(2, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.delay(1.0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('wait q[0], 1\n' in result) self.assertTrue('wait q[1], 1\n' in result) self.assertTrue('wait q[2], 1\n' in result) def test_generate_cqasm_correct_output_delay_qarg(self): q1 = QuantumRegister(1, "q1") q2 = QuantumRegister(2, "q2") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(2, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.delay(1, q2) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('wait q[1], 1\n' in result) self.assertTrue('wait q[2], 1\n' in result) # float is translated to int qc.delay(2.0, q1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('wait q[0], 2\n' in result) def test_generate_cqasm_correct_output_delay_units_in_dt(self): q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") c1 = ClassicalRegister(2, "c1") c2 = ClassicalRegister(2, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.delay(1.0, q1, unit="dt") result = self._generate_cqasm_from_circuit(qc) self.assertTrue('wait q[0], 1\n' in result) self.assertTrue('wait q[1], 1\n' in result) qc.delay(2, q1, unit="dt") result = self._generate_cqasm_from_circuit(qc) self.assertTrue('wait q[0], 2\n' in result) self.assertTrue('wait q[1], 2\n' in result) def test_generate_cqasm_correct_output_delay_units_in_s(self): # we need to transpile first to let the circuit convert the delay to seconds q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") c1 = ClassicalRegister(2, "c1") c2 = ClassicalRegister(2, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.delay(1.1, q1, "ms") result = self._generate_cqasm_from_circuit(qc, transpile_first=True) self.assertTrue('wait q[0], 0\n' in result) self.assertTrue('wait q[1], 0\n' in result) qc.delay(0.9, q2, "ns") result = self._generate_cqasm_from_circuit(qc, transpile_first=True) self.assertTrue('wait q[2], 0\n' in result) self.assertTrue('wait q[3], 0\n' in result) qc.delay(1.0, unit="s") result = self._generate_cqasm_from_circuit(qc, transpile_first=True) self.assertTrue('wait q[0], 1\n' in result) self.assertTrue('wait q[1], 1\n' in result) self.assertTrue('wait q[2], 1\n' in result) self.assertTrue('wait q[3], 1\n' in result) def test_generate_cqasm_correct_output_reset_qubit(self): q1 = QuantumRegister(1, "q1") q2 = QuantumRegister(2, "q2") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(2, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.reset(q1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('prep_z q[0]\n' in result) def test_generate_cqasm_correct_output_reset_qubits(self): q1 = QuantumRegister(1, "q1") q2 = QuantumRegister(2, "q2") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(2, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.reset(q2) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('prep_z q[1]\nprep_z q[2]\n' in result) def test_generate_cqasm_correct_output_identity(self): qc = QuantumCircuit(2, 2) qc.id(0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('I q[0]\n' in result) def test_generate_cqasm_correct_output_conditional_identity(self): q = QuantumRegister(8, "q") c = ClassicalRegister(8, "c") qc = QuantumCircuit(q, c, name="test") qc.id(0).c_if(c, 14) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[0,4,5,6,7]\nC-I b[0,1,2,3,4,5,6,7], q[0]\nnot b[0,4,5,6,7]\n' in result) def test_generate_cqasm_correct_output_gate_s(self): qc = QuantumCircuit(2, 2) qc.s(1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('S q[1]\n' in result) def test_generate_cqasm_correct_output_conditional_gate_s(self): q = QuantumRegister(9, "q") c = ClassicalRegister(9, "c") qc = QuantumCircuit(q, c, name="test") qc.s(2).c_if(c, 11) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,4,5,6,7,8]\nC-S b[0,1,2,3,4,5,6,7,8], q[2]\nnot b[2,4,5,6,7,8]\n' in result) def test_generate_cqasm_correct_output_gate_sdag(self): qc = QuantumCircuit(3, 3) qc.sdg(2) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Sdag q[2]\n' in result) def test_generate_cqasm_correct_output_conditional_gate_sdag(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.sdg(0).c_if(c, 14) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[0]\nC-Sdag b[0,1,2,3], q[0]\nnot b[0]\n' in result) def test_generate_cqasm_correct_output_gate_swap(self): qc = QuantumCircuit(4, 4) qc.swap(2, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('SWAP q[2], q[3]\n' in result) def test_generate_cqasm_correct_output_conditional_gate_swap(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.swap(0, 1).c_if(c, 14) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[0]\nC-SWAP b[0,1,2,3], q[0], q[1]\nnot b[0]\n' in result) def test_generate_cqasm_correct_output_gate_t(self): qc = QuantumCircuit(3, 3) qc.t(2) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('T q[2]\n' in result) def test_generate_cqasm_correct_output_conditional_gate_t(self): q = QuantumRegister(9, "q") c = ClassicalRegister(9, "c") qc = QuantumCircuit(q, c, name="test") qc.t(1).c_if(c, 11) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,4,5,6,7,8]\nC-T b[0,1,2,3,4,5,6,7,8], q[1]\nnot b[2,4,5,6,7,8]\n' in result) def test_generate_cqasm_correct_output_gate_tdag(self): qc = QuantumCircuit(3, 3) qc.tdg(2) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Tdag q[2]\n' in result) def test_generate_cqasm_correct_output_conditional_gate_tdag(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.tdg(0).c_if(c, 14) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[0]\nC-Tdag b[0,1,2,3], q[0]\nnot b[0]\n' in result) def test_generate_cqasm_correct_output_gate_x(self): qc = QuantumCircuit(2, 2) qc.x(0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('X q[0]\n' in result) def test_generate_cqasm_correct_output_conditional_gate_x(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.x(0).c_if(c, 14) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[0]\nC-X b[0,1,2,3], q[0]\nnot b[0]\n' in result) def test_generate_cqasm_correct_output_gate_y(self): qc = QuantumCircuit(2, 2) qc.y(0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Y q[0]\n' in result) def test_generate_cqasm_correct_output_conditional_gate_y(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.y(0).c_if(c, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[1,2,3]\nC-Y b[0,1,2,3], q[0]\nnot b[1,2,3]\n' in result) def test_generate_cqasm_correct_output_gate_z(self): qc = QuantumCircuit(2, 2) qc.z(0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Z q[0]\n' in result) def test_generate_cqasm_correct_output_conditional_gate_z(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.z(0).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Z b[0,1,2,3], q[0]\nnot b[2,3]\n' in result) def test_generate_cqasm_correct_output_gate_u(self): qc = QuantumCircuit(2, 2) qc.u(0, 0, np.pi / 2, 0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[0], 1.570796\n' in result) qc = QuantumCircuit(2, 2) qc.u(-np.pi / 2, 0, 0, 0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Ry q[0], -1.570796\n' in result) qc = QuantumCircuit(2, 2) qc.u(np.pi / 4, np.pi / 2, -np.pi / 2, 0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[0], -1.570796\nRy q[0], 0.785398\nRz q[0], 1.570796\n' in result) qc = QuantumCircuit(2, 2) qc.u(0.123456, 0.654321, -0.333333, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[1], -0.333333\nRy q[1], 0.123456\nRz q[1], 0.654321\n' in result) def test_generate_cqasm_correct_output_conditional_gate_u(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(0, 0, np.pi / 2, 0).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[0], 1.570796\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(-np.pi / 2, 0, 0, 0).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Ry b[0,1,2,3], q[0], -1.570796\nnot b[2,3]' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(np.pi / 4, np.pi / 2, -np.pi / 2, 0).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[0], -1.570796\nC-Ry b[0,1,2,3], q[0], 0.785398\nC-Rz b[0,1,2,3],' ' q[0], 1.570796\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(0.123456, 0.654321, -0.333333, 1).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[1], -0.333333\nC-Ry b[0,1,2,3], q[1], 0.123456\nC-Rz b[0,1,2,3],' ' q[1], 0.654321\nnot b[2,3]\n' in result) def test_generate_cqasm_correct_output_gate_p(self): qc = QuantumCircuit(2, 2) qc.p(np.pi / 2, 0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[0], 1.570796\n' in result) qc = QuantumCircuit(2, 2) qc.p(np.pi / 4, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[1], 0.785398\n' in result) qc = QuantumCircuit(3, 3) qc.p(-np.pi / 4, 2) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[2], -0.785398\n' in result) qc = QuantumCircuit(3, 3) qc.p(0.123456, 2) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[2], 0.123456\n' in result) qc = QuantumCircuit(2, 2) qc.p(0, 0) result = self._generate_cqasm_from_circuit(qc) self.assertFalse('q[0]' in result) def test_generate_cqasm_correct_output_conditional_gate_p(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.p(np.pi / 2, 0).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[0], 1.570796\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.p(np.pi / 4, 1).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[1], 0.785398\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.p(-np.pi / 4, 2).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[2], -0.785398\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.p(0.123456, 2).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[2], 0.123456\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.p(0, 0).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertFalse('q[0]' in result) def test_generate_cqasm_correct_output_gate_u2(self): # Qiskit u2 is deprecated from 0.16.0. u2(a, b) -> u(pi/2, a, b) qc = QuantumCircuit(2, 2) qc.u(np.pi / 2, np.pi, np.pi / 2, 0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[0], 1.570796\nRy q[0], 1.570796\nRz q[0], 3.141593\n' in result) qc = QuantumCircuit(2, 2) qc.u(np.pi / 2, 0, np.pi, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[1], 3.141593\nRy q[1], 1.570796\n' in result) qc = QuantumCircuit(3, 3) qc.u(np.pi / 2, 0.123456, -0.654321, 2) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[2], -0.654321\nRy q[2], 1.570796\nRz q[2], 0.123456\n' in result) qc = QuantumCircuit(3, 3) qc.u(np.pi / 2, 0, 0, 0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Ry q[0], 1.570796\n' in result) def test_generate_cqasm_correct_output_conditional_gate_u2(self): # Qiskit u2 is deprecated from 0.16.0. u2(a, b) -> u(pi/2, a, b) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(np.pi / 2, np.pi, np.pi / 2, 0).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[0], 1.570796\nC-Ry b[0,1,2,3], q[0], 1.570796\nC-Rz b[0,1,2,3], q[0],' ' 3.141593\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(np.pi / 2, 0, np.pi, 1).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[1], 3.141593\nC-Ry b[0,1,2,3], q[1], 1.570796\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(np.pi / 2, 0.123456, -0.654321, 2).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[2], -0.654321\nC-Ry b[0,1,2,3], q[2], 1.570796\nC-Rz b[0,1,2,3], q[2],' ' 0.123456\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(np.pi / 2, 0, 0, 0).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Ry b[0,1,2,3], q[0], 1.570796\nnot b[2,3]\n' in result) def test_generate_cqasm_correct_output_gate_u3(self): # Qiskit u3 is deprecated from 0.16.0. u3 -> u qc = QuantumCircuit(2, 2) qc.u(1, 2, 3, 0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[0], 3.000000\nRy q[0], 1.000000\nRz q[0], 2.000000\n' in result) qc = QuantumCircuit(2, 2) qc.u(0.123456, 0.654321, -0.333333, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[1], -0.333333\nRy q[1], 0.123456\nRz q[1], 0.654321\n' in result) qc = QuantumCircuit(2, 2) qc.u(0, 0.654321, 0, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[1], 0.654321\n' in result) qc = QuantumCircuit(3, 3) qc.u(0.654321, 0, 0, 2) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Ry q[2], 0.654321\n' in result) qc = QuantumCircuit(2, 2) qc.u(0, 0, 0, 0) result = self._generate_cqasm_from_circuit(qc) self.assertFalse('q[0]' in result) def test_generate_cqasm_correct_output_conditional_gate_u3(self): # Qiskit u3 is deprecated from 0.16.0. u3 -> u q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(1, 2, 3, 0).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[0], 3.000000\nC-Ry b[0,1,2,3], q[0], 1.000000\nC-Rz b[0,1,2,3], q[0],' ' 2.000000\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(0.123456, 0.654321, -0.333333, 1).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[1], -0.333333\nC-Ry b[0,1,2,3], q[1], 0.123456\nC-Rz b[0,1,2,3], q[1],' ' 0.654321\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(0, 0.654321, 0, 1).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Rz b[0,1,2,3], q[1], 0.654321\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(0.654321, 0, 0, 2).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Ry b[0,1,2,3], q[2], 0.654321\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.u(0, 0, 0, 0).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertFalse('q[0]' in result) def test_generate_cqasm_correct_output_sympy_special_cases(self): # Zero qc = QuantumCircuit(2, 2) qc.rx(0, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rx q[1], 0.000000\n' in result) # One qc = QuantumCircuit(2, 2) qc.rx(1, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rx q[1], 1.000000\n' in result) # Integer qc = QuantumCircuit(2, 2) qc.rx(2, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rx q[1], 2.000000\n' in result) # NegativeOne qc = QuantumCircuit(2, 2) qc.rx(-1, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rx q[1], -1.000000\n' in result) # Float qc = QuantumCircuit(2, 2) qc.rx(np.pi / 2, 0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rx q[0], 1.570796\n' in result) def test_generate_cqasm_correct_output_rotation_x(self): qc = QuantumCircuit(2, 2) qc.rx(np.pi / 2, 0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rx q[0], 1.570796\n' in result) qc = QuantumCircuit(2, 2) qc.rx(0.123456, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rx q[1], 0.123456\n' in result) def test_generate_cqasm_correct_output_conditional_rotation_x(self): q = QuantumRegister(8, "q") c = ClassicalRegister(8, "c") qc = QuantumCircuit(q, c, name="test") qc.rx(np.pi / 2, 0).c_if(c, 14) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[0,4,5,6,7]\nC-Rx b[0,1,2,3,4,5,6,7], q[0], 1.570796\nnot b[0,4,5,6,7]\n' in result) q = QuantumRegister(8, "q") c = ClassicalRegister(8, "c") qc = QuantumCircuit(q, c, name="test") qc.rx(0.123456, 1).c_if(c, 14) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[0,4,5,6,7]\nC-Rx b[0,1,2,3,4,5,6,7], q[1], 0.123456\nnot b[0,4,5,6,7]\n' in result) def test_generate_cqasm_correct_output_rotation_y(self): qc = QuantumCircuit(2, 2) qc.ry(np.pi / 2, 0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Ry q[0], 1.570796\n' in result) qc = QuantumCircuit(2, 2) qc.ry(0.654321, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Ry q[1], 0.654321\n' in result) def test_generate_cqasm_correct_output_conditional_rotation_y(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.ry(np.pi / 2, 0).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Ry b[0,1,2,3], q[0], 1.570796\nnot b[2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.ry(0.654321, 1).c_if(c, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[2,3]\nC-Ry b[0,1,2,3], q[1], 0.654321\nnot b[2,3]\n' in result) def test_generate_cqasm_correct_output_rotation_z(self): qc = QuantumCircuit(2, 2) qc.rz(np.pi / 2, 0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[0], 1.570796\n' in result) qc = QuantumCircuit(2, 2) qc.rz(-np.pi / 2, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('Rz q[1], -1.570796\n' in result) def test_generate_cqasm_correct_output_conditional_rotation_z(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.rz(np.pi / 2, 0).c_if(c, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[1,2,3]\nC-Rz b[0,1,2,3], q[0], 1.570796\nnot b[1,2,3]\n' in result) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.rz(-np.pi / 2, 1).c_if(c, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[1,2,3]\nC-Rz b[0,1,2,3], q[1], -1.570796\nnot b[1,2,3]\n' in result) def test_generate_cqasm_correct_output_unknown_gate(self): instructions = [{'name': 'bla', 'qubits': [1], 'params': [-np.pi / 2]}] self.assertRaisesRegex(ApiError, "Gate 'bla' not supported", self._generate_cqasm_from_instructions, instructions, 2) def test_generate_cqasm_correct_output_unknown_controlled_gate(self): instructions = [{'mask': '0xF', 'name': 'bfunc', 'register': 17, 'relation': '==', 'val': '0x1'}, {'conditional': 17, 'name': 'bla', 'qubits': [1], 'params': [-np.pi / 2]}] self.assertRaisesRegex(ApiError, "Conditional gate 'c-bla' not supported", self._generate_cqasm_from_instructions, instructions, 2) def test_generate_cqasm_correct_output_no_bit_negation(self): q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c, name="test") qc.rx(-np.pi / 2, 1).c_if(c, 15) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('C-Rx b[0,1,2,3], q[1], -1.570796\n' in result) self.assertFalse('not\n' in result) def test_generate_cqasm_correct_output_one_bit_condition(self): q1 = QuantumRegister(1, "q1") q2 = QuantumRegister(1, "q2") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.rx(-np.pi / 2, q2).c_if(c1, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('C-Rx b[0], q[1], -1.570796\n' in result) self.assertFalse('not\n' in result) q1 = QuantumRegister(1, "q1") q2 = QuantumRegister(1, "q2") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.rx(-np.pi / 2, q2).c_if(c2, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('C-Rx b[1], q[1], -1.570796\n' in result) self.assertFalse('not\n' in result) q1 = QuantumRegister(6, "q1") q2 = QuantumRegister(1, "q2") c1 = ClassicalRegister(6, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.rx(-np.pi / 2, 1).c_if(c2, 1) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('C-Rx b[6], q[1], -1.570796\n' in result) self.assertFalse('not\n' in result) q1 = QuantumRegister(6, "q1") q2 = QuantumRegister(1, "q2") c1 = ClassicalRegister(6, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.rx(-np.pi / 2, 1).c_if(c2, 0) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[6]\nC-Rx b[6], q[1], -1.570796\nnot b[6]\n' in result) def test_generate_cqasm_correct_output_more_bit_condition(self): q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(3, "q2") c1 = ClassicalRegister(3, "c1") c2 = ClassicalRegister(3, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.y(2).c_if(c2, 3) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[5]\nC-Y b[3,4,5], q[2]\nnot b[5]\n' in result) q1 = QuantumRegister(1, "q1") q2 = QuantumRegister(7, "q2") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(7, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.y(2).c_if(c2, 12) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[1,2,5,6,7]\nC-Y b[1,2,3,4,5,6,7], q[2]\nnot b[1,2,5,6,7]\n' in result) q1 = QuantumRegister(1, "q1") q2 = QuantumRegister(7, "q2") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(7, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.y(2).c_if(c2, 27) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[3,6,7]\nC-Y b[1,2,3,4,5,6,7], q[2]\nnot b[3,6,7]\n' in result) q1 = QuantumRegister(5, "q1") q2 = QuantumRegister(2, "q2") c1 = ClassicalRegister(5, "c1") c2 = ClassicalRegister(2, "c2") qc = QuantumCircuit(q1, q2, c1, c2, name="test") qc.y(2).c_if(c2, 2) result = self._generate_cqasm_from_circuit(qc) self.assertTrue('not b[5]\nC-Y b[5,6], q[2]\nnot b[5]\n' in result) def test_generate_cqasm_correct_output_unknown_type(self): instructions = [{'mask': '0xF', 'name': 'bfunc', 'register': 18, 'relation': '!=', 'val': '0x1'}, {'conditional': 18, 'name': 'rx', 'qubits': [1], 'params': [-np.pi / 2]}] self.assertRaisesRegex(ApiError, 'Conditional statement with relation != not supported', self._generate_cqasm_from_instructions, instructions, 2) def test_generate_cqasm_correct_output_no_mask(self): instructions = [{'mask': '0x0', 'name': 'bfunc', 'register': 18, 'relation': '==', 'val': '0x1'}, {'conditional': 18, 'name': 'rx', 'qubits': [1], 'params': [-np.pi / 2]}] self.assertRaisesRegex(ApiError, 'Conditional statement rx without a mask', self._generate_cqasm_from_instructions, instructions, 2) def test_generate_cqasm_register_no_match(self): instructions = [{'mask': '0xF', 'name': 'bfunc', 'register': 1, 'relation': '==', 'val': '0x3'}, {'conditional': 2, 'name': 'rx', 'qubits': [1], 'params': [-np.pi / 2]}] self.assertRaisesRegex(ApiError, 'Conditional not found: reg_idx = 2', self._generate_cqasm_from_instructions, instructions, 2) def test_get_mask_data(self): mask = 0 lowest_mask_bit, mask_length = CircuitToString.get_mask_data(mask) self.assertEqual(lowest_mask_bit, -1) self.assertEqual(mask_length, 0) mask = 56 lowest_mask_bit, mask_length = CircuitToString.get_mask_data(mask) self.assertEqual(lowest_mask_bit, 3) self.assertEqual(mask_length, 3) mask = 1 lowest_mask_bit, mask_length = CircuitToString.get_mask_data(mask) self.assertEqual(lowest_mask_bit, 0) self.assertEqual(mask_length, 1) mask = 255 lowest_mask_bit, mask_length = CircuitToString.get_mask_data(mask) self.assertEqual(lowest_mask_bit, 0) self.assertEqual(mask_length, 8) mask = 510 lowest_mask_bit, mask_length = CircuitToString.get_mask_data(mask) self.assertEqual(lowest_mask_bit, 1) self.assertEqual(mask_length, 8) mask = 128 lowest_mask_bit, mask_length = CircuitToString.get_mask_data(mask) self.assertEqual(lowest_mask_bit, 7) self.assertEqual(mask_length, 1) mask = 192 lowest_mask_bit, mask_length = CircuitToString.get_mask_data(mask) self.assertEqual(lowest_mask_bit, 6) self.assertEqual(mask_length, 2)
https://github.com/qiskit-community/qiskit-qcgpu-provider
qiskit-community
import numpy as np import scipy from scipy.linalg import expm import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA def breast_cancer(training_size, test_size, n, PLOT_DATA=True): class_labels = [r'Benign', r'Malignant'] # First the dataset must be imported. cancer = datasets.load_breast_cancer() # To find if the classifier is accurate, a common strategy is # to divide the dataset into a training set and a test set. # Here the data is divided into 70% training, 30% testing. X_train, X_test, Y_train, Y_test = train_test_split(cancer.data, cancer.target, test_size=0.3, random_state=109) # Now the dataset's features will be standardized # to fit a normal distribution. scaler = StandardScaler().fit(X_train) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) # To be able to use this data with the given # number of qubits, the data must be broken down from # 30 dimensions to `n` dimensions. # This is done with Principal Component Analysis (PCA), # which finds patterns while keeping variation. pca = PCA(n_components=n).fit(X_train) X_train = pca.transform(X_train) X_test = pca.transform(X_test) # The last step in the data processing is # to scale the data to be between -1 and 1 samples = np.append(X_train, X_test, axis=0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) X_train = minmax_scale.transform(X_train) X_test = minmax_scale.transform(X_test) # Now some sample should be picked to train the model from training_input = {key: (X_train[Y_train == k, :])[:training_size] for k, key in enumerate(class_labels)} test_input = {key: (X_train[Y_train == k, :])[training_size:( training_size+test_size)] for k, key in enumerate(class_labels)} if PLOT_DATA: for k in range(0, 2): x_axis_data = X_train[Y_train == k, 0][:training_size] y_axis_data = X_train[Y_train == k, 1][:training_size] label = 'Malignant' if k is 1 else 'Benign' plt.scatter(x_axis_data, y_axis_data, label=label) plt.title("Breast Cancer Dataset (Dimensionality Reduced With PCA)") plt.legend() plt.show() return X_train, training_input, test_input, class_labels from qiskit_aqua.utils import split_dataset_to_data_and_labels n = 2 # How many features to use (dimensionality) training_dataset_size = 20 testing_dataset_size = 10 sample_Total, training_input, test_input, class_labels = breast_cancer(training_dataset_size, testing_dataset_size, n) datapoints, class_to_label = split_dataset_to_data_and_labels(test_input) print(class_to_label) from qiskit_aqua.input import SVMInput from qiskit_qcgpu_provider import QCGPUProvider from qiskit_aqua import run_algorithm params = { 'problem': {'name': 'svm_classification', 'random_seed': 10598}, 'algorithm': { 'name': 'QSVM.Kernel' }, 'backend': {'name': 'qasm_simulator', 'shots': 1024}, 'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entanglement': 'linear'} } backend = QCGPUProvider().get_backend('qasm_simulator') algo_input = SVMInput(training_input, test_input, datapoints[0]) %time result = run_algorithm(params, algo_input) %time result = run_algorithm(params, algo_input, backend=backend) print("ground truth: {}".format(datapoints[1])) print("prediction: {}".format(result['predicted_labels'])) print("predicted class: {}".format(result['predicted_classes'])) print("accuracy: {}".format(result['testing_accuracy']))
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the variational quantum eigensolver algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial import numpy as np from scipy.optimize import minimize as scipy_minimize from ddt import data, ddt from qiskit import QuantumCircuit from qiskit_algorithms import AlgorithmError from qiskit_algorithms.gradients import ParamShiftEstimatorGradient from qiskit_algorithms.minimum_eigensolvers import VQE from qiskit_algorithms.optimizers import ( CG, COBYLA, GradientDescent, L_BFGS_B, OptimizerResult, P_BFGS, QNSPSA, SLSQP, SPSA, TNC, ) from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit.circuit.library import RealAmplitudes, TwoLocal from qiskit.opflow import PauliSumOp, TwoQubitReduction from qiskit.quantum_info import SparsePauliOp, Operator, Pauli from qiskit.primitives import Estimator, Sampler from qiskit.utils import algorithm_globals # pylint: disable=invalid-name def _mock_optimizer(fun, x0, jac=None, bounds=None, inputs=None) -> OptimizerResult: """A mock of a callable that can be used as minimizer in the VQE.""" result = OptimizerResult() result.x = np.zeros_like(x0) result.fun = fun(result.x) result.nit = 0 if inputs is not None: inputs.update({"fun": fun, "x0": x0, "jac": jac, "bounds": bounds}) return result @ddt class TestVQE(QiskitAlgorithmsTestCase): """Test VQE""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed self.h2_op = SparsePauliOp( ["II", "IZ", "ZI", "ZZ", "XX"], coeffs=[ -1.052373245772859, 0.39793742484318045, -0.39793742484318045, -0.01128010425623538, 0.18093119978423156, ], ) self.h2_energy = -1.85727503 self.ryrz_wavefunction = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") self.ry_wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") @data(L_BFGS_B(), COBYLA()) def test_basic_aer_statevector(self, estimator): """Test VQE using reference Estimator.""" vqe = VQE(Estimator(), self.ryrz_wavefunction, estimator) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) with self.subTest(msg="test eigenvalue"): self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) with self.subTest(msg="test optimal_value"): self.assertAlmostEqual(result.optimal_value, self.h2_energy) with self.subTest(msg="test dimension of optimal point"): self.assertEqual(len(result.optimal_point), 16) with self.subTest(msg="assert cost_function_evals is set"): self.assertIsNotNone(result.cost_function_evals) with self.subTest(msg="assert optimizer_time is set"): self.assertIsNotNone(result.optimizer_time) with self.subTest(msg="assert optimizer_result is set"): self.assertIsNotNone(result.optimizer_result) with self.subTest(msg="assert optimizer_result."): self.assertAlmostEqual(result.optimizer_result.fun, self.h2_energy, places=5) with self.subTest(msg="assert return ansatz is set"): estimator = Estimator() job = estimator.run(result.optimal_circuit, self.h2_op, result.optimal_point) np.testing.assert_array_almost_equal(job.result().values, result.eigenvalue, 6) def test_invalid_initial_point(self): """Test the proper error is raised when the initial point has the wrong size.""" ansatz = self.ryrz_wavefunction initial_point = np.array([1]) vqe = VQE( Estimator(), ansatz, SLSQP(), initial_point=initial_point, ) with self.assertRaises(ValueError): _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_ansatz_resize(self): """Test the ansatz is properly resized if it's a blueprint circuit.""" ansatz = RealAmplitudes(1, reps=1) vqe = VQE(Estimator(), ansatz, SLSQP()) result = vqe.compute_minimum_eigenvalue(self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_invalid_ansatz_size(self): """Test an error is raised if the ansatz has the wrong number of qubits.""" ansatz = QuantumCircuit(1) ansatz.compose(RealAmplitudes(1, reps=2)) vqe = VQE(Estimator(), ansatz, SLSQP()) with self.assertRaises(AlgorithmError): _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_missing_ansatz_params(self): """Test specifying an ansatz with no parameters raises an error.""" ansatz = QuantumCircuit(self.h2_op.num_qubits) vqe = VQE(Estimator(), ansatz, SLSQP()) with self.assertRaises(AlgorithmError): vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_max_evals_grouped(self): """Test with SLSQP with max_evals_grouped.""" optimizer = SLSQP(maxiter=50, max_evals_grouped=5) vqe = VQE( Estimator(), self.ryrz_wavefunction, optimizer, ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) @data( CG(), L_BFGS_B(), P_BFGS(), SLSQP(), TNC(), ) def test_with_gradient(self, optimizer): """Test VQE using gradient primitive.""" estimator = Estimator() vqe = VQE( estimator, self.ry_wavefunction, optimizer, gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_gradient_passed(self): """Test the gradient is properly passed into the optimizer.""" inputs = {} estimator = Estimator() vqe = VQE( estimator, RealAmplitudes(), partial(_mock_optimizer, inputs=inputs), gradient=ParamShiftEstimatorGradient(estimator), ) _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertIsNotNone(inputs["jac"]) def test_gradient_run(self): """Test using the gradient to calculate the minimum.""" estimator = Estimator() vqe = VQE( estimator, RealAmplitudes(), GradientDescent(maxiter=200, learning_rate=0.1), gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_with_two_qubit_reduction(self): """Test the VQE using TwoQubitReduction.""" with self.assertWarns(DeprecationWarning): qubit_op = PauliSumOp.from_list( [ ("IIII", -0.8105479805373266), ("IIIZ", 0.17218393261915552), ("IIZZ", -0.22575349222402472), ("IZZI", 0.1721839326191556), ("ZZII", -0.22575349222402466), ("IIZI", 0.1209126326177663), ("IZZZ", 0.16892753870087912), ("IXZX", -0.045232799946057854), ("ZXIX", 0.045232799946057854), ("IXIX", 0.045232799946057854), ("ZXZX", -0.045232799946057854), ("ZZIZ", 0.16614543256382414), ("IZIZ", 0.16614543256382414), ("ZZZZ", 0.17464343068300453), ("ZIZI", 0.1209126326177663), ] ) tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op) vqe = VQE( Estimator(), self.ry_wavefunction, SPSA(maxiter=300, last_avg=5), ) result = vqe.compute_minimum_eigenvalue(tapered_qubit_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2) def test_callback(self): """Test the callback on VQE.""" history = {"eval_count": [], "parameters": [], "mean": [], "metadata": []} def store_intermediate_result(eval_count, parameters, mean, metadata): history["eval_count"].append(eval_count) history["parameters"].append(parameters) history["mean"].append(mean) history["metadata"].append(metadata) optimizer = COBYLA(maxiter=3) wavefunction = self.ry_wavefunction estimator = Estimator() vqe = VQE( estimator, wavefunction, optimizer, callback=store_intermediate_result, ) vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertTrue(all(isinstance(count, int) for count in history["eval_count"])) self.assertTrue(all(isinstance(mean, float) for mean in history["mean"])) self.assertTrue(all(isinstance(metadata, dict) for metadata in history["metadata"])) for params in history["parameters"]: self.assertTrue(all(isinstance(param, float) for param in params)) def test_reuse(self): """Test re-using a VQE algorithm instance.""" ansatz = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") vqe = VQE(Estimator(), ansatz, SLSQP(maxiter=300)) with self.subTest(msg="assert VQE works once all info is available"): result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) operator = Operator(np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]])) with self.subTest(msg="assert vqe works on re-use."): result = vqe.compute_minimum_eigenvalue(operator=operator) self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5) def test_vqe_optimizer_reuse(self): """Test running same VQE twice to re-use optimizer, then switch optimizer""" vqe = VQE( Estimator(), self.ryrz_wavefunction, SLSQP(), ) def run_check(): result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) run_check() with self.subTest("Optimizer re-use."): run_check() with self.subTest("Optimizer replace."): vqe.optimizer = L_BFGS_B() run_check() def test_default_batch_evaluation_on_spsa(self): """Test the default batching works.""" ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz") wrapped_estimator = Estimator() inner_estimator = Estimator() callcount = {"estimator": 0} def wrapped_estimator_run(*args, **kwargs): kwargs["callcount"]["estimator"] += 1 return inner_estimator.run(*args, **kwargs) wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount) spsa = SPSA(maxiter=5) vqe = VQE(wrapped_estimator, ansatz, spsa) _ = vqe.compute_minimum_eigenvalue(Pauli("ZZ")) # 1 calibration + 5 loss + 1 return loss expected_estimator_runs = 1 + 5 + 1 with self.subTest(msg="check callcount"): self.assertEqual(callcount["estimator"], expected_estimator_runs) with self.subTest(msg="check reset to original max evals grouped"): self.assertIsNone(spsa._max_evals_grouped) def test_batch_evaluate_with_qnspsa(self): """Test batch evaluating with QNSPSA works.""" ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz") wrapped_sampler = Sampler() inner_sampler = Sampler() wrapped_estimator = Estimator() inner_estimator = Estimator() callcount = {"sampler": 0, "estimator": 0} def wrapped_estimator_run(*args, **kwargs): kwargs["callcount"]["estimator"] += 1 return inner_estimator.run(*args, **kwargs) def wrapped_sampler_run(*args, **kwargs): kwargs["callcount"]["sampler"] += 1 return inner_sampler.run(*args, **kwargs) wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount) wrapped_sampler.run = partial(wrapped_sampler_run, callcount=callcount) fidelity = ComputeUncompute(wrapped_sampler) def fidelity_callable(left, right): batchsize = np.asarray(left).shape[0] job = fidelity.run(batchsize * [ansatz], batchsize * [ansatz], left, right) return job.result().fidelities qnspsa = QNSPSA(fidelity_callable, maxiter=5) qnspsa.set_max_evals_grouped(100) vqe = VQE( wrapped_estimator, ansatz, qnspsa, ) _ = vqe.compute_minimum_eigenvalue(Pauli("ZZ")) # 5 (fidelity) expected_sampler_runs = 5 # 1 calibration + 1 stddev estimation + 1 initial blocking # + 5 (1 loss + 1 blocking) + 1 return loss expected_estimator_runs = 1 + 1 + 1 + 5 * 2 + 1 self.assertEqual(callcount["sampler"], expected_sampler_runs) self.assertEqual(callcount["estimator"], expected_estimator_runs) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" vqe = VQE( Estimator(), self.ryrz_wavefunction, partial(scipy_minimize, method="L-BFGS-B", options={"maxiter": 10}), ) result = vqe.compute_minimum_eigenvalue(self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2) def test_optimizer_callable(self): """Test passing a optimizer directly as callable.""" ansatz = RealAmplitudes(1, reps=1) vqe = VQE(Estimator(), ansatz, _mock_optimizer) result = vqe.compute_minimum_eigenvalue(SparsePauliOp("Z")) self.assertTrue(np.all(result.optimal_point == np.zeros(ansatz.num_parameters))) def test_aux_operators_list(self): """Test list-based aux_operators.""" vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300)) with self.subTest("Test with an empty list."): result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=[]) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsInstance(result.aux_operators_evaluated, list) self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = [aux_op1, aux_op2] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6) # metadata self.assertIsInstance(result.aux_operators_evaluated[0][1], dict) self.assertIsInstance(result.aux_operators_evaluated[1][1], dict) with self.subTest("Test with additional zero operator."): extra_ops = [*aux_ops, 0] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[2][0], 0.0) # metadata self.assertIsInstance(result.aux_operators_evaluated[0][1], dict) self.assertIsInstance(result.aux_operators_evaluated[1][1], dict) self.assertIsInstance(result.aux_operators_evaluated[2][1], dict) def test_aux_operators_dict(self): """Test dictionary compatibility of aux_operators""" vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300)) with self.subTest("Test with an empty dictionary."): result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators={}) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsInstance(result.aux_operators_evaluated, dict) self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5) # metadata self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict) with self.subTest("Test with additional zero operator."): extra_ops = {**aux_ops, "zero_operator": 0} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["zero_operator"][0], 0.0) # metadata self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["zero_operator"][1], dict) if __name__ == "__main__": unittest.main()
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Numpy and Scipy for data evaluation and reference calculations import numpy as np from scipy.linalg import expm # Matplotlib for visualization import matplotlib.pyplot as plt # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline # Function for convenience which allows for running the simulator and extracting the results def run_on_qasm_simulator(quantum_circuit, num_shots): """Takes a circuit, the number of shots and a backend and returns the counts for running the circuit on the qasm_simulator backend.""" qasm_simulator = Aer.get_backend('qasm_simulator') job = execute(quantum_circuit, backend=qasm_simulator, shots=num_shots) result = job.result() counts = result.get_counts() return counts def Op(M, n ,N): """Given a single site operator, provide the N-body operator string obtained by tensoring identities""" d = M.shape[0] id_left = np.eye(d**n) id_right = np.eye(d**(N-n-1)) res = np.kron(id_left,np.kron(M,id_right)) return res def IsingHamiltonian(N, h): """The Ising Hamiltonian for N sites with parameter h""" Z = np.array([[1., 0.],[0., -1.]]) X = np.array([[0., 1.],[1., 0.]]) H = np.zeros((2**N, 2**N)) for i in range(N): if i<N-1: H += Op(Z, i, N)@Op(Z, i+1, N) H += h*Op(X, i, N) return H # For reference, we provide a function computing the exact solution for # the magnetization as a function of time def get_magnetization_vs_time(h, delta_t, nsteps): """Compute the exact value of the magnetization""" Z = np.array([[1., 0.],[0., -1.]]) X = np.array([[0., 1.],[1., 0.]]) Id = np.eye(2) # The Ising Hamiltonian for 4 sites with parameter h H = IsingHamiltonian(4, h) # The time evolution operator for an interval \Delta t U = expm(-1.0j*delta_t*H) # The operator for the total magnetization M = Op(Z,0,4) + Op(Z,1,4) + Op(Z,2,4) + Op(Z,3,4) # Numpy array to hold the results magnetization = np.zeros(nsteps) # The initial wave function corresponding to |0010> psi = np.zeros(16) psi[int('0010', 2)] = 1 # Evolve in steps of \Delta t and measure the magnetization for n in range(nsteps): psi = U@psi magnetization[n] = np.real(psi.conj().T@M@psi) return magnetization def provide_initial_state(): # Create a quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the necessary gate(s) to provide the inital state |0010> qc.x(2) return qc def Uzz(delta_t): # Create an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the gates for exp(-i Z_k Z_k+1 \Delta t) for all neighboring qubits for i in range(3): qc.rzz(2.0*delta_t, i, i+1) return qc def Ux(delta_t, h): # Create an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the gates for exp(-i h X_k \Delta t) to all qubits for i in range(4): qc.rx(2.0*delta_t*h, i) return qc def build_time_evolution_circuit(qc_init_state, qc_Uzz, qc_Ux, N): """Given the circuits implementing the initial state and the two parts of the trotterized time-evolution operator build the circuit evolving the wave function N steps """ # Generate an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the inital state qc.compose(qc_init_state, inplace=True) # For each time step add qc_Uzz and qc_Ux for i in range(N): qc.compose(qc_Uzz, inplace=True) qc.compose(qc_Ux, inplace=True) # Add the final measurments qc.measure_all() return qc def get_magnetization(counts): """Given the counts resulting form a measurement, compute the site resolved magnetization""" total_counts = sum(counts.values()) res = np.zeros(4) for qubit in range(4): Z_expectation = 0. for key, value in counts.items(): if key[qubit] == '0': Z_expectation += value else: Z_expectation -= value res[qubit] = Z_expectation/total_counts return res # The parameters for the time evolution h = 1.5 delta_t = 0.05 nsteps = 40 nshots = 1000 # Provide the initial state qc_init_state = provide_initial_state() # The time-evolution operators qc_Uzz = Uzz(delta_t) qc_Ux = Ux(delta_t,h) # Numpy array for expectation values of the magnetization magnetization = np.zeros(nsteps) # Numpy array for qubit configuration configuration = np.zeros((4, nsteps)) # Run the time evolution for n in range(1, nsteps+1): # Build the evolution circuit out of qc_init_state, qc_Uzz and qc_Ux for # n steps qc_evo = build_time_evolution_circuit(qc_init_state, qc_Uzz, qc_Ux, n) # Run the evolution circuit on the qasm_simulator res = run_on_qasm_simulator(qc_evo, nshots) # Compute the ovservables configuration[:,n-1] = get_magnetization(res) magnetization[n-1] = sum(configuration[:,n-1]) # For reference we compute the exact solution magnetization_exact = get_magnetization_vs_time(h, delta_t, nsteps) # Plot the total magnetization as a function of time and compare to # the exact result plt.figure() plt.plot(magnetization_exact, '--', label='exact') plt.plot(magnetization, 'o', label='quantum circuit') plt.xlabel('$t/\Delta t$') plt.ylabel('$<\sum_i Z_i(t)>$') plt.title('Total magnetization') plt.legend() # Plot the site resolved spin configuration as a function of time plt.figure() plt.imshow(configuration, aspect='auto') plt.colorbar() plt.xlabel('$t/\Delta t$') plt.ylabel('$<Z_i(t)>$') plt.title('Spatially resolved spin configuration') # Import the package for working with parameters from qiskit.circuit import Parameter # Define parameters, the arguments define the symbols that are shown if we # draw the circuit dt = Parameter('Δt') h = Parameter('h') def Uzz_parameterized(param_delta_t): # Create an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the gates for exp(-i Z_k Z_k+1 \Delta t) for all neighboring qubits for i in range(3): qc.rzz(2.0*param_delta_t, i, i+1) return qc def Ux_parameterized(param_delta_t, param_h): # Create an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) for i in range(4): # Add the exp(-i \Delta t Z_k Z_k+1) gates qc.rx(2.0*param_delta_t*param_h, i) return qc # The parameters for the time evolution (now we can conveniently check # for multiple values of h since we have a parameterized circuit) h_values = [1.0, 1.2 , 1.5] delta_t = 0.05 nsteps = 40 nshots = 1000 # Provide the initial state qc_init_state = provide_initial_state() # The time-evolution operators qc_Uzz = Uzz_parameterized(dt) qc_Ux = Ux_parameterized(dt, h) # Numpy array for expectation values of the magnetization magnetization = np.zeros((len(h_values), nsteps)) # Run the time evolution for n in range(1, nsteps+1): # Build the evolution circuit out of qc_init_state, qc_Uzz and qc_Ux for # n steps qc_evo = build_time_evolution_circuit(qc_init_state, qc_Uzz, qc_Ux, n) # Now we bind the parameter \Delta t qc_evo = qc_evo.bind_parameters({dt: delta_t}) # Now we bind the parameters for h and get a list of circuits, one for each value of h circs = [qc_evo.bind_parameters({h: h_value}) for h_value in h_values] # Run the evolution circuits on the qasm_simulator res = run_on_qasm_simulator(circs, nshots) # Compute the ovservables (now res is a list of counts with one entry for each different value of h) for i in range(len(res)): configuration = get_magnetization(res[i]) magnetization[i, n-1] = sum(configuration) # For reference we compute the exact solutions magnetization_exact = np.zeros((len(h_values), nsteps)) for i in range(len(h_values)): magnetization_exact[i,:] = get_magnetization_vs_time(h_values[i], delta_t, nsteps) # Plot the total magnetization as a function of time and compare to # the exact result plt.figure() for i in range(len(h_values)): hf = plt.plot(magnetization_exact[i,:], '--', label='exact, $h = ' + str(h_values[i]) + '$') plt.plot(magnetization[i,:], 'o', label='quantum circuit, $h = ' + str(h_values[i]) + '$', c=hf[0].get_color()) plt.xlabel('$t/\Delta t$') plt.ylabel('$<\sum_i Z_i(t)>$') plt.title('Total magnetization') plt.legend()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler from qiskit.utils import algorithm_globals from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder, MinMaxScaler from qiskit_machine_learning.algorithms.classifiers import VQC from IPython.display import clear_output algorithm_globals.random_seed = 42 sampler1 = Sampler() sampler2 = Sampler() num_samples = 40 num_features = 2 features = 2 * algorithm_globals.random.random([num_samples, num_features]) - 1 labels = 1 * (np.sum(features, axis=1) >= 0) # in { 0, 1} features = MinMaxScaler().fit_transform(features) features.shape features[0:5, :] labels = OneHotEncoder(sparse=False).fit_transform(labels.reshape(-1, 1)) labels.shape labels[0:5, :] train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=30, random_state=algorithm_globals.random_seed ) train_features.shape def plot_dataset(): plt.scatter( train_features[np.where(train_labels[:, 0] == 0), 0], train_features[np.where(train_labels[:, 0] == 0), 1], marker="o", color="b", label="Label 0 train", ) plt.scatter( train_features[np.where(train_labels[:, 0] == 1), 0], train_features[np.where(train_labels[:, 0] == 1), 1], marker="o", color="g", label="Label 1 train", ) plt.scatter( test_features[np.where(test_labels[:, 0] == 0), 0], test_features[np.where(test_labels[:, 0] == 0), 1], marker="o", facecolors="w", edgecolors="b", label="Label 0 test", ) plt.scatter( test_features[np.where(test_labels[:, 0] == 1), 0], test_features[np.where(test_labels[:, 0] == 1), 1], marker="o", facecolors="w", edgecolors="g", label="Label 1 test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.plot([1, 0], [0, 1], "--", color="black") plot_dataset() plt.show() maxiter = 20 objective_values = [] # callback function that draws a live plot when the .fit() method is called def callback_graph(_, objective_value): clear_output(wait=True) objective_values.append(objective_value) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") stage1_len = np.min((len(objective_values), maxiter)) stage1_x = np.linspace(1, stage1_len, stage1_len) stage1_y = objective_values[:stage1_len] stage2_len = np.max((0, len(objective_values) - maxiter)) stage2_x = np.linspace(maxiter, maxiter + stage2_len - 1, stage2_len) stage2_y = objective_values[maxiter : maxiter + stage2_len] plt.plot(stage1_x, stage1_y, color="orange") plt.plot(stage2_x, stage2_y, color="purple") plt.show() plt.rcParams["figure.figsize"] = (12, 6) original_optimizer = COBYLA(maxiter=maxiter) ansatz = RealAmplitudes(num_features) initial_point = np.asarray([0.5] * ansatz.num_parameters) original_classifier = VQC( ansatz=ansatz, optimizer=original_optimizer, callback=callback_graph, sampler=sampler1 ) original_classifier.fit(train_features, train_labels) print("Train score", original_classifier.score(train_features, train_labels)) print("Test score ", original_classifier.score(test_features, test_labels)) original_classifier.save("vqc_classifier.model") loaded_classifier = VQC.load("vqc_classifier.model") loaded_classifier.warm_start = True loaded_classifier.neural_network.sampler = sampler2 loaded_classifier.optimizer = COBYLA(maxiter=80) loaded_classifier.fit(train_features, train_labels) print("Train score", loaded_classifier.score(train_features, train_labels)) print("Test score", loaded_classifier.score(test_features, test_labels)) train_predicts = loaded_classifier.predict(train_features) test_predicts = loaded_classifier.predict(test_features) # return plot to default figsize plt.rcParams["figure.figsize"] = (6, 4) plot_dataset() # plot misclassified data points plt.scatter( train_features[np.all(train_labels != train_predicts, axis=1), 0], train_features[np.all(train_labels != train_predicts, axis=1), 1], s=200, facecolors="none", edgecolors="r", linewidths=2, ) plt.scatter( test_features[np.all(test_labels != test_predicts, axis=1), 0], test_features[np.all(test_labels != test_predicts, axis=1), 1], s=200, facecolors="none", edgecolors="r", linewidths=2, ) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/msramalho/Teach-Me-Quantum
msramalho
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Choose the drawer you like best: from qiskit.tools.visualization import matplotlib_circuit_drawer as draw #from qiskit.tools.visualization import circuit_drawer as draw from qiskit import IBMQ IBMQ.load_accounts() # make sure you have setup your token locally to use this %matplotlib inline import matplotlib.pyplot as plt def show_results(D): # D is a dictionary with classical bits as keys and count as value # example: D = {'000': 497, '001': 527} plt.bar(range(len(D)), list(D.values()), align='center') plt.xticks(range(len(D)), list(D.keys())) plt.show() from qiskit import Aer # See a list of available local simulators print("Aer backends: ", Aer.backends()) # see a list of available remote backends (these are freely given by IBM) print("IBMQ Backends: ", IBMQ.backends()) # execute circuit and either display a histogram of the results def execute_locally(qc, draw_circuit=False, show_results=False): # Compile and run the Quantum circuit on a simulator backend backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() result_counts = result_sim.get_counts(qc) if draw_circuit or show_results: # Print the results print("simulation: ", result_sim, result_counts) if draw_circuit: # draw the circuit draw(qc) elif show_results: # or show the results show_results(result_counts) return result_counts from qiskit.backends.ibmq import least_busy import time # Compile and run on a real device backend def execute_remotely(qc, draw_circuit=False, show_results=False): if draw_circuit: # draw the circuit draw(qc) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) # running the job job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10) lapse, interval = 0, 10 while job_exp.status().name != 'DONE': print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status()) time.sleep(interval) lapse += 1 print(job_exp.status()) exp_result = job_exp.result() result_counts = exp_result.get_counts(qc) # Show the results print("experiment: ", exp_result, result_counts) if show_results: # show the results show_results(result_counts) return result_counts except: print("All devices are currently unavailable.") return {} def new_circuit(size): # Create a Quantum Register with size qubits qr = QuantumRegister(size) # Create a Classical Register with size bits cr = ClassicalRegister(size) # Create a Quantum Circuit acting on the qr and cr register return qr, cr, QuantumCircuit(qr, cr) ERROR_MESSAGE = "Looks like your Deutsch has a bug" def quantum_oracle_1(qr, cr, circuit): pass def quantum_oracle_2(qr, cr, circuit): circuit.cx(qr[0], qr[1]) def quantum_oracle_3(qr, cr, circuit): circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) def quantum_oracle_4(qr, cr, circuit): circuit.z(qr[1]) circuit.cx(qr[0], qr[1]) def get_deutsch_verdict(res): return "CONSTANT" or "BALANCED" print(get_deutsch_verdict(results)) def deutsch(black_box): # ... black_box(circuit) #... return "CONSTANT" or "BALANCED" assert deutsch(quantum_oracle_1) == 'CONSTANT', ERROR_MESSAGE assert deutsch(quantum_oracle_2) == 'BALANCED', "Looks like your Deutsch has a bug" assert deutsch(quantum_oracle_3) == 'BALANCED', "Looks like your Deutsch has a bug" assert deutsch(quantum_oracle_4) == 'CONSTANT', "Looks like your Deutsch has a bug"
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.mappers.second_quantization import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(padding=2) from qiskit_nature.circuit.library import HartreeFock from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spin_orbitals=6, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) from qiskit_nature.second_q.circuit.library import HartreeFock from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spatial_orbitals=3, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q # TODO: This example should use a real mock backend. backend = FakeOpenPulse3Q() d2 = pulse.DriveChannel(2) with pulse.build(backend) as bell_prep: pulse.u2(0, math.pi, 0) pulse.cx(0, 1) with pulse.build(backend) as decoupled_bell_prep_and_measure: # We call our bell state preparation schedule constructed above. with pulse.align_right(): pulse.call(bell_prep) pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2) pulse.barrier(0, 1, 2) registers = pulse.measure_all() decoupled_bell_prep_and_measure.draw()
https://github.com/liyaochong/quantum-algorithm-learning-and-implementation
liyaochong
# 导入相应的依赖库 import numpy as np import math from math import pi import re from qiskit import BasicAer,execute from qiskit import QuantumCircuit,ClassicalRegister,QuantumRegister from qiskit.tools.visualization import circuit_drawer from qiskit import Aer, execute # 实现目标量子态的制备电路 # 输入经典的数据,以向量的形式给出(注意:这里给出的向量元素为实数) classic_vec = [0.234,0.567] # 获得经典向量的二范数,存储至变量x_norm x_norm = np.linalg.norm(classic_vec, ord=None, axis=None, keepdims=False) # 获得归一化之后的向量,即对应量子态上的概率幅 norm_vec = classic_vec/x_norm print(norm_vec) # 计算制备目标量子态所需要的量子比特 num_qubits = int(math.log(len(classic_vec),2)) # 利用Qiskit中的初始化内置函数,生成对应的制备电路 q_inital = QuantumRegister(num_qubits,'q_inital') Circuit_inital = QuantumCircuit() Circuit_inital.add_register(q_inital) Circuit_inital.initialize(norm_vec,q_inital) # 对初始化制备电路,生成qsam代码,并截取量子门操作部分的代码 Qasm_Code = Circuit_inital.qasm().split(';')[3:-1] # 去除list中字符串的‘\n’部分 Qasm_Code = [x.strip() for x in Qasm_Code if x.strip()!=''] # 设置参数的提取规则 p1 = re.compile(r'[(](.*?)[)]', re.S) # 提取圆括号中的数据,返回数据类型为list p2 = re.compile(r'[[](.*?)[]]', re.S) # 提取方括号中的数据,返回数据类型为list # 设置数据寄存器和地址寄存器,对应各自的量子比特数量为num_qubits # q0表示address地址寄存器,量子比特与数据制备寄存器相等 q0 = QuantumRegister(num_qubits,'q0') c0 = ClassicalRegister(num_qubits,'c0') # q1表示data数据寄存器,用于数据制备 q1 = QuantumRegister(num_qubits,'q1') c1 = ClassicalRegister(num_qubits,'c1') # 辅助量子比特寄存器B,有一个量子比特 q2 = QuantumRegister(1,'q2') c2 = ClassicalRegister(1,'c2') # 将寄存器添加至量子电路 Circuit = QuantumCircuit() Circuit.add_register(q0,c0) Circuit.add_register(q1,c1) Circuit.add_register(q2,c2) # Circuit.add_register(q0) # Circuit.add_register(q1) # Circuit.add_register(q2) # 制备地址寄存器的状态 for i in range(num_qubits): Circuit.h(q0[i]) # 对目标量子态进行制备(概率幅编码) for i in range(len(Qasm_Code)): code_str = Qasm_Code[i] if code_str[0:2]=='ry': theta = float(re.findall(p1, code_str)[0]) target_qubit = int(re.findall(p2, code_str)[0]) Circuit.u3(theta,0,0,q1[target_qubit]) elif code_str[0:2]=='cx': control_qubit = int(re.findall(p2, code_str)[0]) target_qubit = int(re.findall(p2, code_str)[1]) Circuit.cx(q1[control_qubit],q1[target_qubit]) else: print('The desired vector must be real number!') Circuit.barrier() # 执行Hadamard Test操作 Circuit.h(q2[0]) for i in range(len(Qasm_Code)): code_str = Qasm_Code[len(Qasm_Code)-1-i] if code_str[0:2]=='ry': theta = float(re.findall(p1, code_str)[0]) target_qubit = int(re.findall(p2, code_str)[0]) Circuit.cu3(-theta,0,0,q2[0],q1[target_qubit]) elif code_str[0:2]=='cx': control_qubit = int(re.findall(p2, code_str)[0]) target_qubit = int(re.findall(p2, code_str)[1]) Circuit.ccx(q2[0],q1[control_qubit],q1[target_qubit]) else: print('The desired vector must be real number!') for i in range(num_qubits): Circuit.ccx(q2[0],q0[i],q1[i]) Circuit.h(q2[0]) # 绘制量子电路图 # Circuit.draw(output='mpl') # 定义两个函数(分解为通用量子门) # 定义具有两个控制位的受控旋转门(绕Y轴旋转) def cu3_2(theta,control_1,control_2,target,circuit): circuit.cu3(theta/2,0,0,control_1,target) circuit.cu3(theta/2,0,0,control_2,target) circuit.cx(control_1,control_2) circuit.cu3(-theta/2,0,0,control_2,target) circuit.cx(control_1,control_2) return circuit # 定义具有三个控制位的受控非门(使用两个初始状态为0态的辅助量子比特) def cccx(control_1,control_2,control_3,target,circuit): circuit.ccx(control_1,control_2,q_auxiliary[0]) circuit.ccx(control_3,q_auxiliary[0],q_auxiliary[1]) circuit.cx(q_auxiliary[1],target) circuit.ccx(control_3,q_auxiliary[0],q_auxiliary[1]) circuit.ccx(control_1,control_2,q_auxiliary[0]) return circuit # 执行量子相位估计 # 相位估计的第一寄存器q3,量子比特数量决定了计算精度 qpe_control_qubits = 3 q3 = QuantumRegister(qpe_control_qubits,'q3') c3 = ClassicalRegister(qpe_control_qubits,'c3') Circuit.add_register(q3,c3) # Circuit.add_register(q3) # 三个控制位的受控非门,需要两个辅助量子比特 q_auxiliary = QuantumRegister(2,'q_auxiliary') c_auxiliary = ClassicalRegister(2,'c_auxiliary') Circuit.add_register(q_auxiliary,c_auxiliary) # Circuit.add_register(q_auxiliary) # 对相位估计的第一寄存器进行全Hadamard门操作 for i in range(qpe_control_qubits): Circuit.h(q3[i]) Circuit.barrier() # 对相位估计的第二寄存器执行受控U操作 for i in range(qpe_control_qubits): # 由控制位决定U的阶数,使用for循环进行操作 for j in range(int(math.pow(2, i))): # 执行受控Z门以及受控H门的操作,其中控制位为第一寄存器的第i个比特 Circuit.cz(q3[i],q2[0]) Circuit.ch(q3[i],q2[0]) Circuit.barrier() # 执行多位受控非门的操作 for k in range(num_qubits): cccx(control_1=q3[i],control_2=q2[0],control_3=q0[k],target=q1[k],circuit=Circuit) Circuit.barrier() # 执行两比特控制的U^A操作,用到了两比特控制旋转门以及三比特控制非门的分解电路函数 for t1 in range(len(Qasm_Code)): code_str = Qasm_Code[t1] if code_str[0:2]=='ry': theta = float(re.findall(p1, code_str)[0]) target_qubit = int(re.findall(p2, code_str)[0]) cu3_2(theta=theta,control_1=q3[i],control_2=q2[0],target=q1[target_qubit],circuit=Circuit) elif code_str[0:2]=='cx': control_qubit = int(re.findall(p2, code_str)[0]) target_qubit = int(re.findall(p2, code_str)[1]) cccx(control_1=q3[i],control_2=q2[0],control_3=q1[control_qubit],target=q1[target_qubit],circuit=Circuit) else: print('The desired vector must be real number!') Circuit.barrier() # 执行受控H门操作,其中控制位为第一寄存器的第i个比特 Circuit.ch(q3[i],q2[0]) Circuit.barrier() # 执行单比特控制的U^A+操作,用到了单比特控制的受控旋转门以及TOFFOLI门 for t2 in range(len(Qasm_Code)): code_str = Qasm_Code[len(Qasm_Code)-1-t2] if code_str[0:2]=='ry': theta = float(re.findall(p1, code_str)[0]) target_qubit = int(re.findall(p2, code_str)[0]) Circuit.cu3(-theta,0,0,q3[i],q1[target_qubit]) elif code_str[0:2]=='cx': control_qubit = int(re.findall(p2, code_str)[0]) target_qubit = int(re.findall(p2, code_str)[1]) Circuit.ccx(q3[i],q1[control_qubit],q1[target_qubit]) else: print('The desired vector must be real number!') Circuit.barrier() # 多位受控-Z门的操作 # for k in range(num_qubits): # Circuit.x(q1[k]) # Circuit.ccx(q3[i],q1[0],q_auxiliary[0]) # Circuit.ccx(q1[1],q_auxiliary[0],q_auxiliary[1]) # Circuit.cu3(pi,-pi/2,pi/2,q_auxiliary[1],q2[0]) # Circuit.cu3(pi,pi/2,pi/2,q_auxiliary[1],q2[0]) # Circuit.ccx(q1[1],q_auxiliary[0],q_auxiliary[1]) # Circuit.ccx(q3[i],q1[0],q_auxiliary[0]) # for k in range(num_qubits): # Circuit.x(q1[k]) # Circuit.barrier() Circuit.x(q1[0]) Circuit.ccx(q1[0],q3[i],q_auxiliary[0]) Circuit.cu3(pi,-pi/2,pi/2,q_auxiliary[0],q2[0]) Circuit.cu3(pi,pi/2,pi/2,q_auxiliary[0],q2[0]) Circuit.ccx(q1[0],q3[i],q_auxiliary[0]) Circuit.x(q1[0]) Circuit.barrier() # 执行单比特控制的U^A操作,用到了单比特控制的受控旋转门以及TOFFOLI门 for t3 in range(len(Qasm_Code)): code_str = Qasm_Code[t3] if code_str[0:2]=='ry': theta = float(re.findall(p1, code_str)[0]) target_qubit = int(re.findall(p2, code_str)[0]) Circuit.cu3(theta,0,0,q3[i],q1[target_qubit]) elif code_str[0:2]=='cx': control_qubit = int(re.findall(p2, code_str)[0]) target_qubit = int(re.findall(p2, code_str)[1]) Circuit.ccx(q3[i],q1[control_qubit],q1[target_qubit]) else: print('The desired vector must be real number!') Circuit.barrier() # 执行受控H门操作,其中控制位为第一寄存器的第i个比特 Circuit.ch(q3[i],q2[0]) Circuit.barrier() # 执行两比特控制的U^A+操作,用到了两比特控制旋转门以及三比特控制非门的分解电路函数 for t4 in range(len(Qasm_Code)): code_str = Qasm_Code[len(Qasm_Code)-1-t4] if code_str[0:2]=='ry': theta = float(re.findall(p1, code_str)[0]) target_qubit = int(re.findall(p2, code_str)[0]) cu3_2(theta=-theta,control_1=q3[i],control_2=q2[0],target=q1[target_qubit],circuit=Circuit) elif code_str[0:2]=='cx': control_qubit = int(re.findall(p2, code_str)[0]) target_qubit = int(re.findall(p2, code_str)[1]) cccx(control_1=q3[i],control_2=q2[0],control_3=q1[control_qubit],target=q1[target_qubit],circuit=Circuit) else: print('The desired vector must be real number!') Circuit.barrier() # 执行多位受控非门的操作 for k in range(num_qubits): cccx(control_1=q3[i],control_2=q2[0],control_3=q0[k],target=q1[k],circuit=Circuit) Circuit.barrier() # 执行受控H门的操作,其中控制位为第一寄存器的第i个比特 Circuit.ch(q3[i],q2[0]) Circuit.barrier() # 执行量子相位估计的第二阶段(量子傅里叶逆变换) Circuit.h(q3[0]) Circuit.cu1(-pi/2,q3[0],q3[1]) Circuit.cu1(-pi/4,q3[0],q3[2]) Circuit.h(q3[1]) Circuit.cu1(-pi/2,q3[1],q3[2]) Circuit.h(q3[2]) Circuit.barrier() # Circuit.measure(q0,c0) # Circuit.measure(q1,c1) # Circuit.measure(q2,c2) # Circuit.measure(q3,c3) # Circuit.measure(q_auxiliary,c_auxiliary) Circuit.draw(output='mpl').savefig('QC.pdf',dpi=800) simulator = Aer.get_backend('statevector_simulator') result = execute(Circuit, simulator).result() statevector = result.get_statevector(Circuit) print(statevector)
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, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # 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): qc = QuantumCircuit(2) qc.h(1) qc.cx(1,0) qc.h(1) qc.rz(- 2 * dt, 1) qc.rz(dt, 0) qc.h(1) 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() qc = QuantumCircuit(2) qc.h(1) qc.cx(1,0) qc.h(1) qc.rz(- 2 * np.pi / 6, 1) qc.rz(np.pi / 6, 0) qc.h(1) qc.cx(1,0) qc.h(1) qc.rx(np.pi / 6, [1]) qc.barrier() qc.rz(-np.pi / 6, [0,1]) qc.rx(-np.pi / 6, [0,1]) qc.draw('mpl') # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # 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) # The final time of the state evolution target_time = np.pi # Number of trotter steps trotter_steps = 1 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) 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>) qc.x([3]) # 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[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # 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}) shots = 8192 reps = 8 # WE USE A NOISELESS SIMULATION HERE backend = Aer.get_backend('qasm_simulator') # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [qr[1], qr[3], qr[5]]) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs[-1].draw("mpl") # only view trotter gates jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits def state_tomo(result, st_qcs): # The expected final state; necessary to determine state tomography fidelity target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Fit state tomography results tomo_fitter = StateTomographyFitter(result, st_qcs) rho_fit = tomo_fitter.fit(method='lstsq') # Compute fidelity fid = state_fidelity(rho_fit, target_state) return fid # Compute tomography fidelities for each repetition fids = [] for job in jobs: fid = state_tomo(job.result(), st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) from qiskit.compiler import transpile t0_qc = transpile(qc, optimization_level=0, basis_gates=["sx","rz","cx"]) t0_qc.draw("mpl") t1_qc = transpile(qc, optimization_level=1, basis_gates=["sx","rz","cx"]) t1_qc.draw("mpl") t2_qc = transpile(qc, optimization_level=2, basis_gates=["sx","rz","cx"]) t2_qc.draw("mpl") t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx","rz","cx"]) t3_qc.draw("mpl") st_qcs = state_tomography_circuits(t2_qc, [qr[1], qr[3], qr[5]]) jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) fids = [] for job in jobs: fid = state_tomo(job.result(), st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]]) jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) fids = [] for job in jobs: fid = state_tomo(job.result(), st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') zne_fid_list = [] zne_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) retrieved_jobs = jobs zne_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) zne_rho = expvals_to_valid_rho(num_qubits, zne_expvals) zne_fid = state_fidelity(zne_rho, target_state) zne_fids.append(zne_fid) zne_fid_list.append(np.mean(zne_fids)) zne_stddev_list.append(np.std(zne_fids)) t2 = time.perf_counter() print('zne pt state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(zne_fids), np.std(zne_fids))) print("time:", t2 - t1) print() with open("e2d1_zne_pt.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": zne_fid_list, "stddev": zne_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, zne_fid_list)
https://github.com/INFINIT27/Shor-s-Algorithm-using-Qiskit
INFINIT27
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/derivation/quantum_image_edge_detection
derivation
# import_demo_tools.py import numpy as np from numpy import pi import matplotlib.pyplot as plt from qiskit_aqua.components.initial_states import Custom from qiskit import BasicAer, execute
https://github.com/veenaiyuri/qiskit-education
veenaiyuri
from qiskit import * from qiskit.tools.visualization import plot_histogram, circuit_drawer q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[1], q[2]) qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.cx(q[1], q[2]) qc.cz(q[0], q[2]) qc.h(q[2]) qc.measure(q[2], c[2]) backend = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend, shots=1024) sim_result = job_sim.result() measurement_result = sim_result.get_counts(qc) print(measurement_result) plot_histogram(measurement_result)
https://github.com/lancecarter03/QiskitLearning
lancecarter03
from qiskit import * from qiskit.tools.visualization import plot_bloch_multivector from qiskit.tools.visualization import plot_histogram circuit = QuantumCircuit(1,1) circuit.x(0) simulator = Aer.get_backend('statevector_simulator') result = execute(circuit, backend = simulator).result() statevector = result.get_statevector() print(statevector) circuit.draw(output='mpl') plot_bloch_multivector(statevector) circuit.measure([0],[0]) backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend = backend, shots=1024).result() counts = result.get_counts() plot_histogram(counts) circuit = QuantumCircuit(1,1) circuit.x(0) simulator = Aer.get_backend('unitary_simulator') result = execute(circuit, backend = simulator).result() unitary = result.get_unitary() print(unitary)
https://github.com/NesyaLab/qaoa
NesyaLab
#------------------------------------------------------------------------------ # Qaoa.py # # Implementation of the Quantum Approximate Optimization Algorithm (QAOA) [1],[2] # specifically tailored for solving the MaxCut problem on graphs [3]. # This class facilitates the creation of QAOA circuits with # various types of mixer operators and allows execution on a quantum simulator # backend provided by Qiskit. # # The `Qaoa` class provides methods to: # - Initialize with QAOA parameters, graph instance, mixer type, and backend settings # - Create cost operator and various mixer operators (x, xx, y, yy, xy) # - Generate the complete QAOA circuit # # Initialization parameters include the number of QAOA layers, angles for the # mixer and cost operators, and options for setting verbosity, measurement, and # random seed. The class checks for consistency in the provided parameters and # supports visualizing the graph and QAOA circuit. # # Refs. # [1] https://arxiv.org/abs/1411.4028 # [2] https://learning.quantum.ibm.com/tutorial/quantum-approximate-optimization-algorithm # [3] https://en.wikipedia.org/wiki/Maximum_cut # # © Leonardo Lavagna 2024 # @ NESYA https://github.com/NesyaLab #------------------------------------------------------------------------------ import numpy as np from matplotlib import pyplot as plt from classes import Problems as P from functions import qaoa_utilities as utils from qiskit import QuantumCircuit from qiskit_aer import Aer from typing import List, Tuple from networkx import Graph from qiskit.circuit import ParameterVector class Qaoa: def __init__(self, p: int = 0, G: Graph = None, betas: List[float] = None, gammas: List[float] = None, mixer: str = "x", backend = Aer.get_backend('qasm_simulator'), measure: bool = True, seed: int = None, verbose: bool = True): """Initialize class QAOA. Args: p (int): Positive number of QAOA layers. The default is 0. G (Graph): A graph created with the Problem class used as MaxCut problem instance. The default is None. betas (float): Angles for the mixer operator. gammas (float): Angles for the cost operator. mixer (str): Type of mixer operator to be used. The default is "x". backend (Qiskit backend): Qiskit backend to execute the code on a quantum simulator. The default is Aer.get_backend('qasm_simulator'). measure (bool): If True measure the qaoa circuit. The default is True. seed (int): Seed for a pseudo-random number generator. The default is None. verbose (bool): If True enters in debugging mode. The default is True. """ # Setup self.p = p self.G = G self.mixer = mixer self.backend = backend self.measure = measure self.verbose = verbose self.seed = seed self.problems_class = P.Problems(p_type="custom", G=self.G) if self.seed is not None: np.random.seed(self.seed) if self.G is None: self.N = 0 self.w = [[]] self.betas = [] self.gammas = [] if self.G is not None: self.N = G.get_number_of_nodes() self.w = G.get_adjacency_matrix() if betas is None or gammas is None: self.betas = utils.generate_parameters(n=self.p, k=1) self.gammas = utils.generate_parameters(n=self.p, k=2) if betas is not None and gammas is not None: self.betas = betas self.gammas = gammas # Checking... if self.problems_class.__class__.__name__ != self.G.__class__.__name__ and G is not None: raise Exception("Invalid parameters. The graph G should be created with the Problems class.") if (self.p == 0 and self.G is not None) or (self.p > 0 and G is None): raise ValueError("If G is not the empty graph p should be a strictly positive integer, and viceversa.") if len(self.betas) != p or len(self.gammas) != p or len(self.betas) != len(self.gammas): raise ValueError("Invalid angles list. The length of betas and gammas should be equal to p.") # Initializing... if self.verbose is True: print(" --------------------------- ") print("| Intializing Qaoa class... |".upper()) print(" --------------------------- ") print("-> Getting problem instance...".upper()) if self.G is not None: self.G.get_draw() plt.show() if self.G is None: print("\t * G = ø") if self.betas is None and self.G is not None: print("-> Beta angles not provided. Generating angles...".upper()) print(f"\t * betas = {self.betas}") if self.gammas is None and self.G is not None: print("-> Gamma angles not provided. Generating angles...".upper()) print(f"\t * gammas = {self.gammas}") print("-> Getting the ansatz...".upper()) if self.G is not None: print(self.get_circuit()) if self.G is None: print("\t * Qaoa circuit = ø") print("-> The Qaoa class was initialized with the following parameters.".upper()) print(f"\t * Number of layers: p = {self.p};") if self.G is None: print(f"\t * Graph: G = ø;") if self.G is not None: print(f"\t * Graph: G = {self.G.p_type};") print("\t * Angles:") print(f"\t\t - betas = {self.betas};") print(f"\t\t - gammas = {self.gammas};") print(f"\t * Mixer Hamiltonian type: '{self.mixer}';") print(f"\t * Random seed: seed = {self.seed};") print(f"\t * Measurement setting: measure = {self.measure}.") def cost_operator(self, gamma: float) -> QuantumCircuit: """Create an instance of the cost operator with angle 'gamma'. Args: gamma (float): Angle for the cost operator. Returns: QuantumCircuit: Circuit representing the cost operator. """ qc = QuantumCircuit(self.N, self.N) for i,j in self.G.get_edges(): qc.cx(i, j) qc.rz(gamma, j) qc.cx(i, j) return qc def x_mixer_operator(self, beta: float) -> QuantumCircuit: """Create an instance of the x-mixer operator with angle 'beta'. Args: beta (float): Angle for the mixer operator. Returns: QuantumCircuit: Circuit representing the mixer operator. """ qc = QuantumCircuit(self.N, self.N) for v in self.G.get_nodes(): qc.rx(beta, v) return qc def xx_mixer_operator(self, beta: float) -> QuantumCircuit: """Create an instance of the xx-mixer operator with angle 'beta'. Args: beta (float): Angle for the mixer operator. Returns: QuantumCircuit: Circuit representing the mixer operator. """ qc = QuantumCircuit(self.N, self.N) for i, j in self.G.get_edges(): if self.w[i, j] > 0: qc.rxx(beta, i, j) return qc def y_mixer_operator(self, beta: float) -> QuantumCircuit: """Create an instance of the y-mixer operator with angle 'beta'. Args: beta (float): Angle for the mixer operator. Returns: QuantumCircuit: Circuit representing the mixer operator. """ qc = QuantumCircuit(self.N, self.N) for v in self.G.get_nodes(): qc.ry(2 * beta, v) return qc def yy_mixer_operator(self, beta: float) -> QuantumCircuit: """Create an instance of the yy-mixer operator with angle 'beta'. Args: beta (float): Time-slice angle for the mixer operator. Returns: QuantumCircuit: Circuit representing the mixer operator. """ qc = QuantumCircuit(self.N, self.N) for i, j in self.G.get_edges(): if self.w[i, j] > 0: qc.ryy(beta / 2, i, j) return qc def xy_mixer_operator(self, phi: float, psi: float) -> QuantumCircuit: """Create an instance of the xy-mixer operator with angle 'beta'. Args: beta (float): Angle for the mixer operator. Returns: QuantumCircuit: Circuit representing the mixer operator. """ qc = QuantumCircuit(self.N, self.N) # X_iX_j for i, j in self.G.get_edges(): if self.w[i, j] > 0: qc.rxx(phi / 2, i, j) # Y_iY_j for i, j in self.G.get_edges(): if self.w[i, j] > 0: qc.ryy(psi / 2, i, j) return qc def get_circuit(self) -> QuantumCircuit: """Create an instance of the Qaoa circuit with given parameters. Returns: QuantumCircuit: Circuit representing the Qaoa. """ qc = QuantumCircuit(self.N, self.N) params = ParameterVector("params", 2 * self.p) betas = params[0 : self.p] gammas = params[self.p : 2 * self.p] qc.h(range(self.N)) qc.barrier(range(self.N)) for i in range(self.p): qc = qc.compose(self.cost_operator(gammas[i])) qc.barrier(range(self.N)) if self.mixer == "x": qc = qc.compose(self.x_mixer_operator(betas[i])) qc.barrier(range(self.N)) elif self.mixer == "xx": qc = qc.compose(self.xx_mixer_operator(betas[i])) qc.barrier(range(self.N)) elif self.mixer == "y": qc = qc.compose(self.y_mixer_operator(betas[i])) qc.barrier(range(self.N)) elif self.mixer == "yy": qc = qc.compose(self.yy_mixer_operator(betas[i])) qc.barrier(range(self.N)) elif self.mixer == "xy": qc = qc.compose(self.xy_mixer_operator(betas[i],betas[i])) qc.barrier(range(self.N)) qc.barrier(range(self.N)) if self.measure: qc.measure(range(self.N), range(self.N)) return qc
https://github.com/a24l/IBM_Qiskit_QGSS
a24l
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit_textbook.problems import dj_problem_oracle def lab1_ex1(): qc = QuantumCircuit(1) qc.z(0) qc.x(0) return qc state = Statevector.from_instruction(lab1_ex1()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex1 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex1(lab1_ex1()) def lab1_ex2(): qc = QuantumCircuit(1) qc.h(0) # # # FILL YOUR CODE IN HERE # # return qc state = Statevector.from_instruction(lab1_ex2()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex2 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex2(lab1_ex2()) def lab1_ex3(): qc = QuantumCircuit(1) qc.h(0) qc.z(0) # # # FILL YOUR CODE IN HERE # # return qc state = Statevector.from_instruction(lab1_ex3()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex3 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex3(lab1_ex3()) def lab1_ex4(): qc = QuantumCircuit(1) qc.h(0) qc.y(0) qc.sdg(0) qc.sdg(0) qc.sdg(0) # # # FILL YOUR CODE IN HERE # # return qc state = Statevector.from_instruction(lab1_ex4()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex4 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex4(lab1_ex4()) def lab1_ex5(): qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement qc.h(0) qc.cx(0,1) qc.x(1) # # # FILL YOUR CODE IN HERE # # return qc qc = lab1_ex5() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex5 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex5(lab1_ex5()) qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0 qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1 backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities def lab1_ex6(): qc = QuantumCircuit(3,3) # this time, we not only want two qubits, but also two classical bits for the measurement qc.h(0) qc.cx(0,1) qc.x(1) qc.cx(1,2) qc.y(2) # # # FILL YOUR CODE IN HERE # # return qc qc = lab1_ex6() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex6 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex6(lab1_ex6()) oraclenr = 4 # determines the oracle (can range from 1 to 5) oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles oracle.name = "DJ-Oracle" def dj_classical(n, input_str): # build a quantum circuit with n qubits and 1 classical readout bit dj_circuit = QuantumCircuit(n+1,1) # Prepare the initial state corresponding to your input bit string for i in range(n): if input_str[i] == '1': dj_circuit.x(i) # append oracle dj_circuit.append(oracle, range(n+1)) # measure the fourth qubit dj_circuit.measure(n,0) return dj_circuit n = 4 # number of qubits input_str = '1111' dj_circuit = dj_classical(n, input_str) dj_circuit.draw() # draw the circuit input_str = '1111' dj_circuit = dj_classical(n, input_str) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit, qasm_sim) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) def lab1_ex7(): min_nr_inputs = 2# put your answer here max_nr_inputs = 9# put your answer here return [min_nr_inputs, max_nr_inputs] from qc_grader import grade_lab1_ex7 # Note that the grading function is expecting a list of two integers grade_lab1_ex7(lab1_ex7()) n=4 def psi_0(n): qc = QuantumCircuit(n+1,n) qc.x(4) # Build the state (|00000> - |10000>)/sqrt(2) # # # FILL YOUR CODE IN HERE # # return qc dj_circuit = psi_0(n) dj_circuit.draw() def psi_1(n): # obtain the |psi_0> = |00001> state qc = psi_0(n) for qubit in range(n+1): qc.h(qubit) # create the superposition state |psi_1> # # # FILL YOUR CODE IN HERE # # return qc dj_circuit = psi_1(n) dj_circuit.draw() def psi_2(oracle,n): # circuit to obtain psi_1 qc = psi_1(n) # append the oracle qc.append(oracle, range(n+1)) return qc dj_circuit = psi_2(oracle, n) dj_circuit.draw() def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25]) qc = psi_2(oracle, n) # apply n-fold hadamard gate # # # FILL YOUR CODE IN HERE # # for qubit in range(n): qc.h(qubit) # add the measurement by connecting qubits to classical bits # # # FILL YOUR CODE IN HERE # # for i in range(n): qc.measure(i, i) return qc dj_circuit = lab1_ex8(oracle, n) dj_circuit.draw() from qc_grader import grade_lab1_ex8 # Note that the grading function is expecting a quantum circuit with measurements grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n)) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/miamico/Quantum_Generative_Adversarial_Networks
miamico
%%capture %pip install qiskit %pip install qiskit_ibm_provider %pip install qiskit-aer # Importing standard Qiskit libraries from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer from qiskit_ibm_provider import IBMProvider from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.circuit.library import C3XGate # Importing matplotlib import matplotlib.pyplot as plt # Importing Numpy, Cmath and math import numpy as np import os, math, cmath from numpy import pi # Other imports from IPython.display import display, Math, Latex # Specify the path to your env file env_file_path = 'config.env' # Load environment variables from the file os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#')) # Load IBM Provider API KEY IBMP_API_KEY = os.environ.get('IBMP_API_KEY') # Loading your IBM Quantum account(s) IBMProvider.save_account(IBMP_API_KEY, overwrite=True) # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') qc_b1 = QuantumCircuit(2, 2) qc_b1.h(0) qc_b1.cx(0, 1) qc_b1.draw(output='mpl', style="iqp") sv = backend.run(qc_b1).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ") qc_b2 = QuantumCircuit(2, 2) qc_b2.x(0) qc_b2.h(0) qc_b2.cx(0, 1) qc_b2.draw(output='mpl', style="iqp") sv = backend.run(qc_b2).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ") qc_b2 = QuantumCircuit(2, 2) qc_b2.h(0) qc_b2.cx(0, 1) qc_b2.z(0) qc_b2.draw(output='mpl', style="iqp") sv = backend.run(qc_b2).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ") qc_b3 = QuantumCircuit(2, 2) qc_b3.x(1) qc_b3.h(0) qc_b3.cx(0, 1) qc_b3.draw(output='mpl', style="iqp") sv = backend.run(qc_b3).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ") qc_b3 = QuantumCircuit(2, 2) qc_b3.h(0) qc_b3.cx(0, 1) qc_b3.x(0) qc_b3.draw(output='mpl', style="iqp") sv = backend.run(qc_b3).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ") qc_b4 = QuantumCircuit(2, 2) qc_b4.x(0) qc_b4.h(0) qc_b4.x(1) qc_b4.cx(0, 1) qc_b4.draw(output='mpl', style="iqp") sv = backend.run(qc_b4).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ") qc_b4 = QuantumCircuit(2, 2) qc_b4.h(0) qc_b4.cx(0, 1) qc_b4.x(0) qc_b4.z(1) qc_b4.draw(output='mpl', style="iqp") sv = backend.run(qc_b4).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ") def sv_latex_from_qc(qc, backend): sv = backend.run(qc).result().get_statevector() return sv.draw(output='latex') qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(1) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(1) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(1) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(3) sv_latex_from_qc(qc_ej2, backend) def circuit_adder (num): if num<1 or num>8: raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo. # Definición del circuito base que vamos a construir qreg_q = QuantumRegister(4, 'q') creg_c = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qreg_q, creg_c) qbit_position = 0 for element in reversed(np.binary_repr(num)): if (element=='1'): circuit.barrier() match qbit_position: case 0: # +1 circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]]) circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) circuit.x(qreg_q[0]) case 1: # +2 circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3]) circuit.cx(qreg_q[1], qreg_q[2]) circuit.x(qreg_q[1]) case 2: # +4 circuit.cx(qreg_q[2], qreg_q[3]) circuit.x(qreg_q[2]) case 3: # +8 circuit.x(qreg_q[3]) qbit_position+=1 return circuit add_3 = circuit_adder(3) add_3.draw(output='mpl', style="iqp") qc_test_2 = QuantumCircuit(4, 4) qc_test_2.x(1) qc_test_2_plus_3 = qc_test_2.compose(add_3) qc_test_2_plus_3.draw(output='mpl', style="iqp") sv_latex_from_qc(qc_test_2_plus_3, backend) qc_test_7 = QuantumCircuit(4, 4) qc_test_7.x(0) qc_test_7.x(1) qc_test_7.x(2) qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8)) sv_latex_from_qc(qc_test_7_plus_8, backend) #qc_test_7_plus_8.draw() theta = 6.544985 phi = 2.338741 lmbda = 0 alice_1 = 0 alice_2 = 1 bob_1 = 2 qr_alice = QuantumRegister(2, 'Alice') qr_bob = QuantumRegister(1, 'Bob') cr = ClassicalRegister(3, 'c') qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr) qc_ej3.barrier(label='1') qc_ej3.u(theta, phi, lmbda, alice_1); qc_ej3.barrier(label='2') qc_ej3.h(alice_2) qc_ej3.cx(alice_2, bob_1); qc_ej3.barrier(label='3') qc_ej3.cx(alice_1, alice_2) qc_ej3.h(alice_1); qc_ej3.barrier(label='4') qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]); qc_ej3.barrier(label='5') qc_ej3.x(bob_1).c_if(alice_2, 1) qc_ej3.z(bob_1).c_if(alice_1, 1) qc_ej3.measure(bob_1, bob_1); qc_ej3.draw(output='mpl', style="iqp") result = backend.run(qc_ej3, shots=1024).result() counts = result.get_counts() plot_histogram(counts) sv_0 = np.array([1, 0]) sv_1 = np.array([0, 1]) def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10): """ Check if the given numerical value corresponds to a symbolic constant within a specified tolerance. Parameters: - value (float): The numerical value to check. - symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations. Defaults to {1/np.sqrt(2): '1/√2'}. - tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10. Returns: str or float: If a match is found, returns the symbolic representation as a string (prefixed with '-' if the value is negative); otherwise, returns the original value. """ for constant, symbol in symbolic_constants.items(): if np.isclose(abs(value), constant, atol=tolerance): return symbol if value >= 0 else '-' + symbol return value def array_to_dirac_notation(array, tolerance=1e-10): """ Convert a complex-valued array representing a quantum state in superposition to Dirac notation. Parameters: - array (numpy.ndarray): The complex-valued array representing the quantum state in superposition. - tolerance (float): Tolerance for considering amplitudes as negligible. Returns: str: The Dirac notation representation of the quantum state. """ # Ensure the statevector is normalized array = array / np.linalg.norm(array) # Get the number of qubits num_qubits = int(np.log2(len(array))) # Find indices where amplitude is not negligible non_zero_indices = np.where(np.abs(array) > tolerance)[0] # Generate Dirac notation terms terms = [ (find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b")) for i in non_zero_indices ] # Format Dirac notation dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms]) return dirac_notation def array_to_matrix_representation(array): """ Convert a one-dimensional array to a column matrix representation. Parameters: - array (numpy.ndarray): The one-dimensional array to be converted. Returns: numpy.ndarray: The column matrix representation of the input array. """ # Replace symbolic constants with their representations matrix_representation = np.array([find_symbolic_representation(value) or value for value in array]) # Return the column matrix representation return matrix_representation.reshape((len(matrix_representation), 1)) def array_to_dirac_and_matrix_latex(array): """ Generate LaTeX code for displaying both the matrix representation and Dirac notation of a quantum state. Parameters: - array (numpy.ndarray): The complex-valued array representing the quantum state. Returns: Latex: A Latex object containing LaTeX code for displaying both representations. """ matrix_representation = array_to_matrix_representation(array) latex = "Matrix representation\n\\begin{bmatrix}\n" + \ "\\\\\n".join(map(str, matrix_representation.flatten())) + \ "\n\\end{bmatrix}\n" latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}' return Latex(latex) sv_b1 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b1) sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b1) sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b1) sv_b2 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b3 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = np.kron(sv_0, sv_1) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b4 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = np.kron(sv_0, sv_1) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b4)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import 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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # Build a quantum circuit circuit = QuantumCircuit(3, 3) circuit.x(1) circuit.h(range(3)) circuit.cx(0, 1) circuit.measure(range(3), range(3)); print(circuit) circuit.draw() # Matplotlib Drawing circuit.draw(output='mpl') # Draw a new circuit with barriers and more registers q_a = QuantumRegister(3, name='qa') q_b = QuantumRegister(5, name='qb') c_a = ClassicalRegister(3) c_b = ClassicalRegister(5) circuit = QuantumCircuit(q_a, q_b, c_a, c_b) circuit.x(q_a[1]) circuit.x(q_b[1]) circuit.x(q_b[2]) circuit.x(q_b[4]) circuit.barrier() circuit.h(q_a) circuit.barrier(q_a) circuit.h(q_b) circuit.cswap(q_b[0], q_b[1], q_b[2]) circuit.cswap(q_b[2], q_b[3], q_b[4]) circuit.cswap(q_b[3], q_b[4], q_b[0]) circuit.barrier(q_b) circuit.measure(q_a, c_a) circuit.measure(q_b, c_b); # Draw the circuit circuit.draw(output='mpl') # Draw the circuit with reversed bit order circuit.draw(output='mpl', reverse_bits=True) # Draw the circuit without barriers circuit.draw(output='mpl', plot_barriers=False) # Draw the circuit without barriers and reverse bit order circuit.draw(output='mpl', plot_barriers=False, reverse_bits=True) # Set line length to 80 for above circuit circuit.draw(output='text') # Change the background color in mpl style = {'backgroundcolor': 'lightgreen'} circuit.draw(output='mpl', style=style) # Scale the mpl output to 1/2 the normal size circuit.draw(output='mpl', scale=0.5) from qiskit.tools.visualization import circuit_drawer circuit_drawer(circuit, output='mpl', plot_barriers=False) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2023, 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for Statevector Sampler.""" from __future__ import annotations import unittest import numpy as np from numpy.typing import NDArray from qiskit import ClassicalRegister, QiskitError, QuantumCircuit, QuantumRegister from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, UnitaryGate from qiskit.primitives import PrimitiveResult, PubResult from qiskit.primitives.containers import BitArray from qiskit.primitives.containers.data_bin import DataBin from qiskit.primitives.containers.sampler_pub import SamplerPub from qiskit.primitives.statevector_sampler import StatevectorSampler from qiskit.providers import JobStatus from test import QiskitTestCase # pylint: disable=wrong-import-order class TestStatevectorSampler(QiskitTestCase): """Test for StatevectorSampler""" def setUp(self): super().setUp() self._shots = 10000 self._seed = 123 self._cases = [] hadamard = QuantumCircuit(1, 1, name="Hadamard") hadamard.h(0) hadamard.measure(0, 0) self._cases.append((hadamard, None, {0: 5000, 1: 5000})) # case 0 bell = QuantumCircuit(2, name="Bell") bell.h(0) bell.cx(0, 1) bell.measure_all() self._cases.append((bell, None, {0: 5000, 3: 5000})) # case 1 pqc = RealAmplitudes(num_qubits=2, reps=2) pqc.measure_all() self._cases.append((pqc, [0] * 6, {0: 10000})) # case 2 self._cases.append((pqc, [1] * 6, {0: 168, 1: 3389, 2: 470, 3: 5973})) # case 3 self._cases.append((pqc, [0, 1, 1, 2, 3, 5], {0: 1339, 1: 3534, 2: 912, 3: 4215})) # case 4 self._cases.append((pqc, [1, 2, 3, 4, 5, 6], {0: 634, 1: 291, 2: 6039, 3: 3036})) # case 5 pqc2 = RealAmplitudes(num_qubits=2, reps=3) pqc2.measure_all() self._cases.append( (pqc2, [0, 1, 2, 3, 4, 5, 6, 7], {0: 1898, 1: 6864, 2: 928, 3: 311}) ) # case 6 def _assert_allclose(self, bitarray: BitArray, target: NDArray | BitArray, rtol=1e-1): self.assertEqual(bitarray.shape, target.shape) for idx in np.ndindex(bitarray.shape): int_counts = bitarray.get_int_counts(idx) target_counts = ( target.get_int_counts(idx) if isinstance(target, BitArray) else target[idx] ) max_key = max(max(int_counts.keys()), max(target_counts.keys())) ary = np.array([int_counts.get(i, 0) for i in range(max_key + 1)]) tgt = np.array([target_counts.get(i, 0) for i in range(max_key + 1)]) np.testing.assert_allclose(ary, tgt, rtol=rtol, err_msg=f"index: {idx}") def test_sampler_run(self): """Test run().""" with self.subTest("single"): bell, _, target = self._cases[1] sampler = StatevectorSampler(seed=self._seed) job = sampler.run([bell], shots=self._shots) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array(target)) with self.subTest("single with param"): pqc, param_vals, target = self._cases[2] sampler = StatevectorSampler(seed=self._seed) params = (param.name for param in pqc.parameters) job = sampler.run([(pqc, {params: param_vals})], shots=self._shots) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array(target)) with self.subTest("multiple"): pqc, param_vals, target = self._cases[2] sampler = StatevectorSampler(seed=self._seed) params = (param.name for param in pqc.parameters) job = sampler.run( [(pqc, {params: [param_vals, param_vals, param_vals]})], shots=self._shots ) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array([target, target, target])) def test_sampler_run_multiple_times(self): """Test run() returns the same results if the same input is given.""" bell, _, _ = self._cases[1] sampler = StatevectorSampler(seed=self._seed) result1 = sampler.run([bell], shots=self._shots).result() meas1 = result1[0].data.meas result2 = sampler.run([bell], shots=self._shots).result() meas2 = result2[0].data.meas self._assert_allclose(meas1, meas2, rtol=0) def test_sample_run_multiple_circuits(self): """Test run() with multiple circuits.""" bell, _, target = self._cases[1] sampler = StatevectorSampler(seed=self._seed) result = sampler.run([bell, bell, bell], shots=self._shots).result() self.assertEqual(len(result), 3) self._assert_allclose(result[0].data.meas, np.array(target)) self._assert_allclose(result[1].data.meas, np.array(target)) self._assert_allclose(result[2].data.meas, np.array(target)) def test_sampler_run_with_parameterized_circuits(self): """Test run() with parameterized circuits.""" pqc1, param1, target1 = self._cases[4] pqc2, param2, target2 = self._cases[5] pqc3, param3, target3 = self._cases[6] sampler = StatevectorSampler(seed=self._seed) result = sampler.run( [(pqc1, param1), (pqc2, param2), (pqc3, param3)], shots=self._shots ).result() self.assertEqual(len(result), 3) self._assert_allclose(result[0].data.meas, np.array(target1)) self._assert_allclose(result[1].data.meas, np.array(target2)) self._assert_allclose(result[2].data.meas, np.array(target3)) def test_run_1qubit(self): """test for 1-qubit cases""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc, qc2], shots=self._shots).result() self.assertEqual(len(result), 2) for i in range(2): self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) def test_run_2qubit(self): """test for 2-qubit cases""" qc0 = QuantumCircuit(2) qc0.measure_all() qc1 = QuantumCircuit(2) qc1.x(0) qc1.measure_all() qc2 = QuantumCircuit(2) qc2.x(1) qc2.measure_all() qc3 = QuantumCircuit(2) qc3.x([0, 1]) qc3.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc0, qc1, qc2, qc3], shots=self._shots).result() self.assertEqual(len(result), 4) for i in range(4): self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) def test_run_single_circuit(self): """Test for single circuit case.""" with self.subTest("No parameter"): circuit, _, target = self._cases[1] param_target = [ (None, np.array(target)), ({}, np.array(target)), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target) with self.subTest("One parameter"): circuit = QuantumCircuit(1, 1, name="X gate") param = Parameter("x") circuit.ry(param, 0) circuit.measure(0, 0) param_target = [ ({"x": np.pi}, np.array({1: self._shots})), ({param: np.pi}, np.array({1: self._shots})), ({"x": np.array(np.pi)}, np.array({1: self._shots})), ({param: np.array(np.pi)}, np.array({1: self._shots})), ({"x": [np.pi]}, np.array({1: self._shots})), ({param: [np.pi]}, np.array({1: self._shots})), ({"x": np.array([np.pi])}, np.array({1: self._shots})), ({param: np.array([np.pi])}, np.array({1: self._shots})), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.c, target) with self.subTest("More than one parameter"): circuit, param, target = self._cases[3] param_target = [ (param, np.array(target)), (tuple(param), np.array(target)), (np.array(param), np.array(target)), ((param,), np.array([target])), ([param], np.array([target])), (np.array([param]), np.array([target])), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target) def test_run_reverse_meas_order(self): """test for sampler with reverse measurement order""" x = Parameter("x") y = Parameter("y") qc = QuantumCircuit(3, 3) qc.rx(x, 0) qc.rx(y, 1) qc.x(2) qc.measure(0, 2) qc.measure(1, 1) qc.measure(2, 0) sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(qc, [0, 0]), (qc, [np.pi / 2, 0])], shots=self._shots).result() self.assertEqual(len(result), 2) # qc({x: 0, y: 0}) self._assert_allclose(result[0].data.c, np.array({1: self._shots})) # qc({x: pi/2, y: 0}) self._assert_allclose(result[1].data.c, np.array({1: self._shots / 2, 5: self._shots / 2})) def test_run_errors(self): """Test for errors with run method""" qc1 = QuantumCircuit(1) qc1.measure_all() qc2 = RealAmplitudes(num_qubits=1, reps=1) qc2.measure_all() qc3 = QuantumCircuit(1, 1) with qc3.for_loop(range(5)): qc3.h(0) sampler = StatevectorSampler() with self.subTest("set parameter values to a non-parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, [1e2])]).result() with self.subTest("missing all parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2]).result() with self.assertRaises(ValueError): _ = sampler.run([(qc2, [])]).result() with self.assertRaises(ValueError): _ = sampler.run([(qc2, None)]).result() with self.subTest("missing some parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc2, [1e2])]).result() with self.subTest("too many parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc2, [1e2] * 100)]).result() with self.subTest("with control flow"): with self.assertRaises(QiskitError): _ = sampler.run([qc3]).result() with self.subTest("negative shots, run arg"): with self.assertRaises(ValueError): _ = sampler.run([qc1], shots=-1).result() with self.subTest("negative shots, pub-like"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, None, -1)]).result() with self.subTest("negative shots, pub"): with self.assertRaises(ValueError): _ = sampler.run([SamplerPub(qc1, shots=-1)]).result() with self.subTest("zero shots, run arg"): with self.assertRaises(ValueError): _ = sampler.run([qc1], shots=0).result() with self.subTest("zero shots, pub-like"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, None, 0)]).result() with self.subTest("zero shots, pub"): with self.assertRaises(ValueError): _ = sampler.run([SamplerPub(qc1, shots=0)]).result() with self.subTest("missing []"): with self.assertRaisesRegex(ValueError, "An invalid Sampler pub-like was given"): _ = sampler.run(qc1).result() with self.subTest("missing [] for pqc"): with self.assertRaisesRegex(ValueError, "Note that if you want to run a single pub,"): _ = sampler.run((qc2, [0, 1])).result() def test_run_empty_parameter(self): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) sampler = StatevectorSampler(seed=self._seed) with self.subTest("one circuit"): result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.c, np.array({0: self._shots})) with self.subTest("two circuits"): result = sampler.run([qc, qc], shots=self._shots).result() self.assertEqual(len(result), 2) for i in range(2): self._assert_allclose(result[i].data.c, np.array({0: self._shots})) def test_run_numpy_params(self): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2) qc.measure_all() k = 5 params_array = np.linspace(0, 1, k * qc.num_parameters).reshape((k, qc.num_parameters)) params_list = params_array.tolist() sampler = StatevectorSampler(seed=self._seed) target = sampler.run([(qc, params_list)], shots=self._shots).result() with self.subTest("ndarray"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(qc, params_array)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target[0].data.meas) with self.subTest("split a list"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run( [(qc, params) for params in params_list], shots=self._shots ).result() self.assertEqual(len(result), k) for i in range(k): self._assert_allclose( result[i].data.meas, np.array(target[0].data.meas.get_int_counts(i)) ) def test_run_with_shots_option(self): """test with shots option.""" bell, _, _ = self._cases[1] shots = 100 with self.subTest("run arg"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([bell], shots=shots).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], shots) with self.subTest("default shots"): sampler = StatevectorSampler(seed=self._seed) default_shots = sampler.default_shots result = sampler.run([bell]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, default_shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], default_shots) with self.subTest("setting default shots"): default_shots = 100 sampler = StatevectorSampler(default_shots=default_shots, seed=self._seed) self.assertEqual(sampler.default_shots, default_shots) result = sampler.run([bell]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, default_shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], default_shots) with self.subTest("pub-like"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(bell, None, shots)]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], shots) with self.subTest("pub"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([SamplerPub(bell, shots=shots)]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], shots) with self.subTest("multiple pubs"): sampler = StatevectorSampler(seed=self._seed) shots1 = 100 shots2 = 200 result = sampler.run( [ SamplerPub(bell, shots=shots1), SamplerPub(bell, shots=shots2), ], shots=self._shots, ).result() self.assertEqual(len(result), 2) self.assertEqual(result[0].data.meas.num_shots, shots1) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots1) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], shots1) self.assertEqual(result[1].data.meas.num_shots, shots2) self.assertEqual(sum(result[1].data.meas.get_counts().values()), shots2) self.assertIn("shots", result[1].metadata) self.assertEqual(result[1].metadata["shots"], shots2) def test_run_shots_result_size(self): """test with shots option to validate the result size""" n = 10 qc = QuantumCircuit(n) qc.h(range(n)) qc.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) self.assertLessEqual(result[0].data.meas.num_shots, self._shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), self._shots) def test_primitive_job_status_done(self): """test primitive job's status""" bell, _, _ = self._cases[1] sampler = StatevectorSampler(seed=self._seed) job = sampler.run([bell], shots=self._shots) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_seed(self): """Test for seed options""" with self.subTest("empty"): sampler = StatevectorSampler() self.assertIsNone(sampler.seed) with self.subTest("set int"): sampler = StatevectorSampler(seed=self._seed) self.assertEqual(sampler.seed, self._seed) with self.subTest("set generator"): sampler = StatevectorSampler(seed=np.random.default_rng(self._seed)) self.assertIsInstance(sampler.seed, np.random.Generator) def test_circuit_with_unitary(self): """Test for circuit with unitary gate.""" with self.subTest("identity"): gate = UnitaryGate(np.eye(2)) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([circuit], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) with self.subTest("X"): gate = UnitaryGate([[0, 1], [1, 0]]) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([circuit], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({1: self._shots})) def test_circuit_with_multiple_cregs(self): """Test for circuit with multiple classical registers.""" cases = [] # case 1 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2, 2], [0, 2, 4, 5]) target = {"a": {0: 5000, 1: 5000}, "b": {0: 5000, 2: 5000}, "c": {0: 5000, 6: 5000}} cases.append(("use all cregs", qc, target)) # case 2 a = ClassicalRegister(1, "a") b = ClassicalRegister(5, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2, 2], [0, 2, 4, 5]) target = { "a": {0: 5000, 1: 5000}, "b": {0: 2500, 2: 2500, 24: 2500, 26: 2500}, "c": {0: 10000}, } cases.append(("use only a and b", qc, target)) # case 3 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure(1, 5) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 5000, 4: 5000}} cases.append(("use only c", qc, target)) # case 4 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2], [5, 5, 5]) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 5000, 4: 5000}} cases.append(("use only c multiple qubits", qc, target)) # case 5 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 10000}} cases.append(("no measure", qc, target)) for title, qc, target in cases: with self.subTest(title): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) data = result[0].data self.assertEqual(len(data), 3) for creg in qc.cregs: self.assertTrue(hasattr(data, creg.name)) self._assert_allclose(getattr(data, creg.name), np.array(target[creg.name])) def test_circuit_with_aliased_cregs(self): """Test for circuit with aliased classical registers.""" q = QuantumRegister(3, "q") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c1, c2) qc.ry(np.pi / 4, 2) qc.cx(2, 1) qc.cx(0, 1) qc.h(0) qc.measure(0, c1) qc.measure(1, c2) qc.z(2).c_if(c1, 1) qc.x(2).c_if(c2, 1) qc2 = QuantumCircuit(5, 5) qc2.compose(qc, [0, 2, 3], [2, 4], inplace=True) cregs = [creg.name for creg in qc2.cregs] target = { cregs[0]: {0: 4255, 4: 4297, 16: 720, 20: 726}, cregs[1]: {0: 5000, 1: 5000}, cregs[2]: {0: 8500, 1: 1500}, } sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc2], shots=self._shots).result() self.assertEqual(len(result), 1) data = result[0].data self.assertEqual(len(data), 3) for creg_name, creg in target.items(): self.assertTrue(hasattr(data, creg_name)) self._assert_allclose(getattr(data, creg_name), np.array(creg)) def test_no_cregs(self): """Test that the sampler works when there are no classical register in the circuit.""" qc = QuantumCircuit(2) sampler = StatevectorSampler() with self.assertWarns(UserWarning): result = sampler.run([qc]).result() self.assertEqual(len(result), 1) self.assertEqual(len(result[0].data), 0) def test_iter_pub(self): """Test of an iterable of pubs""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = StatevectorSampler() result = sampler.run(iter([qc, qc2]), shots=self._shots).result() self.assertIsInstance(result, PrimitiveResult) self.assertEqual(len(result), 2) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[1], PubResult) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) self._assert_allclose(result[1].data.meas, np.array({1: self._shots})) if __name__ == "__main__": unittest.main()
https://github.com/noamsgl/IBMAscolaChallenge
noamsgl
import logging import sys import time from itertools import product import numpy as np import pandas as pd from qiskit import QuantumCircuit, execute from qiskit.circuit.library import U3Gate from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel, depolarizing_error, ReadoutError, thermal_relaxation_error def get_data_point(circ, theta, phi, lam, readout_params, depol_param, thermal_params, shots): """Generate a dict datapoint with the given circuit and noise parameters""" U3_gate_length = 7.111111111111112e-08 # extract parameters (p0_0, p1_0), (p0_1, p1_1) = readout_params depol_prob = depol_param t1, t2, population = thermal_params # Add Readout and Quantum Errors noise_model = NoiseModel() noise_model.add_all_qubit_readout_error(ReadoutError(readout_params)) noise_model.add_all_qubit_quantum_error(depolarizing_error(depol_param, 1), 'u3', warnings=False) noise_model.add_all_qubit_quantum_error( thermal_relaxation_error(t1, t2, U3_gate_length, excited_state_population=population), 'u3', warnings=False) job = execute(circ, QasmSimulator(), shots=shots, noise_model=noise_model) result = job.result() # add data point to DataFrame data_point = {'theta': theta, 'phi': phi, 'lam': lam, 'p0_0': p0_0, 'p1_0': p1_0, 'p0_1': p0_1, 'p1_1': p1_1, 'depol_prob': depol_prob, 't1': t1, 't2': t2, 'population': population, 'E': result.get_counts(0).get('1', 0) / shots} return data_point def get_noise_model_params(K=10, readout=True, thermal=True, depol=True): """generate a list of tuples for all noise params (readout_params, depol_param, thermal_params) """ # Simple implementation. Use this... noise_model_params = [] # Readout Error for p0_0 in np.linspace(0.94, 1.0, K, endpoint=True): for p1_1 in np.linspace(0.94, 1.0, K, endpoint=True): p1_0 = 1 - p0_0 p0_1 = 1 - p1_1 readout_params = (p0_0, p1_0), (p0_1, p1_1) # Thermal Error for t1 in np.linspace(34000, 190000, K, endpoint=True): for t2 in np.linspace(t1 / 5.6, t1 / 0.65, K, endpoint=True): for population in np.linspace(0, 1, K, endpoint=True): thermal_params = (t1, t2, population) # Depolarizing Error for depol_param in np.linspace(0, 0.001, K, endpoint=True): noise_model_params.append((readout_params, depol_param, thermal_params)) return noise_model_params # Inefficient implementation. Don't Use... """if readout: p0_0_iter = np.linspace(0.94, 1.0, K, endpoint=True) p1_1_iter = np.linspace(0.94, 1.0, K, endpoint=True) else: p0_0_iter = [1] p1_1_iter = [1] if depol: depol_iter = np.linspace(0, 0.001, K, endpoint=True) else: depol_iter = [0] if thermal: t1_iter = np.linspace(34000, 190000, K, endpoint=True) # thermal_iter = map(lambda t1: (t1, np.linspace(t1/5.6, t1/0.65, 10, endpoint=True)), t1_iter) thermal_iter = chain.from_iterable( map(lambda t1: product([t1], np.linspace(t1 / 5.6, t1 / 0.65, K, endpoint=True)), t1_iter)) else: thermal_iter = [(np.inf, np.inf)] iterator = product(p0_0_iter, p1_1_iter, depol_iter, thermal_iter) noise_model_params = [(((p0_0, 1 - p0_0), (1 - p1_1, p1_1)), depol, (t1, t2)) for p0_0, p1_1, depol, (t1, t2) in tqdm(iterator)] return noise_model_params""" def U3Dataset(angle_step=10, other_steps=10, shots=2048, readout=True, thermal=True, depol=True, save_dir=None): a_logger = logging.getLogger(__name__) # the array to hold dataset array = np.empty() # the dictionary to pass to pandas dataframe data = {} # a counter to use to add entries to "data" i = 0 # a counter to use to log circuit number j = 0 # Iterate over all U3 gates for theta, phi, lam in product(np.linspace(0, 2 * np.pi, angle_step, endpoint=True), repeat=3): j = j + 1 # Generate sample data circ = QuantumCircuit(1, 1) circ.append(U3Gate(theta, phi, lam), [0]) circ.measure(0, 0) a_logger.info("Generating data points for circuit: {}/{}\n".format(j, angle_step ** 3) + str(circ)) start_time = time.time() for readout_params, depol_param, thermal_params in get_noise_model_params(other_steps, readout, thermal, depol): data_point = get_data_point(circ, theta, phi, lam, readout_params, depol_param, thermal_params, shots) data[i] = {'thet a': data_point['theta'], 'phi': data_point['phi'], 'lam': data_point['lam'], 'p0_0': data_point['p0_0'], 'p1_0': data_point['p1_0'], 'p0_1': data_point['p0_1'], 'p1_1': data_point['p1_1'], 'depol_prob': data_point['depol_prob'], 't1': data_point['t1'], 't2': data_point['t2'], 'population': data_point['population'], 'E': data_point['E']} i = i + 1 a_logger.info("Last circuit took: {:.2f} seconds.".format(time.time() - start_time)) # set the 'orient' parameter to "index" to make the keys as rows df = pd.DataFrame.from_dict(data, "index") # Save to CSV if save_dir is not None: df.to_csv(save_dir) return df # start main script if __name__ == '__main__': # create formatter formatter = logging.Formatter("%(asctime)s; %(message)s", "%y-%m-%d %H:%M:%S") # initialize logger a_logger = logging.getLogger(__name__) a_logger.setLevel(logging.INFO) # log to output file log_file_path = "../logs/output_{}.log".format(time.strftime("%Y%m%d-%H%M%S")) output_file_handler = logging.FileHandler(log_file_path, mode='w', encoding='utf-8') output_file_handler.setFormatter(formatter) a_logger.addHandler(output_file_handler) # log to stdout stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(formatter) a_logger.addHandler(stdout_handler) for n, m in [(12, 6)]: save_dir = '../datasets/universal_error/AllErrors/U3_{}_{}.csv'.format(n, m) a_logger.info("Starting dataset generation with resolution n = {}, m = {}.".format(n, m)) angle_step = n other_steps = m U3Dataset(angle_step=angle_step, other_steps=other_steps, readout=True, thermal=True, depol=True, save_dir=save_dir) a_logger.info("Finished dataset generation with resolution n = {}, m = {}.".format(n, m)) a_logger.info("Dataset saved to {}".format(save_dir)) a_logger.info("Exiting Gracefully")
https://github.com/TheGupta2012/QPE-Algorithms
TheGupta2012
from qiskit import QuantumCircuit, execute, transpile, Aer from qiskit.extensions import UnitaryGate,Initialize from qiskit.quantum_info import Statevector from qiskit.tools.visualization import plot_bloch_vector from qiskit.tools.visualization import plot_histogram,plot_bloch_multivector import numpy as np from time import sleep import sys from scipy.stats import unitary_group import matplotlib.pyplot as plt %matplotlib inline from qiskit import IBMQ # defining the absolute error in the eigenvalue deltas = [0.4, 0.3, 0.2, 0.15, 0.1, 0.05, 0.025, 0.01] # find the target costs for each of the algorithm target_costs = [] for i in deltas: cost = (np.cos(i))**2 target_costs.append(cost) target_costs u1 = unitary_group.rvs(2) u1 eigen_phases1, eigen_vectors1 = np.linalg.eig(u1) print("Eigen states of Unitary :",eigen_vectors1) eigen_phases1 = np.angle(eigen_phases1) ep1 = [] for k in eigen_phases1: if k < 0: ep1.append((k + 2*np.pi)/(2*np.pi)) else: ep1.append(k/(2*np.pi)) eigen_phases1 = np.array(ep1) print("Eigen phases of unitary :",eigen_phases1) from normal_SPEA import SPEA backend = Aer.get_backend('qasm_simulator') # looping and storing the results we get generated_deltas, errors = [],[] for delta,cost in zip(deltas,target_costs): spea = SPEA(u1,resolution=35,max_iters=15) max_differences = [] delta_error = [] print("TARGET COST :",cost) print("GIVEN DELTA :",delta) # doing numerous experiments to converge for exp in range(10): result = spea.get_eigen_pair(backend = backend,progress = False, randomize = True, target_cost = cost) print("Result with target cost as",cost,"was returned\n",result) # find the final cost theta = result['theta'] stop_cost = result['cost'] # find the maximum difference between the eigenphases and this returned phase max_diff = max(abs(eigen_phases1 - theta)) max_differences.append(max_diff) # now append this and the error from how it actually should have been # NOTE - there is no error if the max difference is actually less than # the delta desired . if delta - max_diff >= 0: error = 0 else: # this error should not be more than 5-6 % or 0.05 - 0.06 error = abs((delta - max_diff))/delta delta_error.append(error) # the maximum would be a better metric generated_deltas.append(np.average(max_differences)) errors.append(np.average(delta_error)) iters = [i for i in range(1,9)] plt.figure(figsize=(10,8)) plt.title("Plot for Generated and Given maximum $ \delta^{*}$ values",fontsize=16) plt.xlabel("Iteration Number", fontsize = 14) plt.ylabel("Values of $ \delta^{*}$ (maximum average error)",fontsize = 14) plt.grid() plt.plot(iters, deltas, label = 'Actual Values', color = 'black', alpha = 0.7, marker = 'o') plt.plot(iters, generated_deltas, label = 'Generated Values', color = 'green', alpha = 0.7, marker = 's') plt.legend() plt.savefig("Plot for verifying Cost Lower Bound.JPG",dpi = 200) plt.figure(figsize=(10,8)) plt.title("Plot for Error in Generated and Given maximum $ \delta^{*}$ values",fontsize=16) plt.xlabel("Iteration Number", fontsize = 14) plt.ylabel("Relative Error in $ \delta^{*}$",fontsize = 14) plt.grid() plt.plot(iters, errors, label = 'Error Values', color = 'cyan', alpha = 0.8, marker = 'o') plt.legend() plt.savefig("Plot for Error in Cost Lower Bound.JPG",dpi = 200)
https://github.com/victor-onofre/Quantum_Algorithms
victor-onofre
from qiskit import ClassicalRegister , QuantumCircuit, QuantumRegister import numpy as np qr = QuantumRegister(2) cr = ClassicalRegister(3) #For tree classicals bites qc = QuantumCircuit(qr , cr) qc.h(qr[0]) #auxiliary qubit qc.x(qr[1]) # eigenvector #qc.cp((3/2)*np.pi , qr[0] , qr[1]) qc.cp(3*np.pi , qr[0] , qr[1]) qc.h(qr[0]) qc.measure(qr[0] , cr[0]) # this is the controlled-U^(2^n-1) operator for determine phi_n qc.draw("mpl") qc.reset(qr[0]) qc.h(qr[0]) # la valeur du bit du poids le plus faible est dans cr[0]. #Si cr[0] = 1 on enléve le bit de poids le plus faible en fesant la rotation alpha_2 #et on continu le bit n-1 devient le bit le bit de poids le plus faible #si cr[0] est à 0 alors on peut appliquer directement la matrice unitaire associé sans avoir #à faire de rotation inverse alpha_k with qc.if_test((cr[0] , 1)) as else_: qc.p(-np.pi/2 , qr[0]) #qc.cp((3/8)*np.pi , qr[0] ,qr[1]) qc.cp((3/2)*np.pi , qr[0] ,qr[1]) qc.h(qr[0]) # For make measure in X basis {|0> , |1>} qc.measure(qr[0] , cr[1]) qc.draw("mpl") qc.reset(qr[0]) qc.h(qr[0]) # la valeur du bit du poids le plus faible est dans cr[0]. #Si cr[0] = 1 on enléve le bit de poids le plus faible en fesant la rotation alpha_2 #et on continu le bit n-1 devient le bit le bit de poids le plus faible #si cr[0] est à 0 alors on peut appliquer directement la matrice unitaire associé sans avoir #à faire de rotation inverse alpha_k with qc.if_test((cr[1] , 1)) as else_: qc.p(-(3/4)*np.pi , qr[0]) qc.cp((3/4)*np.pi , qr[0] ,qr[1]) qc.h(qr[0]) # For make measure in X basis {|0> , |1>} qc.measure(qr[0] , cr[2]) qc.draw("mpl") from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() counts import qiskit.tools.jupyter %qiskit_version_table
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
mathelatics
from qiskit.aqua.operators import WeightedPauliOperator pauli_dict = { 'paulis': [{"coeff": {"imag": 0.0, "real": -1.052373245772859}, "label": "II"}, {"coeff": {"imag": 0.0, "real": 0.39793742484318045}, "label": "ZI"}, {"coeff": {"imag": 0.0, "real": -0.39793742484318045}, "label": "IZ"}, {"coeff": {"imag": 0.0, "real": -0.01128010425623538}, "label": "ZZ"}, {"coeff": {"imag": 0.0, "real": 0.18093119978423156}, "label": "XX"} ] } qubit_op = WeightedPauliOperator.from_dict(pauli_dict) from qiskit.aqua.algorithms import NumPyMinimumEigensolver ee = NumPyMinimumEigensolver(qubit_op) result = ee.run() print(result.eigenvalue.real) from qiskit import BasicAer from qiskit.aqua.algorithms import VQE from qiskit.circuit.library import TwoLocal from qiskit.aqua.components.optimizers import L_BFGS_B var_form = TwoLocal(qubit_op.num_qubits, ['ry', 'rz'], 'cz', reps=3, entanglement='linear') optimizer = L_BFGS_B(maxfun=1000) vqe = VQE(qubit_op, var_form, optimizer) backend = BasicAer.get_backend('statevector_simulator') result = vqe.run(backend) print(result.eigenvalue.real) from qiskit.aqua import QuantumInstance var_form = TwoLocal(qubit_op.num_qubits, ['ry', 'rz'], 'cz', reps=3, entanglement='linear') optimizer = L_BFGS_B(maxfun=1000) vqe = VQE(qubit_op, var_form, optimizer) backend = BasicAer.get_backend('statevector_simulator') qi = QuantumInstance(backend=backend) result = vqe.run(qi) print(result.eigenvalue.real)
https://github.com/ratansahu05/Quantum-Computing-and-Programming
ratansahu05
from qiskit import QuantumCircuit from qiskit.tools.visualization import circuit_drawer import numpy as np from matplotlib import pyplot as plt n=5 qc = QuantumCircuit(n) qc.x(1) qc.ccx(0, 1, 3) qc.ccx(2, 3, 4) qc.ccx(0, 1, 3) qc.x(1) qc.draw('mpl') def phase_oracle(n, name = 'Uf'): qc = QuantumCircuit(n, name = name) qc.x(1) qc.ccx(0, 1, 3) qc.ccx(2, 3, 4) qc.ccx(0, 1, 3) qc.x(1) return qc n=5 qc = QuantumCircuit(n) for i in range(n-2): qc.x(i) qc.ccx(0, 1, 3) qc.ccx(2, 3, 4) qc.ccx(0, 1, 3) for i in range(n-2): qc.x(i) qc.draw('mpl') def diffuser(n, name= 'V'): qc = QuantumCircuit(n, name =name) for qb in range(n-2): # First layer of Hadamards in diffuser qc.h(qb) for i in range(n-2): qc.x(i) qc.ccx(0, 1, 3) qc.ccx(2, 3, 4) qc.ccx(0, 1, 3) for i in range(n-2): qc.x(i) for qb in range(n-2): # Second layer of Hadamards in diffuser qc.h(qb) return qc n=5 gr = QuantumCircuit(n, n-2) mu = 1 #number of solutions r = int(np.floor(np.pi/4*np.sqrt(2**(n-2)/mu))) #determine r print('r = ',r) gr.h(range(n-2)) #step1: apply Hadamard gates on all working qubits #put ancilla in state |-> gr.x(n-1) gr.h(n-1) #step 2: apply r rounds of the phase oracle and the diffuser for j in range(r): gr.append(phase_oracle(n), range(n)) gr.append(diffuser(n), range(n)) gr.measure(range(n-2), range(n-2)) #step 3: measure all qubits gr.draw('mpl') from qiskit import BasicAer, Aer, execute, IBMQ from qiskit.visualization import plot_histogram simulator = Aer.get_backend('qasm_simulator') result = execute(gr, backend = simulator, shots = 1024).result() counts = result.get_counts() plot_histogram(counts) from qiskit import IBMQ IBMQ.save_account('e19ab1a54fb68a1937a725b48b02eafb8af0db9189107e78762686e5bf12dff5642e1597470d966ea9d2e121cc86f4a0f08bea5d5e760de66c7be7be04fd2974') IBMQ.load_account() provider = IBMQ.get_provider(hub = 'ibm-q') device = provider.get_backend('ibmq_qasm_simulator') job = execute(gr, backend=device, shots=1024) print(job.job_id()) from qiskit.tools.monitor import job_monitor job_monitor(job) device_result = job.result() plot_histogram(device_result.get_counts(gr))
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
from dell_runtime import DellRuntimeProvider from qiskit import QuantumCircuit import os import logging logging.basicConfig(level=logging.DEBUG) RUNTIME_PROGRAM = """ # This code is part of qiskit-runtime. # # (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. # This is a simplified version of the circuit-runner program. from qiskit.compiler import transpile, schedule def main( backend, user_messenger, circuits, initial_layout=None, seed_transpiler=None, optimization_level=None, transpiler_options=None, scheduling_method=None, schedule_circuit=False, inst_map=None, meas_map=None, measurement_error_mitigation=False, **kwargs, ): # transpiling the circuits using given transpile options transpiler_options = transpiler_options or {} circuits = transpile( circuits, initial_layout=initial_layout, seed_transpiler=seed_transpiler, optimization_level=optimization_level, backend=backend, **transpiler_options, ) if schedule_circuit: circuits = schedule( circuits=circuits, backend=backend, inst_map=inst_map, meas_map=meas_map, method=scheduling_method, ) if not isinstance(circuits, list): circuits = [circuits] # Compute raw results result = backend.run(circuits, **kwargs).result() if measurement_error_mitigation: # Performs measurement error mitigation. pass user_messenger.publish(result.to_dict(), final=True) """ RUNTIME_PROGRAM_METADATA = { "max_execution_time": 600, "description": "Qiskit test program" } PROGRAM_PREFIX = 'qiskit-test' def main(): provider = DellRuntimeProvider() program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA) N = 6 qc = QuantumCircuit(N) qc.x(range(0, N)) qc.h(range(0, N)) for kk in range(N//2,0,-1): qc.ch(kk, kk-1) for kk in range(N//2, N-1): qc.ch(kk, kk+1) qc.measure_all() program_inputs = { 'circuits': qc, 'shots': 2048, 'optimization_level': 0, 'initial_layout': [0,1,4,7,10,12], 'measurement_error_mitigation': False } runtime_program = provider.runtime.program(program_id) job = provider.runtime.run(program_id, options=None, inputs=program_inputs) res = job.result(timeout=120) print(f"res: {res}") if __name__ == "__main__": main()
https://github.com/a24l/Quantum-Computations-and-Algorithms
a24l
import numpy as np #import matplotlib as plt import random from matplotlib import pyplot as plt # Importing standard Qiskit libraries from qiskit import * from qiskit.tools import * from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator from qiskit.tools.visualization import plot_histogram from qiskit import IBMQ # IBMQ.save_account(TOKEN) IBMQ.load_account() # Load account from disk provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider.backends() #Load the necessary backend (unitary simulator) backend = Aer.get_backend('unitary_simulator') #make the quantum circuit qc = QuantumCircuit(1,1) qc.x(0) # add the X gate print(qc) #print the circuit #send the job to the simulator to retrieve the unitary job = execute(qc, backend, shots=1024) result = job.result() unitary = result.get_unitary(qc) #this gets the matrix of the unitary gate print('X=\n',unitary) #print out the matrix of the X gate #similary now use HZH qc1 = QuantumCircuit(1,1) qc1.h(0) qc1.z(0) qc1.h(0) print(qc1) #send the job to the simulator to retrieve the unitary job = execute(qc1, backend, shots=1024) result = job.result() unitary = result.get_unitary(qc1, decimals=2) #this gets the matrix of the unitary gate print('thus HZH=X=\n',unitary) #print out the matrix of the HZH gate #similary now use CNOT gate (with control at q_0 and target at q_1 qubits respectively) qc2 = QuantumCircuit(2,2) qc2.cnot(0,1) print(qc2) #send the job to the simulator to retrieve the unitary job = execute(qc2, backend, shots=1024) result = job.result() unitary = result.get_unitary(qc2, decimals=2) #this gets the matrix of the unitary gate print('CNOT_01=\n',unitary) #print out the matrix of the CNOT_01 gate #similary now use CNOT gate (with control at q_1 and target at q_0 qubits respectively) with Hadamard gate #make the quantum circuit qc3 = QuantumCircuit(2,2) qc3.h(0) qc3.h(1) qc3.cnot(1,0) qc3.h(0) qc3.h(1) print(qc3) #print the circuit #send the job to the simulator to retrieve the unitary job = execute(qc3, backend, shots=1024) result = job.result() unitary = result.get_unitary(qc3, decimals=2) #this gets the matrix of the unitary gate print('equivalent CNOT_01=\n',unitary) #print out the matrix of the CNOT_01 gate equivalence #similary now use SWAP gate qc4 = QuantumCircuit(2,2) qc4.swap(0,1) print(qc4) #send the job to the simulator to retrieve the unitary job = execute(qc4, backend, shots=1024) result = job.result() unitary = result.get_unitary(qc4, decimals=2) #this gets the matrix of the unitary gate print('SWAP=\n',unitary) #print out the matrix of the SWAP gate #similary now use combination of CNOT gates to show SWAP equivalence #make the quantum circuit qc5 = QuantumCircuit(2,2) qc5.cx(0,1) qc5.cx(1,0) qc5.cx(0,1) print(qc5) #print the circuit #send the job to the simulator to retrieve the unitary job = execute(qc5, backend, shots=1024) result = job.result() unitary = result.get_unitary(qc5, decimals=2) #this gets the matrix of the unitary gate print('equivalent SWAP=\n',unitary) #print out the matrix of the SWAP gate equivalence #make the increment circuit # define the required registers p_1 = QuantumRegister(1, name='p1') a_1 = QuantumRegister(1, name='a1') p_2 = QuantumRegister(1, name='p2') a_2 = QuantumRegister(1, name='a2') p_3 = QuantumRegister(1, name='p3') a_3 = QuantumRegister(1, name='a3') p_4 = QuantumRegister(1, name='p4') #inout the registers into the quantum circuit incq = QuantumCircuit(p_1, a_1, p_2, a_2, p_3, a_3, p_4) incq.cx(0,1) incq.ccx(1,2,3) incq.ccx(3,4,5) incq.cx(5,6) incq.ccx(3,4,5) incq.cx(3,4) incq.ccx(1,2,3) incq.cx(1,2) incq.cx(0,1) incq.x(0) #draw the incrementer circuit incq.draw() inc_gate = incq.to_gate(label=' (inc)') #turn the above increment circuit to a gate #make a new circuit new_inc = QuantumCircuit(7) new_inc.append(inc_gate, [0,1,2,3,4,5,6]) #append the gate in to the circuit new_inc.draw() #increment gate is embedded in to the circuit now # Define the required registers p_1 = QuantumRegister(1, name='p1') a_1 = QuantumRegister(1, name='a1') p_2 = QuantumRegister(1, name='p2') a_2 = QuantumRegister(1, name='a2') p_3 = QuantumRegister(1, name='p3') a_3 = QuantumRegister(1, name='a3') p_4 = QuantumRegister(1, name='p4') # Input the registers into the quantum circuit decq = QuantumCircuit(p_1, a_1, p_2, a_2, p_3, a_3, p_4) # Apply the operations in reverse order to "uncompute" the increment circuit decq.x(0) decq.cx(0, 1) decq.cx(1, 2) decq.ccx(1, 2, 3) decq.cx(3, 4) decq.ccx(3, 4, 5) decq.cx(5, 6) decq.ccx(3,4,5) decq.ccx(1, 2, 3) decq.cx(0,1) # Draw the decrementer circuit decq.draw() dec_gate = decq.to_gate(label=' (dec)') #turn the above decrementer circuit to a gate #make a new circuit new_dec = QuantumCircuit(7) new_dec.append(dec_gate, [0,1,2,3,4,5,6]) #append the gate in to the circuit new_dec.draw() #decrement gate is embedded into the circuit now #make the controlled L gate first L = new_inc.to_gate(label= ' (c-inc)').control(1,ctrl_state='0') #make the controlled R gate R = new_dec.to_gate(label= ' (c-dec)').control(1) #design the circuit to hold the above to gates and make a basic walker (condition-shift) shift= QuantumCircuit(8) shift.append(L, [0,1,2,3,4,5,6,7]) #input the L gate #shift.x(0) shift.append(R, [0,1,2,3,4,5,6,7]) #input the R gate shift.draw('mpl') #make the shift operator gate by converting the above inc-dec circuit to gate shift_gate = shift.to_gate( label= ' S = shift operator') #design the step circuit with coin shift_op = QuantumCircuit(8) shift_op.h(0) #this is the coin shift_op.append(shift_gate, [0,1,2,3,4,5,6,7]) #append the shift gate shift_op.draw('mpl') #the step circuit is ready #convert the step circuit to gate step_gate = shift_op.to_gate(label='step_gate') #design our first step circuit for walk step_op = QuantumCircuit(8) step_op.append(step_gate,[0,1,2,3,4,5,6,7]) step_op.draw() #walk-step operator gate is now ready #prepare the random walk step circuit qWalk = QuantumCircuit(8,4) #inout the above initial state|13> qWalk.x(1) qWalk.x(3) n=5 # performs number of steps for quantum walk for i in range(n): qWalk.append(step_gate,[0,1,2,3,4,5,6,7]) #append the step gate for number of desired walks #measure the p-qubits only qWalk.measure(1,0) qWalk.measure(3,1) qWalk.measure(5,2) qWalk.measure(7,3) #QRW is now ready qWalk.draw() #make the measurement of the above circuit simulator = Aer.get_backend('aer_simulator') result = execute(qWalk, backend=simulator, shots=2048).result() bit_count = result.get_counts() print("binary counts", bit_count) #print the counts bit_list = list(bit_count.keys()) # get the keys of the binary dictionary count_list= list(bit_count.values()) # get the values of the binary dictionary #print(count_list) decimal_list = [] #make an empty decimal list to store the values of decimal count for binary_string in bit_list: decimal = int(binary_string, 2) # Convert binary string to decimal decimal_list.append(decimal) # insert the decimal values to decimal_list print("Decimal list:", decimal_list) dec_string_list = [str(decimal) for decimal in decimal_list] #print(dec_string_list) dec_count = dict(zip(dec_string_list,count_list)) #make the dictionary for decimal count print("decimal counts", dec_count) #plot the measurement plot_histogram(dec_count, color='midnightblue', title='plot for QRW circuit for shots =2048', figsize = (12,8)) #transpiler to decompose the circuit basis = ['h','cx','rz'] # use the basis gates as given result = transpile(step_op,basis_gates = basis) print(result) #transpiled circuit # define a particular random walk def randomwalk1D(n): x, y = 0, 3 #start with the initial state # Generate the time points [1, 2, 3, ... , n] timepoints = np.arange(n + 1) positions = [y] directions = ["UP", "DOWN"] for i in range(1, n + 1): # Randomly select either UP or DOWN step = random.choice(directions) # Move the object up or down if step == "UP": y += 1 elif step == "DOWN": y -= 1 # Keep track of the positions positions.append(y) final = y return final n = 1000 #choose repititions positions = np.zeros(n) #create a position space for storing our walk positions walkstep = 5 #choose the number of random walk steps for i in range(n): positions[i] = randomwalk1D(walkstep) #print(positions) # Plotting unique, counts = np.unique(positions, return_counts=True) # generates - bit-string, counts unique[0]= 14 #convert the integer to string format for plotting later points = list(map(str, unique.astype(int))) #print(points) #lists the counts of corresponsing bit strings plot = dict(zip(points, counts)) print(plot) #plot_histogram(plot) legend = ['QRW', 'Classical'] plot_histogram([dec_count, plot], legend=legend, color=['crimson','midnightblue'], title="QRW vs Classical random walk comparison, shots = 1000", figsize = (12,8)) oracle = QuantumCircuit(4) oracle.cx(0,3) oracle.cx(2,3) oracle.draw() bv = QuantumCircuit(4,3) #make the quantum Circuit #input the Hadamards bv.x(3) for i in range(4): bv.h(i) bv.barrier() #input the oracle from the avove cell bv.cx(0,3) bv.cx(2,3) bv.barrier() #complete it with Hadamard for i in range(3): bv.h(i) bv.barrier() #make the measurement for i in range(3): bv.measure(i,i) bv.draw() #for plotting: choose a required simulator simulator = Aer.get_backend("qasm_simulator") result = execute(bv, backend = simulator, shots = 1000).result() #execute the circuit to get measurements counts = result.get_counts() #get the counts for each measurement print(counts) plot_histogram(counts, color='midnightblue', title='B-V Algorithm for secret string a ',figsize = (12,8)) #plot the histogram def decimalToBinary(n): ''' converts a decimal interger to binary ''' return "{0:b}".format(int(n)) #ask to choose a decimal input a_deci = int(input('Choose a number between 0 to 7 :')) # 3bit binary string equivalent a = decimalToBinary(a_deci) print(a) #converts the decimal string to binary bits #make the B-V circuit bv_circ = QuantumCircuit(len(a)+1,len(a)) #first insert all the hadamards bv_circ.h(range(len(a))) bv_circ.x(len(a)) bv_circ.h(len(a)) bv_circ.barrier() #make the oracle for i, query in enumerate(reversed(a)): #cause qiskit uses a reverse ordering LSB-MSB if query == "1": bv_circ.cx(i, len(a)) bv_circ.barrier() #again insert the hadamards bv_circ.h(range(len(a))) bv_circ.barrier() #measure the circuit bv_circ.measure(range(len(a)),range(len(a))) bv_circ.draw("mpl") #follow rthe similar procedure from the above cells for measurement plotting simulator = Aer.get_backend("qasm_simulator") result = execute(bv_circ, backend = simulator, shots = 1000).result() #run the circuit counts = result.get_counts() # get the counts print(counts) plot_histogram(counts, color='midnightblue', title='B-V Algorithm for a chosen string ',figsize = (12,8)) #plot Histogram circuit = QuantumCircuit(4) circuit.cx(1,2) circuit.cx(0,1) circuit.h(2) circuit.cx(0,3) circuit.measure_all() circuit.draw() #make the measurement of the above circuit simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1000).result() #run the circuit counts_old = result.get_counts() # get the counts from qiskit.tools.visualization import plot_histogram plot_histogram(counts_old, color='midnightblue', title='Measurement plot for circuit 2.4a) ',figsize = (12,8)) #transpiler to decompose the circuit result = transpile(circuit, basis_gates=['h', 'cz'], optimization_level=3) result.draw(output='mpl') #draw the circuit #making the transpiled Circuit #insert all the gates with reference to the transpiled circuit and build it. circuit1 = QuantumCircuit(4) circuit1.h(2) circuit1.h(3) circuit1.cz(1,2) circuit1.h(1) circuit1.cz(0,1) circuit1.h(1) circuit1.cz(0,3) circuit1.h(3) print('the transpiled circuit \n') circuit1.measure_all() circuit1.draw() #make the measurement of the transpiled circuit simulator = Aer.get_backend('qasm_simulator') result = execute(circuit1, backend=simulator, shots=1000).result() counts_new = result.get_counts() legend = ['old', 'new (transpiled)'] plot_histogram([counts_old, counts_new], legend=legend, color=['crimson','midnightblue'], title="Measurement comparison for old vs transpiled circuit, shots =1000", figsize = (12,8)) basis_gates = ["cx", "id", "rz", "sx", "x"] adjacency_matrix = [[0,1],[1,0],[1,2],[2,1],[1,3],[3,1],[3,5],[5,3],[4,5],[5,4],[5,6],[6,5]] result = transpile(circuit, basis_gates = basis_gates, coupling_map = adjacency_matrix) result.draw('mpl') from qiskit.providers.fake_provider import FakeMontrealV2 #import the fakebackends to get the topology of 'montreal' backend = FakeMontrealV2() new_circuit = transpile(circuit, backend=backend) #transpile new_circuit.draw()
https://github.com/anikazaman24/Quantum_computer_data_collection_HHL_algorithm_circuit_with_NoiseAnalysis_Framework
anikazaman24
from qiskit_ibm_runtime import QiskitRuntimeService # Save an IBM Quantum account and set it as your default account. QiskitRuntimeService.save_account(channel="ibm_quantum", token='<YOUR_TOKEN>', overwrite=True,set_as_default=True) # Load saved credentials service = QiskitRuntimeService() service.backend() !pip install qiskit[visualization] # Imports for Qiskit from qiskit import QuantumCircuit, execute,IBMQ from qiskit.compiler import transpile, assemble from qiskit import QuantumCircuit, transpile, IBMQ, execute #i added to remove error from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit import * from qiskit import IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.visualization import plot_histogram from copy import deepcopy from matplotlib import pyplot as plt from qiskit import * from qiskit.tools.visualization import * from qiskit.visualization import plot_histogram, plot_bloch_vector from math import sqrt, pi from qiskit import QuantumCircuit, assemble from math import pi, sqrt from qiskit.visualization import plot_bloch_multivector, plot_histogram #sim = Aer.get_backend('aer_simulator') from IPython.display import clear_output #Quantum Volume from IPython.display import clear_output #Import Qiskit classes import qiskit from qiskit import assemble, transpile #from qiskit.providers.aer.noise import NoiseModel #from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error #Import the qv function #import qiskit.ignis.verification.quantum_volume as qv #Import qv measurement classes #from qiskit_experiments.framework import BatchExperiment #from qiskit_experiments.library import QuantumVolume #from qiskit import Aer #from qiskit.providers.aer import AerSimulator from qiskit.circuit.random import random_circuit from qiskit import QuantumCircuit from qiskit_ibm_runtime import QiskitRuntimeService from qiskit.tools.monitor import job_monitor # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * #from ibm_quantum_widgets import * #from qiskit.providers.aer import QasmSimulator from qiskit import * import numpy as np # Register declaration clock = QuantumRegister(2, name='clock') input_ = QuantumRegister(1, name='b') ancilla = QuantumRegister(1, name='ancilla') circuit = QuantumCircuit(ancilla, clock, input_) #---------------Psi 0-------------------------- circuit.barrier() circuit.x(input_); #---------------Psi 1-------------------------- circuit.barrier(); circuit.h(clock[0]); circuit.h(clock[1]); #--------------Psi 2--------------------------- circuit.barrier(); # e^{i*A*t} circuit.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], input_, label='U'); # e^{i*A*t*2} circuit.cu(np.pi, np.pi, 0, 0, clock[1], input_, label='U2'); #--------------Psi 3--------------------------- circuit.barrier(); circuit.h(clock[1]); for j in reversed(range(2)): for k in reversed(range(j+1,2)): circuit.cp(-np.pi/float(2**(k-j)), clock[k], clock[j]); #cu1 changes to cp in the new version circuit.h(clock[0]); circuit.swap(clock[0], clock[1]); #--------------Psi 4--------------------------- circuit.barrier(); circuit.cry(np.pi, clock[0], ancilla); circuit.cry(np.pi/3, clock[1], ancilla); #--------------Psi 5--------------------------- circuit.barrier(); circuit.swap(clock[0], clock[1]); circuit.h(clock[0]); for j in reversed(range(2)): for k in reversed(range(j+1,2)): circuit.cp(np.pi/float(2**(k-j)), clock[k], clock[j]); circuit.h(clock[1]) #--------------Psi 6--------------------------- circuit.barrier(); circuit.cu(np.pi, np.pi, 0, 0, clock[1], input_, label='U2'); # e^{i*A*t} circuit.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], input_, label='U'); #--------------Psi 7-------------------------- circuit.barrier(); circuit.h(clock[0]); circuit.h(clock[1]); #--------------Psi 8--------------------------- circuit.barrier(); circuit.draw(output='mpl', style = 'iqp') # Register declaration clock = QuantumRegister(2, name='clock') input_ = QuantumRegister(1, name='b') ancilla = QuantumRegister(1, name='ancilla') circuit0 = QuantumCircuit(ancilla, clock, input_) #---------------Psi 0-------------------------- circuit0.barrier() circuit0.x(input_); circuit0.measure_all() circuit0.draw(output='mpl',idle_wires=False) from qiskit_ibm_provider import IBMProvider provider = IBMProvider() transpiled_ckt0 = transpile(circuit0, provider.get_backend('ibm_brisbane'), seed_transpiler = 13,optimization_level=0) transpiled_ckt0.draw(output = 'mpl',idle_wires=False) from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Options service = QiskitRuntimeService() options = Options() options.resilience_level = 0 options.optimization_level = 0 #backend = service.least_busy(operational=True, simulator=False) example_circuit = transpiled_ckt0 service = QiskitRuntimeService() backend = service.backend("ibm_brisbane") sampler = Sampler(backend, options=options) job = sampler.run(example_circuit) print(f"job id: {job.job_id()}") result = job.result() print(result) binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists] plot_histogram(binary_prob) import csv data = binary_prob # Extract all possible combinations of 4-bit binary headings all_combinations = [format(i, '04b') for i in range(16)] # Iterate over the data and fill in missing values with zeros filled_data = [] for d in data: filled_row = {key: d.get(key, 0) for key in all_combinations} filled_data.append(filled_row) # Write the filled data to a CSV file csv_file = "data.csv" with open(csv_file, mode='w', newline='') as file: writer = csv.DictWriter(file, fieldnames=all_combinations) writer.writeheader() for row in filled_data: writer.writerow(row) print(f"Data has been written to {csv_file}") # Register declaration clock = QuantumRegister(2, name='clock') input_ = QuantumRegister(1, name='b') ancilla = QuantumRegister(1, name='ancilla') circuit1 = QuantumCircuit(ancilla, clock, input_) #---------------Psi 0-------------------------- circuit1.barrier() circuit1.x(input_); #---------------Psi 1-------------------------- circuit1.barrier(); circuit1.h(clock[0]); circuit1.h(clock[1]); circuit1.measure_all() circuit1.draw(output='mpl',idle_wires=False) #--------------Psi 2--------------------------- from qiskit_ibm_provider import IBMProvider provider = IBMProvider() transpiled_ckt1 = transpile(circuit1, provider.get_backend('ibm_brisbane'), seed_transpiler = 13,optimization_level=0) transpiled_ckt1.draw(output = 'mpl',idle_wires=False) from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Options service = QiskitRuntimeService() options = Options() options.resilience_level = 0 options.optimization_level = 0 #backend = service.least_busy(operational=True, simulator=False) example_circuit = transpiled_ckt1 service = QiskitRuntimeService() backend = service.backend("ibm_brisbane") sampler = Sampler(backend, options=options) job = sampler.run(example_circuit) print(f"job id: {job.job_id()}") result = job.result() print(result) binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists] plot_histogram(binary_prob) import csv data1 = binary_prob # Fill in missing values in data1 with zeros filled_data1 = [] for d in data1: filled_row = {key: d.get(key, 0) for key in all_combinations} filled_data1.append(filled_row) # Append filled_data1 to filled_data filled_data.extend(filled_data1) # Write the updated filled_data to the same CSV file csv_file = "data.csv" with open(csv_file, mode='a', newline='') as file: writer = csv.DictWriter(file, fieldnames=all_combinations) for row in filled_data1: writer.writerow(row) print(f"Data1 has been added to {csv_file}") # Register declaration clock = QuantumRegister(2, name='clock') input_ = QuantumRegister(1, name='b') ancilla = QuantumRegister(1, name='ancilla') circuit2 = QuantumCircuit(ancilla, clock, input_) #---------------Psi 0-------------------------- circuit2.barrier() circuit2.x(input_); #---------------Psi 1-------------------------- circuit2.barrier(); circuit2.h(clock[0]); circuit2.h(clock[1]); #--------------Psi 2--------------------------- circuit2.barrier(); # e^{i*A*t} circuit2.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], input_, label='U'); # e^{i*A*t*2} circuit2.cu(np.pi, np.pi, 0, 0, clock[1], input_, label='U2'); circuit2.measure_all() circuit2.draw(output='mpl',idle_wires=False) #--------------Psi 3--------------------------- from qiskit_ibm_provider import IBMProvider provider = IBMProvider() transpiled_ckt2 = transpile(circuit2, provider.get_backend('ibm_brisbane'), seed_transpiler = 13,optimization_level=0) transpiled_ckt2.draw(output = 'mpl',idle_wires=False) from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Options service = QiskitRuntimeService() options = Options() options.resilience_level = 0 options.optimization_level = 0 #backend = service.least_busy(operational=True, simulator=False) example_circuit = transpiled_ckt2 service = QiskitRuntimeService() backend = service.backend("ibm_brisbane") sampler = Sampler(backend, options=options) job = sampler.run(example_circuit) print(f"job id: {job.job_id()}") result = job.result() print(result) binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists] plot_histogram(binary_prob) import csv data1 = binary_prob # Fill in missing values in data1 with zeros filled_data1 = [] for d in data1: filled_row = {key: d.get(key, 0) for key in all_combinations} filled_data1.append(filled_row) # Append filled_data1 to filled_data filled_data.extend(filled_data1) # Write the updated filled_data to the same CSV file csv_file = "data.csv" with open(csv_file, mode='a', newline='') as file: writer = csv.DictWriter(file, fieldnames=all_combinations) for row in filled_data1: writer.writerow(row) print(f"Data1 has been added to {csv_file}") # Register declaration clock = QuantumRegister(2, name='clock') input_ = QuantumRegister(1, name='b') ancilla = QuantumRegister(1, name='ancilla') circuit3 = QuantumCircuit(ancilla, clock, input_) #---------------Psi 0-------------------------- circuit3.barrier() circuit3.x(input_); #---------------Psi 1-------------------------- circuit3.barrier(); circuit3.h(clock[0]); circuit3.h(clock[1]); #--------------Psi 2--------------------------- circuit3.barrier(); # e^{i*A*t} circuit3.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], input_, label='U'); # e^{i*A*t*2} circuit3.cu(np.pi, np.pi, 0, 0, clock[1], input_, label='U2'); #--------------Psi 3--------------------------- circuit3.barrier(); circuit3.h(clock[1]); for j in reversed(range(2)): for k in reversed(range(j+1,2)): circuit3.cp(-np.pi/float(2**(k-j)), clock[k], clock[j]); #cu1 changes to cp in the new version circuit3.h(clock[0]); circuit3.swap(clock[0], clock[1]); circuit3.measure_all(); circuit3.draw(output='mpl',idle_wires=False) #--------------Psi 4--------------------------- from qiskit_ibm_provider import IBMProvider provider = IBMProvider() transpiled_ckt3 = transpile(circuit3, provider.get_backend('ibm_brisbane'), seed_transpiler = 13,optimization_level=0) transpiled_ckt3.draw(output = 'mpl',idle_wires=False) from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Options service = QiskitRuntimeService() options = Options() options.resilience_level = 0 options.optimization_level = 0 #backend = service.least_busy(operational=True, simulator=False) example_circuit = transpiled_ckt3 service = QiskitRuntimeService() backend = service.backend("ibm_brisbane") sampler = Sampler(backend, options=options) job = sampler.run(example_circuit) print(f"job id: {job.job_id()}") result = job.result() print(result) binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists] plot_histogram(binary_prob) import csv data1 = binary_prob # Fill in missing values in data1 with zeros filled_data1 = [] for d in data1: filled_row = {key: d.get(key, 0) for key in all_combinations} filled_data1.append(filled_row) # Append filled_data1 to filled_data filled_data.extend(filled_data1) # Write the updated filled_data to the same CSV file csv_file = "data.csv" with open(csv_file, mode='a', newline='') as file: writer = csv.DictWriter(file, fieldnames=all_combinations) for row in filled_data1: writer.writerow(row) print(f"Data1 has been added to {csv_file}") # Register declaration clock = QuantumRegister(2, name='clock') input_ = QuantumRegister(1, name='b') ancilla = QuantumRegister(1, name='ancilla') circuit4 = QuantumCircuit(ancilla, clock, input_) #---------------Psi 0-------------------------- circuit4.barrier() circuit4.x(input_); #---------------Psi 1-------------------------- circuit4.barrier(); circuit4.h(clock[0]); circuit4.h(clock[1]); #--------------Psi 2--------------------------- circuit4.barrier(); # e^{i*A*t} circuit4.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], input_, label='U'); # e^{i*A*t*2} circuit4.cu(np.pi, np.pi, 0, 0, clock[1], input_, label='U2'); #--------------Psi 3--------------------------- circuit4.barrier(); circuit4.h(clock[1]); for j in reversed(range(2)): for k in reversed(range(j+1,2)): circuit4.cp(-np.pi/float(2**(k-j)), clock[k], clock[j]); #cu1 changes to cp in the new version circuit4.h(clock[0]); circuit4.swap(clock[0], clock[1]); #--------------Psi 4--------------------------- circuit4.barrier(); circuit4.cry(np.pi, clock[0], ancilla); circuit4.cry(np.pi/3, clock[1], ancilla); circuit4.measure_all() circuit4.draw(output='mpl',idle_wires=False) #--------------Psi 5--------------------------- from qiskit_ibm_provider import IBMProvider provider = IBMProvider() transpiled_ckt4 = transpile(circuit4, provider.get_backend('ibm_brisbane'), seed_transpiler = 13,optimization_level=0) transpiled_ckt4.draw(output = 'mpl',idle_wires=False) from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Options service = QiskitRuntimeService() options = Options() options.resilience_level = 0 options.optimization_level = 0 #backend = service.least_busy(operational=True, simulator=False) example_circuit = transpiled_ckt4 service = QiskitRuntimeService() backend = service.backend("ibm_brisbane") sampler = Sampler(backend, options=options) job = sampler.run(example_circuit) print(f"job id: {job.job_id()}") result = job.result() print(result) binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists] plot_histogram(binary_prob) import csv data1 = binary_prob # Fill in missing values in data1 with zeros filled_data1 = [] for d in data1: filled_row = {key: d.get(key, 0) for key in all_combinations} filled_data1.append(filled_row) # Append filled_data1 to filled_data filled_data.extend(filled_data1) # Write the updated filled_data to the same CSV file csv_file = "data.csv" with open(csv_file, mode='a', newline='') as file: writer = csv.DictWriter(file, fieldnames=all_combinations) for row in filled_data1: writer.writerow(row) print(f"Data1 has been added to {csv_file}") # Register declaration clock = QuantumRegister(2, name='clock') input_ = QuantumRegister(1, name='b') ancilla = QuantumRegister(1, name='ancilla') circuit5 = QuantumCircuit(ancilla, clock, input_) #---------------Psi 0-------------------------- circuit5.barrier() circuit5.x(input_); #---------------Psi 1-------------------------- circuit5.barrier(); circuit5.h(clock[0]); circuit5.h(clock[1]); #--------------Psi 2--------------------------- circuit5.barrier(); # e^{i*A*t} circuit5.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], input_, label='U'); # e^{i*A*t*2} circuit5.cu(np.pi, np.pi, 0, 0, clock[1], input_, label='U2'); #--------------Psi 3--------------------------- circuit5.barrier(); circuit5.h(clock[1]); for j in reversed(range(2)): for k in reversed(range(j+1,2)): circuit5.cp(-np.pi/float(2**(k-j)), clock[k], clock[j]); #cu1 changes to cp in the new version circuit5.h(clock[0]); circuit5.swap(clock[0], clock[1]); #--------------Psi 4--------------------------- circuit5.barrier(); circuit5.cry(np.pi, clock[0], ancilla); circuit5.cry(np.pi/3, clock[1], ancilla); #--------------Psi 5--------------------------- circuit5.barrier(); circuit5.swap(clock[0], clock[1]); circuit5.h(clock[0]); for j in reversed(range(2)): for k in reversed(range(j+1,2)): circuit5.cp(np.pi/float(2**(k-j)), clock[k], clock[j]); circuit5.h(clock[1]) circuit5.measure_all() circuit5.draw(output='mpl',idle_wires=False) #--------------Psi 6--------------------------- from qiskit_ibm_provider import IBMProvider provider = IBMProvider() transpiled_ckt5 = transpile(circuit5, provider.get_backend('ibm_brisbane'), seed_transpiler = 13,optimization_level=0) transpiled_ckt5.draw(output = 'mpl',idle_wires=False) from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Options service = QiskitRuntimeService() options = Options() options.resilience_level = 0 options.optimization_level = 0 #backend = service.least_busy(operational=True, simulator=False) example_circuit = transpiled_ckt5 service = QiskitRuntimeService() backend = service.backend("ibm_brisbane") sampler = Sampler(backend, options=options) job = sampler.run(example_circuit) print(f"job id: {job.job_id()}") result = job.result() print(result) binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists] plot_histogram(binary_prob) import csv data1 = binary_prob # Fill in missing values in data1 with zeros filled_data1 = [] for d in data1: filled_row = {key: d.get(key, 0) for key in all_combinations} filled_data1.append(filled_row) # Append filled_data1 to filled_data filled_data.extend(filled_data1) # Write the updated filled_data to the same CSV file csv_file = "data.csv" with open(csv_file, mode='a', newline='') as file: writer = csv.DictWriter(file, fieldnames=all_combinations) for row in filled_data1: writer.writerow(row) print(f"Data1 has been added to {csv_file}") # Register declaration clock = QuantumRegister(2, name='clock') input_ = QuantumRegister(1, name='b') ancilla = QuantumRegister(1, name='ancilla') circuit6 = QuantumCircuit(ancilla, clock, input_) #---------------Psi 0-------------------------- circuit6.barrier() circuit6.x(input_); #---------------Psi 1-------------------------- circuit6.barrier(); circuit6.h(clock[0]); circuit6.h(clock[1]); #--------------Psi 2--------------------------- circuit6.barrier(); # e^{i*A*t} circuit6.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], input_, label='U'); # e^{i*A*t*2} circuit6.cu(np.pi, np.pi, 0, 0, clock[1], input_, label='U2'); #--------------Psi 3--------------------------- circuit6.barrier(); circuit6.h(clock[1]); for j in reversed(range(2)): for k in reversed(range(j+1,2)): circuit6.cp(-np.pi/float(2**(k-j)), clock[k], clock[j]); #cu1 changes to cp in the new version circuit6.h(clock[0]); circuit6.swap(clock[0], clock[1]); #--------------Psi 4--------------------------- circuit6.barrier(); circuit6.cry(np.pi, clock[0], ancilla); circuit6.cry(np.pi/3, clock[1], ancilla); #--------------Psi 5--------------------------- circuit6.barrier(); circuit6.swap(clock[0], clock[1]); circuit6.h(clock[0]); for j in reversed(range(2)): for k in reversed(range(j+1,2)): circuit6.cp(np.pi/float(2**(k-j)), clock[k], clock[j]); circuit6.h(clock[1]) #--------------Psi 6--------------------------- circuit6.barrier(); circuit6.cu(np.pi, np.pi, 0, 0, clock[1], input_, label='U2'); # e^{i*A*t} circuit6.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], input_, label='U'); circuit6.measure_all() circuit6.draw(output='mpl',idle_wires=False) #--------------Psi 7-------------------------- from qiskit_ibm_provider import IBMProvider provider = IBMProvider() transpiled_ckt6 = transpile(circuit6, provider.get_backend('ibm_brisbane'), seed_transpiler = 13,optimization_level=0) transpiled_ckt6.draw(output = 'mpl',idle_wires=False) from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Options service = QiskitRuntimeService() options = Options() options.resilience_level = 0 options.optimization_level = 0 #backend = service.least_busy(operational=True, simulator=False) example_circuit = transpiled_ckt6 service = QiskitRuntimeService() backend = service.backend("ibm_brisbane") sampler = Sampler(backend, options=options) job = sampler.run(example_circuit) print(f"job id: {job.job_id()}") result = job.result() print(result) binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists] plot_histogram(binary_prob) import csv data1 = binary_prob # Fill in missing values in data1 with zeros filled_data1 = [] for d in data1: filled_row = {key: d.get(key, 0) for key in all_combinations} filled_data1.append(filled_row) # Append filled_data1 to filled_data filled_data.extend(filled_data1) # Write the updated filled_data to the same CSV file csv_file = "data.csv" with open(csv_file, mode='a', newline='') as file: writer = csv.DictWriter(file, fieldnames=all_combinations) for row in filled_data1: writer.writerow(row) print(f"Data1 has been added to {csv_file}") # Register declaration clock = QuantumRegister(2, name='clock') input_ = QuantumRegister(1, name='b') ancilla = QuantumRegister(1, name='ancilla') circuit7 = QuantumCircuit(ancilla, clock, input_) #---------------Psi 0-------------------------- circuit7.barrier() circuit7.x(input_); #---------------Psi 1-------------------------- circuit7.barrier(); circuit7.h(clock[0]); circuit7.h(clock[1]); #--------------Psi 2--------------------------- circuit7.barrier(); # e^{i*A*t} circuit7.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], input_, label='U'); # e^{i*A*t*2} circuit7.cu(np.pi, np.pi, 0, 0, clock[1], input_, label='U2'); #--------------Psi 3--------------------------- circuit7.barrier(); circuit7.h(clock[1]); for j in reversed(range(2)): for k in reversed(range(j+1,2)): circuit7.cp(-np.pi/float(2**(k-j)), clock[k], clock[j]); #cu1 changes to cp in the new version circuit7.h(clock[0]); circuit7.swap(clock[0], clock[1]); #--------------Psi 4--------------------------- circuit7.barrier(); circuit7.cry(np.pi, clock[0], ancilla); circuit7.cry(np.pi/3, clock[1], ancilla); #--------------Psi 5--------------------------- circuit7.barrier(); circuit7.swap(clock[0], clock[1]); circuit7.h(clock[0]); for j in reversed(range(2)): for k in reversed(range(j+1,2)): circuit7.cp(np.pi/float(2**(k-j)), clock[k], clock[j]); circuit7.h(clock[1]) #--------------Psi 6--------------------------- circuit7.barrier(); circuit7.cu(np.pi, np.pi, 0, 0, clock[1], input_, label='U2'); # e^{i*A*t} circuit7.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], input_, label='U'); #--------------Psi 7-------------------------- circuit7.barrier(); circuit7.h(clock[0]); circuit7.h(clock[1]); #--------------Psi 8--------------------------- circuit7.measure_all(); circuit.draw(output='mpl', style = 'iqp') from qiskit_ibm_provider import IBMProvider provider = IBMProvider() transpiled_ckt7 = transpile(circuit7, provider.get_backend('ibm_brisbane'), seed_transpiler = 13,optimization_level=0) transpiled_ckt7.draw(output = 'mpl',idle_wires=False) from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Options service = QiskitRuntimeService() options = Options() options.resilience_level = 0 options.optimization_level = 0 #backend = service.least_busy(operational=True, simulator=False) example_circuit = transpiled_ckt7 service = QiskitRuntimeService() backend = service.backend("ibm_brisbane") sampler = Sampler(backend, options=options) job = sampler.run(example_circuit) print(f"job id: {job.job_id()}") result = job.result() print(result) binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists] plot_histogram(binary_prob) import csv data1 = binary_prob # Fill in missing values in data1 with zeros filled_data1 = [] for d in data1: filled_row = {key: d.get(key, 0) for key in all_combinations} filled_data1.append(filled_row) # Append filled_data1 to filled_data filled_data.extend(filled_data1) # Write the updated filled_data to the same CSV file csv_file = "data.csv" with open(csv_file, mode='a', newline='') as file: writer = csv.DictWriter(file, fieldnames=all_combinations) for row in filled_data1: writer.writerow(row) print(f"Data1 has been added to {csv_file}")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) ghz.draw(output='mpl')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# A jupyter notebook is composed by one or more cells. # A cell is used to write and execute your codes. # A cell is also used to write descriptions, notes, formulas, etc. # You can format your descriptions by using HTML or LaTex codes. # During this tutorial, you are expected to write only python codes. # Interested readers may also use HTML and LaTex, but it is not necesary to complete this tutorial. # # We explain basic usage of cells in Jupyter notebooks here # # This is the first cell in this notebook. # You can write Python code here, # and then EXECUTE/RUN it by # 1) pressing SHIFT+ENTER # 2) clicking "Run" on the menu # here is a few lines of python codes print("hello world") str="*" for i in range(5): print(str) str+="*" # after executing this cell, you will see the outcomes immedeately after this cell # you may change the range above and re-run this cell # after executing this cell, you can continue with the next cell # This is the second cell. # # When you double click after the last cell, a new cell appears automatically. # It automatically happens when you execute the last cell as well. # # By using menu item "Insert", you may also add a new cell before or after the selected cell. # When a cell is selected, you may delete it by using menu item "Edit". # # As you may notice, there are other editing options under "Edit", # for example, copy/cut-paste cells and split-merge cells.
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/quantumyatra/quantum_computing
quantumyatra
from qiskit import QuantumCircuit, execute from qiskit import Aer, execute, BasicAer, IBMQ from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram import numpy as np def dj_oracle(case, n): oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant elif case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n=4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw('mpl') backend = BasicAer.get_backend('qasm_simulator') results = execute(dj_circuit, backend=backend, shots=1024).result() answer = results.get_counts() plot_histogram(answer) # Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) 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(dj_circuit, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) # Get the results of the computation results = job.result() counts = results.get_counts() plot_histogram(counts)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for BasePrimitive.""" import json from ddt import data, ddt, unpack from numpy import array, float32, float64, int32, int64 from qiskit import QuantumCircuit, pulse, transpile from qiskit.circuit.random import random_circuit from qiskit.primitives.base.base_primitive import BasePrimitive from qiskit.primitives.utils import _circuit_key from qiskit.providers.fake_provider import FakeAlmaden from qiskit.test import QiskitTestCase @ddt class TestCircuitValidation(QiskitTestCase): """Test circuits validation logic.""" @data( (random_circuit(2, 2, seed=0), (random_circuit(2, 2, seed=0),)), ( [random_circuit(2, 2, seed=0), random_circuit(2, 2, seed=1)], (random_circuit(2, 2, seed=0), random_circuit(2, 2, seed=1)), ), ) @unpack def test_validate_circuits(self, circuits, expected): """Test circuits standardization.""" self.assertEqual(BasePrimitive._validate_circuits(circuits), expected) @data(None, "ERROR", True, 0, 1.0, 1j, [0.0]) def test_type_error(self, circuits): """Test type error if invalid input.""" with self.assertRaises(TypeError): BasePrimitive._validate_circuits(circuits) @data((), [], "") def test_value_error(self, circuits): """Test value error if no circuits are provided.""" with self.assertRaises(ValueError): BasePrimitive._validate_circuits(circuits) @ddt class TestParameterValuesValidation(QiskitTestCase): """Test parameter_values validation logic.""" @data( ((), ((),)), ([], ((),)), (0, ((0,),)), (1.2, ((1.2,),)), ((0,), ((0,),)), ([0], ((0,),)), ([1.2], ((1.2,),)), ((0, 1), ((0, 1),)), ([0, 1], ((0, 1),)), ([0, 1.2], ((0, 1.2),)), ([0.3, 1.2], ((0.3, 1.2),)), (((0, 1)), ((0, 1),)), (([0, 1]), ((0, 1),)), ([(0, 1)], ((0, 1),)), ([[0, 1]], ((0, 1),)), ([[0, 1.2]], ((0, 1.2),)), ([[0.3, 1.2]], ((0.3, 1.2),)), # Test for numpy dtypes (int32(5), ((float(int32(5)),),)), (int64(6), ((float(int64(6)),),)), (float32(3.2), ((float(float32(3.2)),),)), (float64(6.4), ((float(float64(6.4)),),)), ([int32(5), float32(3.2)], ((float(int32(5)), float(float32(3.2))),)), ) @unpack def test_validate_parameter_values(self, _parameter_values, expected): """Test parameter_values standardization.""" for parameter_values in [_parameter_values, array(_parameter_values)]: # Numpy self.assertEqual(BasePrimitive._validate_parameter_values(parameter_values), expected) self.assertEqual( BasePrimitive._validate_parameter_values(None, default=parameter_values), expected ) @data( "ERROR", ("E", "R", "R", "O", "R"), (["E", "R", "R"], ["O", "R"]), 1j, (1j,), ((1j,),), True, False, float("inf"), float("-inf"), float("nan"), ) def test_type_error(self, parameter_values): """Test type error if invalid input.""" with self.assertRaises(TypeError): BasePrimitive._validate_parameter_values(parameter_values) def test_value_error(self): """Test value error if no parameter_values or default are provided.""" with self.assertRaises(ValueError): BasePrimitive._validate_parameter_values(None) class TestCircuitKey(QiskitTestCase): """Tests for _circuit_key function""" def test_different_circuits(self): """Test collision of quantum circuits.""" with self.subTest("Ry circuit"): def test_func(n): qc = QuantumCircuit(1, 1, name="foo") qc.ry(n, 0) return qc keys = [_circuit_key(test_func(i)) for i in range(5)] self.assertEqual(len(keys), len(set(keys))) with self.subTest("pulse circuit"): def test_with_scheduling(n): custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(160 * n, 0.1), pulse.DriveChannel(0)), inplace=True ) qc = QuantumCircuit(1) qc.x(0) qc.add_calibration("x", qubits=(0,), schedule=custom_gate) return transpile(qc, FakeAlmaden(), scheduling_method="alap") keys = [_circuit_key(test_with_scheduling(i)) for i in range(1, 5)] self.assertEqual(len(keys), len(set(keys))) def test_circuit_key_controlflow(self): """Test for a circuit with control flow.""" qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) self.assertIsInstance(hash(_circuit_key(qc)), int) self.assertIsInstance(json.dumps(_circuit_key(qc)), str)
https://github.com/18520339/uts-quantum-computing
18520339
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile from termcolor import colored class Board: def __init__(self, size=3, simulator=None): # Initialize the quantum circuit with one qubit and classical bit for each cell self.size = size self.simulator = simulator self.superposition_count = 0 self.cells = [[' ' for _ in range(size)] for _ in range(size)] # Initialize the board representation self.qubits = QuantumRegister(size**2, 'q') self.bits = ClassicalRegister(size**2, 'c') self.circuit = QuantumCircuit(self.qubits, self.bits) ''' For a 3x3 board, the winning lines are: - Horizontal lines: (0, 1, 2), (3, 4, 5), (6, 7, 8) - Vertical lines: (0, 3, 6), (1, 4, 7), (2, 5, 8) - Diagonal lines: (0, 4, 8), (2, 4, 6) ''' self.winning_lines = [tuple(range(i, size**2, size)) for i in range(size)] + \ [tuple(range(i * size, (i + 1) * size)) for i in range(size)] + \ [tuple(range(0, size**2, size + 1)), tuple(range(size - 1, size**2 - 1, size - 1))] def __str__(self): # Create a colorful string representation of the board board_str = '' for i, row in enumerate(self.cells): for cell in row: if '?' in cell: cell_color = 'cyan' # Quantum move elif cell == 'X': cell_color = 'red' elif cell == 'O': cell_color = 'green' else: cell_color = 'yellow' board_str += f' {colored(cell, cell_color)} ' board_str += '|' if '?' in cell else ' |' board_str = board_str[:-1] + '\n' # Remove last separator if i < self.size - 1: # Add horizontal separator board_str += '-' * (5 * self.size - 1) + '\n' return board_str def make_classical_move(self, row, col, player_mark, is_collapsed=False): if self.cells[row][col] == ' ' or is_collapsed: # Check if the cell is occupied self.cells[row][col] = player_mark index = row * self.size + col if player_mark == 'X': self.circuit.x(self.qubits[index]) else: self.circuit.id(self.qubits[index]) return True return False def make_swap_move(self, row1, col1, row2, col2, **kwargs): if self.cells[row1][col1] != ' ' and self.cells[row2][col2] != ' ': indices = [row1 * self.size + col1, row2 * self.size + col2] self.circuit.swap(self.qubits[indices[0]], self.qubits[indices[1]]) self.cells[row1][col1], self.cells[row2][col2] = self.cells[row2][col2], self.cells[row1][col1] return True return False def make_superposition_move(self, row, col, player_mark, **kwargs): if self.cells[row][col] == ' ': index = row * self.size + col self.circuit.h(self.qubits[index]) self.cells[row][col] = player_mark + '?' self.superposition_count += 1 return True return False def make_entangled_move(self, *positions, risk_level, player_mark, **kwargs): # Entangle the quantum states of 2 or 3 cells based on the risk level pos_count = len(positions) if pos_count not in [2, 3] or risk_level not in [1, 2, 3, 4] or len(set(positions)) != pos_count or \ (pos_count == 2 and risk_level not in [1, 3]) or (pos_count == 3 and risk_level not in [2, 4]) or \ any(self.cells[row][col] != ' ' for row, col in positions): return False indices = [row * self.size + col for row, col in positions] self.circuit.h(self.qubits[indices[0]]) if pos_count == 2: # Pairwise Entanglement with Bell state for 2 qubits: # Lv1. |Ψ+⟩ = (∣01⟩ + ∣10⟩)/√2 | Lv3. |Φ+⟩ = (∣00⟩ + ∣11⟩)/√2 if risk_level == 1: self.circuit.x(self.qubits[indices[1]]) self.circuit.cx(self.qubits[indices[0]], self.qubits[indices[1]]) else: # Triple Entanglement with GHZ state for 3 qubits: # Lv2. (∣010⟩ + ∣101⟩)/√2 | Lv4. (∣000⟩ + ∣111⟩)/√2 if risk_level == 2: self.circuit.x(self.qubits[indices[1]]) self.circuit.x(self.qubits[indices[2]]) # Apply CNOT chain to entangle all 3 qubits self.circuit.cx(self.qubits[indices[0]], self.qubits[indices[1]]) self.circuit.cx(self.qubits[indices[1]], self.qubits[indices[2]]) for row, col in positions: self.cells[row][col] = player_mark + '?' self.superposition_count += pos_count return True def can_be_collapsed(self): # If superpositions/entanglement cells form a potential winning line => collapse for line in self.winning_lines: if all(self.cells[i // self.size][i % self.size].endswith('?') for i in line): return True return False def collapse_board(self): # Update the board based on the measurement results and apply the corresponding classical moves self.circuit.barrier() self.circuit.measure(self.qubits, self.bits) # Measure all qubits to collapse them to classical states transpiled_circuit = transpile(self.circuit, self.simulator) job = self.simulator.run(transpiled_circuit, memory=True) counts = job.result().get_counts() max_state = max(counts, key=counts.get)[::-1] # Get the state with the highest probability for i in range(self.size ** 2): row, col = divmod(i, self.size) if self.cells[row][col].endswith('?'): self.circuit.reset(self.qubits[i]) self.make_classical_move(row, col, 'X' if max_state[i] == '1' else 'O', is_collapsed=True) self.superposition_count = 0 return counts def check_win(self): # Dynamic implementation for above logic with dynamic winning lines for line in self.winning_lines: # Check if all cells in the line are the same and not empty first_cell = self.cells[line[0] // self.size][line[0] % self.size] if first_cell not in [' ', 'X?', 'O?']: is_same = all(self.cells[i // self.size][i % self.size] == first_cell for i in line) if is_same: return line # If no spaces and no superpositions left => 'Draw' # If all cells are filled but some are still in superpositions => collapse_board if all(self.cells[i // self.size][i % self.size] not in [' '] for i in range(self.size**2)): if self.superposition_count <= 0: return 'Draw' return self.superposition_count return None
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") circ.draw(output='mpl')
https://github.com/rochisha0/stock-picking
rochisha0
from qiskit.finance.data_providers import RandomDataProvider import numpy as np import matplotlib.pyplot as plt import datetime import pandas as pd from nsepy import get_history from docplex.mp.model import Model from qiskit.optimization import QuadraticProgram from qiskit.optimization.converters import LinearEqualityToPenalty import pennylane as qml assets = ['INFY', 'TCS', 'DRREDDY'] num_assets = len(assets) print('The total number of assets {0}'.format(num_assets)) stockStartDate = datetime.date(2019,8,20) stockEndDate = datetime.date(2020,8,20) df = pd.DataFrame() for stock in assets: df[stock] = get_history(symbol=stock, start=stockStartDate, end=stockEndDate)['Close'] title = 'Portfolio Adj. Close Price History ' #Get the stocks my_stocks = df #Create and plot the graph plt.figure(figsize=(12.2,4.5)) #width = 12.2in, height = 4.5 # Loop through each stock and plot the Adj Close for each day for c in my_stocks.columns.values: plt.plot( my_stocks[c], label=c)#plt.plot( X-Axis , Y-Axis, line_width, alpha_for_blending, label) plt.title(title) plt.xlabel('Date',fontsize=18) plt.ylabel('Adj. Price Rs.',fontsize=18) plt.legend(my_stocks.columns.values, loc='upper left') plt.show() returns = df.pct_change() cov_matrix_annual = returns.cov() * 249 mu = returns.mean().to_numpy() sigma = cov_matrix_annual.to_numpy() q = 0.5 # set risk factor budget = 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term mdl = Model('docplex model') x = mdl.binary_var_list(num_assets) # set objective function: # # maximize { mu^T * x - q * x^T * sigma * x } # objective = mdl.sum([mu[i] * x[i] for i in range(num_assets)]) # mu^T * x objective -= q * mdl.sum([sigma[i][j]*x[i]*x[j] for i in range(num_assets) for j in range(num_assets)]) mdl.maximize(objective) # add budget constraint: # # 1^T * x == budget # cost = mdl.sum([x[i] for i in range(num_assets)]) mdl.add_constraint(cost == budget, ctname='budget') # converting to Quadratic Program mod = QuadraticProgram() mod.from_docplex(mdl) #removing the constraint to create the QUBO lineq2penalty = LinearEqualityToPenalty(penalty) qubo = lineq2penalty.convert(mod) #converting QUBO to an Ising Hamiltonian H, offset = qubo.to_ising() H.num_qubits H = H.to_legacy_op() H.print_details() def anstanz(theta): qml.RX(theta[0], wires=0) qml.RX(theta[1], wires=1) qml.RX(theta[2], wires=2) qml.CNOT(wires=[0,1]) qml.CNOT(wires=[0,2]) qml.CNOT(wires=[1,2]) qml.RX(theta[3], wires=0) qml.RX(theta[4], wires=1) qml.RX(theta[5], wires=2) qml.CNOT(wires=[0,1]) qml.CNOT(wires=[0,2]) qml.CNOT(wires=[1,2]) qml.RX(theta[6], wires=0) qml.RX(theta[7], wires=1) qml.RX(theta[8], wires=2) return anstanz dev1 = qml.device("default.qubit", wires=3) @qml.qnode(dev1) def circuit_IIZ(params): anstanz(params) return qml.expval(qml.Identity(0)@qml.Identity(1)@qml.PauliZ(2)) @qml.qnode(dev1) def circuit_IZI(params): anstanz(params) return qml.expval(qml.Identity(0)@qml.PauliZ(1)@qml.Identity(2)) @qml.qnode(dev1) def circuit_ZII(params): anstanz(params) return qml.expval(qml.PauliZ(0)@qml.Identity(1)@qml.Identity(2)) @qml.qnode(dev1) def circuit_IZZ(params): anstanz(params) return qml.expval(qml.Identity(0)@qml.PauliZ(1)@qml.PauliZ(2)) @qml.qnode(dev1) def circuit_ZIZ(params): anstanz(params) return qml.expval(qml.PauliZ(0)@qml.Identity(1)@qml.PauliZ(2)) @qml.qnode(dev1) def circuit_ZZI(params): anstanz(params) return qml.expval(qml.PauliZ(0)@qml.PauliZ(1)@qml.Identity(2)) def pauli_operator_to_dict(pauli_operator): d = pauli_operator.to_dict() paulis = d['paulis'] paulis_dict = {} for x in paulis: label = x['label'] coeff = x['coeff']['real'] paulis_dict[label] = coeff return paulis_dict pauli_dict = pauli_operator_to_dict(H) def vqe(parameters): expval_ZII = pauli_dict['ZII'] * circuit_ZII(parameters) expval_IIZ = pauli_dict['IIZ'] * circuit_IIZ(parameters) expval_IZI = pauli_dict['IZI'] * circuit_IZI(parameters) expval_ZZI = pauli_dict['ZZI'] * circuit_ZZI(parameters) expval_ZIZ = pauli_dict['ZIZ'] * circuit_ZIZ(parameters) expval_IZZ = pauli_dict['IZZ'] * circuit_IZZ(parameters) # summing the measurement results classical_adder = expval_ZII + expval_IIZ + expval_ZIZ + expval_ZZI + expval_ZIZ + expval_IZZ return classical_adder opt = qml.GradientDescentOptimizer(stepsize=0.5) value = [] params = [0.01, 0.02, 0.01, np.pi, 0.1, np.pi/2, np.pi, np.pi/2, np.pi] ## Random initial parameters steps = 100 for i in range(steps): #print(i) params = opt.step(vqe, params) value.append(vqe(params)) @qml.qnode(dev1) def final_circ(params): anstanz(params) return qml.probs(wires=[0,1,2]) plt.bar(['000', '001', '010', '011', '100', '101', '110', '111'], final_circ(params)) from qiskit.optimization.applications.ising.common import sample_most_likely exact_eigensolver = NumPyMinimumEigensolver(H) result = exact_eigensolver.run() sample_most_likely(result.eigenstate)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
MonitSharma
import matplotlib.pyplot as plt import numpy as np %matplotlib inline np.set_printoptions(precision=3, suppress=True) if(1j**2==-1): print("Complex Number") else: print("Not a Complex Number") x = 3.5 + 2.1j print("Type of x:" , type(x)) print("Real part of x:", x.real) print("Imaginary part of x:", x.imag) def plot_complex(a): for x in range(len(a)): plt.plot([0,a[x].real], [0,a[x].imag], 'r-o') plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') plt.ylabel('Imaginary') plt.xlabel('Real') limit = np.max(np.ceil(np.absolute(a))) plt.xlim((-limit,limit)) plt.ylim((-limit,limit)) plt.show() plot_complex([x]) abs(x) r = abs(x) φ = np.arctan2(x.imag, x.real) z = r*np.exp(1j*φ) z == x print(x.conjugate()) plot_complex([x.conjugate()]) a = np.array([[1+2j], [2+2j]]) a a.T.conj() b = np.array([[0.1], [2j]]) b.T.conj() @ a c = np.array([[1], [0]]) d = np.array([[0], [1]]) c.T.conj() @ d print("The square of the l2 norm of a:", np.linalg.norm(a)**2) print("The same thing calculated as an inner product:", a.T.conj() @ a) sum(a != 0), sum(c != 0) np.linalg.norm(a, ord=1) np.kron(c, d) A = np.array([[1+2j, 2], [1j, 3+4j]]) A A.T.conj() A @ a a @ a.T.conj() λs, eigenvectors = np.linalg.eig(A) np.all(A == A.T.conj()) B = a @ a.T.conj() np.all(B == B.T.conj())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(2) qc.h(0) qc.x(1) state = Statevector(qc) plot_bloch_multivector(state)
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# # A quantum circuit is composed by quantum and classical bits. # # here are the objects that we use to create a quantum circuit in qiskit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # we use a quantum register to keep our quantum bits. qreg = QuantumRegister(1) # in this example we will use a single quantum bit # To get an information from a quantum bit, it must be measured. (More details will appear.) # The measurement result is stored classically. # Therefore, we also use a classical regiser with classical bits creg = ClassicalRegister(1) # in this example we will use a single classical bit # now we can define our quantum circuit # it is composed by a quantum and a classical register mycircuit = QuantumCircuit(qreg,creg) # we apply operators on quantum bits # operators are also called as gates # we apply NOT operator represented as "x" in qiskit # operator is a part of the circuit, and we should specify the quantum bit as its parameter mycircuit.x(qreg[0]) # (quantum) bits are enumerated starting from 0 # NOT operator or x-gate is applied to the first qubit of the quantum register # let's run our codes until now, and then draw our circuit print("Everything looks fine, let's continue ...") # in qiskit, the circuit object has a method called "draw" # it can take different parameters # we use "matplotlib" -- the first parameter # we also order the bits by reversing, which helps us to read the output -- the second parameter # let's draw our circuit now mycircuit.draw(output='mpl',reverse_bits=True) # re-execute this cell if you DO NOT see the circuit diagram # measurement is defined by associating a quantum bit to a classical bit mycircuit.measure(qreg[0],creg[0]) # the result will be stored in the classical bit print("Everything looks fine, let's continue ...") # let's draw the circuit again to see how the measurement is defined mycircuit.draw() # we use now ASCII art version # reexecute me if you DO NOT see the circuit diagram # we are done with designing of our circuit # now we can execute it # we execute quantum circuits many times (WHY?) # we use method "execute" and object "Aer" from qiskit library from qiskit import execute, Aer # we create a job object for execution of the circuit # there are three parameters # 1. mycircuit # 2. beckend on which it will be executed: we will use local simulator # 3. how_many_times will it be executed, let's pick it as 1024 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1024) # we can get the result of the outcome as follows counts = job.result().get_counts(mycircuit) print(counts) # usually quantum programs produce probabilistic outcomes # # My second quantum circuit # # we import all at once from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # we will use 4 quantum bits and 4 classical bits qreg2 = QuantumRegister(4) creg2 = ClassicalRegister(4) mycircuit2 = QuantumCircuit(qreg2,creg2) # We will apply x-gate to the first quantum bit twice mycircuit2.x(qreg2[0]) mycircuit2.x(qreg2[0]) # We will apply x-gate to the fourth quantum bit once mycircuit2.x(qreg2[3]) # We will apply x-gate to the third quantum bit three times mycircuit2.x(qreg2[2]) mycircuit2.x(qreg2[2]) mycircuit2.x(qreg2[2]) # We will apply x-gate to the second quantum bit four times mycircuit2.x(qreg2[1]) mycircuit2.x(qreg2[1]) mycircuit2.x(qreg2[1]) mycircuit2.x(qreg2[1]) # if the sizes of quantum and classical registers are the same, we can define measurements with a single line of code mycircuit2.measure(qreg2,creg2) # then each quantum bit and classical bit is associated with respect to their indices # let's run our codes until now, and then draw our circuit print("Everything looks fine, let's continue ...") mycircuit2.draw(output='mpl',reverse_bits=True) # re-execute me if you DO NOT see the circuit diagram job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=500) counts = job.result().get_counts(mycircuit2) print(counts) def print_outcomes(counts): # takes a dictionary variable for outcome in counts: # for each key-value in dictionary reverse_outcome = '' for i in outcome: # each string can be considered as a list of characters reverse_outcome = i + reverse_outcome # each new symbol comes before the old symbol(s) print(reverse_outcome,"is observed",counts[outcome],"times") job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=1024) counts = job.result().get_counts(mycircuit2) # counts is a dictionary object in python print_outcomes(counts) from random import randrange n = 20 r=randrange(n) # pick a number from the list {0,1,...,n-1} print(r) # test this method by using a loop for i in range(10): print(randrange(n)) # # your solution is here # # Quantum register with 10 bits qreg3 = QuantumRegister(10) creg3 = ClassicalRegister(10) # Construct the quantum circuit mycircuit3 = QuantumCircuit(qreg3,creg3) qubits_idx=[] # Randomly iterate through bits for i in range(10): if(randrange(2) == 1): # 1 is the head mycircuit3.x(qreg3[i]) qubits_idx.append(i) # Measure the results mycircuit3.measure(qreg3,creg3) job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=128) counts = job.result().get_counts(mycircuit3) print_outcomes(counts) # display counts and randomly picked index print(counts) print(picked_qubits_idx) mycircuit3.draw(output='mpl',reverse_bits=True)
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram # Create a quantum circuit with 2 qubits # The default initial state of qubits will be |0> or [1,0] qc = QuantumCircuit(2) #Applying the hadarmad gate to target qc.sdg(1) #apply the cx gate to both qubits qc.cx(0,1) #Applying the hadarmad gate to target qc.s(1) #Draw the circuit qc.draw('mpl') #Get the backend for the circuit to display unitary matrix backend = Aer.get_backend('unitary_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_unitary() #import qiskit_textbook and display the combined unitary matrix from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ") #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_statevector() #import qiskit_textbook and display the statevector #from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{Statevector} = ") #execute the circuit and get the plain result out = execute(qc,backend).result() counts = out.get_counts() plot_histogram(counts)
https://github.com/drithidavuluri/Implementation-of-Algorithm-using-Qiskit
drithidavuluri
my_list = [1,3,5,2,4,2,5,8,0,7,6] #classical computation method def oracle(my_input): winner =7 if my_input is winner: response = True else: response = False return response for index, trial_number in enumerate(my_list): if oracle(trial_number) is True: print("Winner is found at index %i" %index) print("%i calls to the oracle used " %(index +1)) break #quantum implemenation from qiskit import * import matplotlib.pyplot as plt import numpy as np from qiskit.tools import job_monitor # oracle circuit oracle = QuantumCircuit(2, name='oracle') oracle.cz(0,1) oracle.to_gate() oracle.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle,[0,1]) grover_circuit.draw(output='mpl') job= execute(grover_circuit, backend=backend) result= job.result() sv= result.get_statevector() np.around(sv,2) #amplitude amplification reflection = QuantumCircuit(2, name='reflection') reflection.h([0,1]) reflection.z([0,1]) reflection.cz(0,1) reflection.h([0,1]) reflection.to_gate() reflection.draw(output='mpl') #testing circuit on simulator simulator = Aer.get_backend('qasm_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle,[0,1]) grover_circuit.append(reflection, [0,1]) grover_circuit.barrier() grover_circuit.measure([0,1],[0,1]) grover_circuit.draw(output='mpl') job= execute(grover_circuit,backend=simulator,shots=1) result=job.result() result.get_counts() #testing on real backend system IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp= provider.get_backend('ibmq_manila') job = execute(grover_circuit,backend=qcomp) job_monitor(job) result=job.result() counts=result.get_counts(grover_circuit) from qiskit.visualization import plot_histogram plot_histogram(counts) counts['11']
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_hinton qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3 , 0) qc.rx(np.pi/5, 1) state = DensityMatrix(qc) plot_state_hinton(state, title="New Hinton Plot")
https://github.com/iAbdullahAlshehri/Deutsch_Jozsa
iAbdullahAlshehri
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 19 19:13:26 2023 @author: abdullahalshihry """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 18 19:15:12 2023 @author: abdullahalshihry """ import qiskit as qs import qiskit.visualization as qv import random import qiskit.circuit as qf def Deutsch_Jozsa(circuit): qr = qs.QuantumRegister(5,'q') cr = qs.ClassicalRegister(4,'c') qc = qs.QuantumCircuit(qr,cr) qc.x(qr[4]) qc.barrier(range(5)) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.h(qr[4]) qc.barrier(range(5)) qc = qc.compose(circuit) qc.barrier(range(5)) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.barrier(range(5)) qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.measure(3,3) job1 = qs.execute(qc, qs.Aer.get_backend('aer_simulator'), shots = 1024) output1 = job1.result().get_counts() print(output1) qc.draw('mpl') def Oracle(): qr = qs.QuantumRegister(5,'q') cr = qs.ClassicalRegister(4,'c') qc = qs.QuantumCircuit(qr,cr) qq = qs.QuantumCircuit(5,name='Uf') v = random.randint(1, 2) if v == 1: qc.cx(0,4) qc.cx(1,4) qc.cx(2,4) qc.cx(3,4) print('Balanced (1)') elif v == 2: qq.i(qr[0]) qq.i(qr[1]) qq.i(qr[2]) qq.i(qr[3]) print('Constant (0)') qq =qq.to_gate() qc.append(qq,[0,1,2,3,4]) return qc Deutsch_Jozsa(Oracle())
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. """ Initialize test. """ import math import unittest import numpy as np from ddt import ddt, data from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit import ClassicalRegister from qiskit import transpile from qiskit import execute, assemble, BasicAer from qiskit.quantum_info import state_fidelity, Statevector, Operator from qiskit.exceptions import QiskitError from qiskit.test import QiskitTestCase from qiskit.extensions.quantum_initializer import Initialize @ddt class TestInitialize(QiskitTestCase): """Qiskit Initialize tests.""" _desired_fidelity = 0.99 def test_uniform_superposition(self): """Initialize a uniform superposition on 2 qubits.""" desired_vector = [0.5, 0.5, 0.5, 0.5] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_deterministic_state(self): """Initialize a computational-basis state |01> on 2 qubits.""" desired_vector = [0, 1, 0, 0] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_statevector(self): """Initialize gates from a statevector.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/5134 (footnote) desired_vector = [0, 0, 0, 1] qc = QuantumCircuit(2) statevector = Statevector.from_label("11") qc.initialize(statevector, [0, 1]) self.assertEqual(qc.data[0].operation.params, desired_vector) def test_bell_state(self): """Initialize a Bell state on 2 qubits.""" desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_ghz_state(self): """Initialize a GHZ state on 3 qubits.""" desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_initialize_register(self): """Initialize one register out of two.""" desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") qr2 = QuantumRegister(2, "qr2") qc = QuantumCircuit(qr, qr2) qc.initialize(desired_vector, qr) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, np.kron([1, 0, 0, 0], desired_vector)) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_initialize_one_by_one(self): """Initializing qubits individually into product state same as initializing the pair.""" qubit_0_state = [1, 0] qubit_1_state = [1 / math.sqrt(2), 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") qc_a = QuantumCircuit(qr) qc_a.initialize(np.kron(qubit_1_state, qubit_0_state), qr) qc_b = QuantumCircuit(qr) qc_b.initialize(qubit_0_state, [qr[0]]) qc_b.initialize(qubit_1_state, [qr[1]]) job = execute([qc_a, qc_b], BasicAer.get_backend("statevector_simulator")) result = job.result() statevector_a = result.get_statevector(0) statevector_b = result.get_statevector(1) fidelity = state_fidelity(statevector_a, statevector_b) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_single_qubit(self): """Initialize a single qubit to a weighted superposition state.""" desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3)] qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_random_3qubit(self): """Initialize to a non-trivial 3-qubit state.""" desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0, ] qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_random_4qubit(self): """Initialize to a non-trivial 4-qubit state.""" desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] qr = QuantumRegister(4, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_malformed_amplitudes(self): """Initializing to a vector with 3 amplitudes fails.""" desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3), 0] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]]) def test_non_unit_probability(self): """Initializing to a vector with probabilities not summing to 1 fails.""" desired_vector = [1, 1] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]]) def test_normalize(self): """Test initializing with a non-normalized vector is normalized, if specified.""" desired_vector = [1, 1] normalized = np.asarray(desired_vector) / np.linalg.norm(desired_vector) qc = QuantumCircuit(1) qc.initialize(desired_vector, [0], normalize=True) op = qc.data[0].operation self.assertAlmostEqual(np.linalg.norm(op.params), 1) self.assertEqual(Statevector(qc), Statevector(normalized)) def test_wrong_vector_size(self): """Initializing to a vector with a size different to the qubit parameter length. See https://github.com/Qiskit/qiskit-terra/issues/2372""" qr = QuantumRegister(2) random_state = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] qc = QuantumCircuit(qr) self.assertRaises(QiskitError, qc.initialize, random_state, qr[0:2]) def test_initialize_middle_circuit(self): """Reset + initialize gives the correct statevector.""" desired_vector = [0.5, 0.5, 0.5, 0.5] qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.reset(qr[0]) qc.reset(qr[1]) qc.initialize(desired_vector, [qr[0], qr[1]]) qc.measure(qr, cr) # statevector simulator does not support reset shots = 2000 threshold = 0.005 * shots job = execute(qc, BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=42) result = job.result() counts = result.get_counts() target = {"00": shots / 4, "01": shots / 4, "10": shots / 4, "11": shots / 4} self.assertDictAlmostEqual(counts, target, threshold) def test_math_amplitudes(self): """Initialize to amplitudes given by math expressions""" desired_vector = [ 0, math.cos(math.pi / 3) * complex(0, 1) / math.sqrt(4), math.sin(math.pi / 3) / math.sqrt(4), 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4), 1 / math.sqrt(4) * complex(0, 1), ] qr = QuantumRegister(4, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_combiner(self): """Combining two circuits containing initialize.""" desired_vector_1 = [1.0 / math.sqrt(2), 1.0 / math.sqrt(2)] desired_vector_2 = [1.0 / math.sqrt(2), -1.0 / math.sqrt(2)] qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") qc1 = QuantumCircuit(qr, cr) qc1.initialize(desired_vector_1, [qr[0]]) qc2 = QuantumCircuit(qr, cr) qc2.initialize(desired_vector_2, [qr[0]]) job = execute(qc1.compose(qc2), BasicAer.get_backend("statevector_simulator")) result = job.result() quantum_state = result.get_statevector() fidelity = state_fidelity(quantum_state, desired_vector_2) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_equivalence(self): """Test two similar initialize instructions evaluate to equal.""" desired_vector = [0.5, 0.5, 0.5, 0.5] qr = QuantumRegister(2, "qr") qc1 = QuantumCircuit(qr, name="circuit") qc1.initialize(desired_vector, [qr[0], qr[1]]) qc2 = QuantumCircuit(qr, name="circuit") qc2.initialize(desired_vector, [qr[0], qr[1]]) self.assertEqual(qc1, qc2) def test_max_number_cnots(self): """ Check if the number of cnots <= 2^(n+1) - 2n (arXiv:quant-ph/0406176) """ num_qubits = 4 _optimization_level = 0 vector = np.array( [ 0.1314346 + 0.0j, 0.32078572 - 0.01542775j, 0.13146466 + 0.0945312j, 0.21090852 + 0.07935982j, 0.1700122 - 0.07905648j, 0.15570757 - 0.12309154j, 0.18039667 + 0.04904504j, 0.22227187 - 0.05055569j, 0.23573255 - 0.09894111j, 0.27307292 - 0.10372994j, 0.24162792 + 0.1090791j, 0.3115577 + 0.1211683j, 0.1851788 + 0.08679141j, 0.36226463 - 0.09940202j, 0.13863395 + 0.10558225j, 0.30767986 + 0.02073838j, ] ) vector = vector / np.linalg.norm(vector) qr = QuantumRegister(num_qubits, "qr") circuit = QuantumCircuit(qr) circuit.initialize(vector, qr) b = transpile( circuit, basis_gates=["u1", "u2", "u3", "cx"], optimization_level=_optimization_level, seed_transpiler=42, ) number_cnots = b.count_ops()["cx"] max_cnots = 2 ** (num_qubits + 1) - 2 * num_qubits self.assertLessEqual(number_cnots, max_cnots) def test_from_labels(self): """Initialize from labels.""" desired_sv = Statevector.from_label("01+-lr") qc = QuantumCircuit(6) qc.initialize("01+-lr", range(6)) actual_sv = Statevector.from_instruction(qc) self.assertTrue(desired_sv == actual_sv) def test_from_int(self): """Initialize from int.""" desired_sv = Statevector.from_label("110101") qc = QuantumCircuit(6) qc.initialize(53, range(6)) actual_sv = Statevector.from_instruction(qc) self.assertTrue(desired_sv == actual_sv) def _remove_resets(self, circ): circ.data = [instr for instr in circ.data if instr.operation.name != "reset"] def test_global_phase_random(self): """Test global phase preservation with random state vectors""" from qiskit.quantum_info.random import random_statevector repeats = 5 for n_qubits in [1, 2, 4]: for irep in range(repeats): with self.subTest(i=f"{n_qubits}_{irep}"): dim = 2**n_qubits qr = QuantumRegister(n_qubits) initializer = QuantumCircuit(qr) target = random_statevector(dim) initializer.initialize(target, qr) uninit = initializer.data[0].operation.definition self._remove_resets(uninit) evolve = Statevector(uninit) self.assertEqual(target, evolve) def test_global_phase_1q(self): """Test global phase preservation with some simple 1q statevectors""" target_list = [ Statevector([1j, 0]), Statevector([0, 1j]), Statevector([1j / np.sqrt(2), 1j / np.sqrt(2)]), ] n_qubits = 1 dim = 2**n_qubits qr = QuantumRegister(n_qubits) for target in target_list: with self.subTest(i=target): initializer = QuantumCircuit(qr) initializer.initialize(target, qr) # need to get rid of the resets in order to use the Operator class disentangler = Operator(initializer.data[0].operation.definition.data[1].operation) zero = Statevector.from_int(0, dim) actual = zero & disentangler self.assertEqual(target, actual) @data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) def test_decompose_contains_stateprep(self, state): """Test initialize decomposes to a StatePreparation and reset""" qc = QuantumCircuit(2) qc.initialize(state) decom_circ = qc.decompose() self.assertEqual(decom_circ.data[0].operation.name, "reset") self.assertEqual(decom_circ.data[1].operation.name, "reset") self.assertEqual(decom_circ.data[2].operation.name, "state_preparation") def test_mutating_params(self): """Test mutating Initialize params correctly updates StatePreparation params""" init = Initialize("11") init.params = "00" qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.append(init, qr) decom_circ = qc.decompose() self.assertEqual(decom_circ.data[2].operation.name, "state_preparation") self.assertEqual(decom_circ.data[2].operation.params, ["0", "0"]) class TestInstructionParam(QiskitTestCase): """Test conversion of numpy type parameters.""" def test_diag(self): """Verify diagonal gate converts numpy.complex to complex.""" # ref: https://github.com/Qiskit/qiskit-aer/issues/696 diag = np.array([1 + 0j, 1 + 0j]) qc = QuantumCircuit(1) qc.diagonal(list(diag), [0]) params = qc.data[0].operation.params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) qobj = assemble(qc) params = qobj.experiments[0].instructions[0].params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) def test_init(self): """Verify initialize gate converts numpy.complex to complex.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4151 qc = QuantumCircuit(1) vec = np.array([0, 0 + 1j]) qc.initialize(vec, 0) params = qc.data[0].operation.params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) qobj = assemble(qc) params = qobj.experiments[0].instructions[0].params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2 pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits) pw_approximation._build() qc = QuantumCircuit(pw_approximation.num_qubits) qc.h(list(range(num_state_qubits))) qc.append(pw_approximation.to_instruction(), qc.qubits) qc.draw(output='mpl')
https://github.com/qclib/qclib
qclib
# Copyright 2021 qclib project. # 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. """ Test qclib.gate.mcg.LdMcSpecialUnitary """ from unittest import TestCase import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library import RXGate from qiskit.quantum_info import Operator from qiskit.circuit.library import UnitaryGate from scipy.stats import unitary_group from qclib.gates.ldmcsu import LdMcSpecialUnitary, Ldmcsu from qclib.gates.util import u2_to_su2 from qclib.util import get_cnot_count NUM_CTRL = 6 def _generate_su_2(): """ Returns random SU(2) matrix """ u_2 = unitary_group.rvs(2) su_2, _ = u2_to_su2(u_2) return su_2 class TestLcMcSpecialUnitary(TestCase): """ Test cases for the decomposition of Multicontrolled Special Unitary with linear depth by Barenco et al. """ def _build_qiskit_circuit(self, su2, num_controls, ctrl_state=None): su2_gate = UnitaryGate(su2) controls_list = list(range(num_controls)) target = num_controls qiskit_circ = QuantumCircuit(num_controls + 1) qiskit_circ.append(su2_gate.control(num_controls, ctrl_state=ctrl_state), [*controls_list, target]) return qiskit_circ def _compute_bound(self, num_qubits): if num_qubits % 2 == 0: return 28 * num_qubits - 88 return 28 * num_qubits - 92 def test_lcmcsu_op_for_trivial_control_state(self): """ Test LdMcSpecialUnitary open controls """ su2 = _generate_su_2() num_controls = NUM_CTRL ldmcsu_circ = LdMcSpecialUnitary(su2, num_controls).definition qiskit_circ = self._build_qiskit_circuit(su2, num_controls) ldmcsu_op = Operator(ldmcsu_circ).data qiskit_op = Operator(qiskit_circ).data self.assertTrue(np.allclose(ldmcsu_op, qiskit_op)) def test_lcmcsu_op_for_all_zero_control_states(self): """ Test LdMcSpecialUnitary with open controls """ su_2 = _generate_su_2() num_controls = NUM_CTRL ctrl_state = '0' * num_controls ldmcsu_circ = LdMcSpecialUnitary(su_2, num_controls, ctrl_state=ctrl_state).definition qiskit_circ = self._build_qiskit_circuit(su_2, num_controls, ctrl_state=ctrl_state) ldmcsu_op = Operator(ldmcsu_circ).data qiskit_op = Operator(qiskit_circ).data self.assertTrue(np.allclose(ldmcsu_op, qiskit_op)) def test_lcmcsu_cnot_count(self): """ Test LdMcSpecialUnitary cx count """ su_2 = _generate_su_2() for num_controls in range(8, 10): ldmcsu_circ = LdMcSpecialUnitary(su_2, num_controls).definition ldmcsu_count = get_cnot_count(ldmcsu_circ) self.assertLessEqual(ldmcsu_count, self._compute_bound(num_controls+1)) class TestMcSpecialUnitary(TestCase): """ Test cases for the decomposition of Multicontrolled Special Unitary with linear depth https://arxiv.org/pdf/2302.06377.pdf """ def _build_qiskit_circuit(self, su2, num_controls, ctrl_state=None): su2_gate = UnitaryGate(su2) controls_list = list(range(num_controls)) target = num_controls qiskit_circ = QuantumCircuit(num_controls + 1) qiskit_circ.append(su2_gate.control(num_controls, ctrl_state=ctrl_state), [*controls_list, target]) return qiskit_circ def _compute_bound(self, num_qubits): if num_qubits % 2 == 0: return 28 * num_qubits - 88 return 28 * num_qubits - 92 def test_lcmcsu_op_for_trivial_control_state(self): """ Test LdMcSpecialUnitary open controls """ su2 = _generate_su_2() num_controls = NUM_CTRL ldmcsu_circ = Ldmcsu(su2, num_controls).definition qiskit_circ = self._build_qiskit_circuit(su2, num_controls) ldmcsu_op = Operator(ldmcsu_circ).data qiskit_op = Operator(qiskit_circ).data self.assertTrue(np.allclose(ldmcsu_op, qiskit_op)) def test_lcmcsu_op_for_all_zero_control_states(self): """ Test LdMcSpecialUnitary with open controls """ su_2 = _generate_su_2() num_controls = NUM_CTRL ctrl_state = '0' * num_controls ldmcsu_circ = Ldmcsu(su_2, num_controls, ctrl_state=ctrl_state).definition qiskit_circ = self._build_qiskit_circuit(su_2, num_controls, ctrl_state=ctrl_state) ldmcsu_op = Operator(ldmcsu_circ).data qiskit_op = Operator(qiskit_circ).data self.assertTrue(np.allclose(ldmcsu_op, qiskit_op)) def test_lcmcsu_cnot_count(self): """ Test LdMcSpecialUnitary cx count """ su_2 = _generate_su_2() for num_controls in range(8, 10): ldmcsu_circ = Ldmcsu(su_2, num_controls).definition ldmcsu_count = get_cnot_count(ldmcsu_circ) self.assertTrue(ldmcsu_count <= 20 * (num_controls + 1)-38) def test_lcmcsu_cnot_count_real_diagonal(self): """ Test LdMcSpecialUnitary cx count """ su_2 = RXGate(0.3).to_matrix() for num_controls in range(8, 10): ldmcsu_circ = Ldmcsu(su_2, num_controls).definition ldmcsu_count = get_cnot_count(ldmcsu_circ) self.assertTrue(ldmcsu_count <= 16 * (num_controls + 1)-40) def test_lcmcsu_op_for_exception_unitary(self): """ Test Ldmcsu with Z gate """ su2 = np.array([[-1., 0.], [0., -1.]]) num_controls = 6 ldmcsu_circ = Ldmcsu(su2, num_controls).definition qiskit_circ = self._build_qiskit_circuit(su2, num_controls) ldmcsu_op = Operator(ldmcsu_circ).data qiskit_op = Operator(qiskit_circ).data self.assertTrue(np.allclose(ldmcsu_op, qiskit_op)) def test_lcmcsu_op_for_exception_unitary_2(self): """ Test Ldmcsu diagonal gate """ su2 = np.array([[np.e**(-1j*0.3), 0], [0, np.e**(1j*0.3)]]) num_controls = 6 ldmcsu_circ = Ldmcsu(su2, num_controls).definition qiskit_circ = self._build_qiskit_circuit(su2, num_controls) ldmcsu_op = Operator(ldmcsu_circ).data qiskit_op = Operator(qiskit_circ).data self.assertTrue(np.allclose(ldmcsu_op, qiskit_op))
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
my_list = [1,3,5,2,4,2,5,8,0,7,6] #classical computation method def oracle(my_input): winner =7 if my_input is winner: response = True else: response = False return response for index, trial_number in enumerate(my_list): if oracle(trial_number) is True: print("Winner is found at index %i" %index) print("%i calls to the oracle used " %(index +1)) break #quantum implemenation from qiskit import * import matplotlib.pyplot as plt import numpy as np from qiskit.tools import job_monitor # oracle circuit oracle = QuantumCircuit(2, name='oracle') oracle.cz(0,1) oracle.to_gate() oracle.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle,[0,1]) grover_circuit.draw(output='mpl') job= execute(grover_circuit, backend=backend) result= job.result() sv= result.get_statevector() np.around(sv,2) #amplitude amplification reflection = QuantumCircuit(2, name='reflection') reflection.h([0,1]) reflection.z([0,1]) reflection.cz(0,1) reflection.h([0,1]) reflection.to_gate() reflection.draw(output='mpl') #testing circuit on simulator simulator = Aer.get_backend('qasm_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle,[0,1]) grover_circuit.append(reflection, [0,1]) grover_circuit.barrier() grover_circuit.measure([0,1],[0,1]) grover_circuit.draw(output='mpl') job= execute(grover_circuit,backend=simulator,shots=1) result=job.result() result.get_counts() #testing on real backend system IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp= provider.get_backend('ibmq_manila') job = execute(grover_circuit,backend=qcomp) job_monitor(job) result=job.result() counts=result.get_counts(grover_circuit) from qiskit.visualization import plot_histogram plot_histogram(counts) counts['11']
https://github.com/Anastasia-Sim/PoW-QCSA-fa22
Anastasia-Sim
print("hello word") hash_dict = { '0000': '1111', '1000': '0111', '0001': '0010', '1001': '1100', '0010': '0000', '1010': '0110', '0011': '0101', '1011': '1001', '0100': '1010', '1100': '0011', '0101': '1101', '1101': '1110', '0110': '1000', '1110': '0001', '0111': '1011', '1111': '0100' } import random def get_strings(usr_input, nonce_len): strarr = [] #generate all input + nonce combinations def generate(n, s=usr_input): if len(s) == n: strarr.append(s) else: generate(n, s + '0') generate(n, s + '1') generate(len(usr_input) + nonce_len) random.shuffle(strarr) return strarr def proof_of_work(usr_input, level, nonce_len): strarr = get_strings(usr_input, nonce_len) count = 1 for i in strarr: if hash_dict[i].startswith('0'*level): # print("found hash", i, "in", count, " tries") random.shuffle(strarr) break; else: count += 1 return count def getAvgTries(tries, level=2, nonce_len=3): sum = 0 usr_input = '1' for i in range(tries): sum += proof_of_work(usr_input, level, nonce_len) return sum/tries getAvgTries(100)
https://github.com/usamisaori/Grover
usamisaori
import qiskit from qiskit import QuantumCircuit from qiskit.visualization import plot_histogram import numpy as np from qiskit import execute, Aer simulator = Aer.get_backend('qasm_simulator') import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') from qiskit.quantum_info import DensityMatrix, Statevector, Operator def getDensityMatrix(circuit): return DensityMatrix(circuit).data state_0 = np.array([1, 0]) # |0> state_1 = np.array([0, 1]) # |1> from functools import reduce Dag = lambda matrix: matrix.conj().T # Dag(M) = M† Kron = lambda *matrices: reduce(np.kron, matrices) def pm(matrix): for row in range(len(matrix)): for col in range (len(matrix[row])): print("{:.3f}".format(matrix[row][col]), end = " ") print() # https://qiskit.org/textbook/ch-algorithms/grover.html def initCircuit(n): circuit = QuantumCircuit(n, n) for i in range(n): circuit.h(i) circuit.barrier() return circuit inputCircuit_2q = initCircuit(2) inputCircuit_2q.draw(output='mpl') def createOracle_3(): circuit = QuantumCircuit(2, 2) # Oracle for find 3 # U_f circuit.cz(0, 1) circuit.barrier() return circuit oracleCircuit_3 = createOracle_3() oracleCircuit_3.draw(output='mpl') O_3 = Operator(oracleCircuit_3).data pm(O_3) # all possible states state_00 = Kron(state_0, state_0) state_01 = Kron(state_0, state_1) state_10 = Kron(state_1, state_0) state_11 = Kron(state_1, state_1) print("O|00>", O_3 @ state_00) print("O|01>", O_3 @ state_01) print("O|10>", O_3 @ state_10) print("O|11>", O_3 @ state_11) # flip phase # H R H, where R = 2|0><0| - I def createR_2q(): circuit = QuantumCircuit(2, 2) circuit.z(0) circuit.z(1) circuit.cz(0, 1) return circuit R_2q = createR_2q() R_2q.draw(output='mpl') R_2q = Operator(R_2q).data pm(R_2q) # flip phase(no work on zero states) => Conditional Phase Shift gate print("RO|00>", R_2q @ O_3 @ state_00) # zero state => would not flip print("RO|01>", R_2q @ O_3 @ state_01) print("RO|10>", R_2q @ O_3 @ state_10) print("RO|11>", R_2q @ O_3 @ state_11) # H R H def createDiffuser_2q(): circuit = QuantumCircuit(2, 2) circuit.h(0) circuit.h(1) circuit = circuit.compose(createR_2q()) circuit.h(0) circuit.h(1) circuit.barrier() return circuit diffuserCircuit_2q = createDiffuser_2q() diffuserCircuit_2q.draw(output='mpl') diff_2q = Operator(diffuserCircuit_2q).data pm(diff_2q) DB = 0.5 * state_00 + 0.5 * state_01 + 0.5 * state_10 + 0.5 * state_11 print("DO|DB>", diff_2q @ O_3 @ DB) def createGroverIteration(oracle, diffuser): return oracle.compose(diffuser) groverIteration_2q = createGroverIteration(createOracle_3(), createDiffuser_2q()) groverIteration_2q.draw(output='mpl') groverIteration_2q = createGroverIteration(createOracle_3(), createDiffuser_2q()) grover_2q_1 = initCircuit(2).compose(groverIteration_2q.copy()) grover_2q_1.draw(output='mpl') grover_2q_1.measure([0, 1], [0, 1]) job = execute(grover_2q_1, simulator, shots = 10000) results = job.result() counts = results.get_counts(grover_2q_1) print(counts) plot_histogram(counts, figsize=(1, 5), color="#CC3333", title="one iteration - find 3") grover_2q_2 = initCircuit(2).compose(groverIteration_2q.copy()).compose(groverIteration_2q.copy()) grover_2q_2.draw(output='mpl') grover_2q_2.measure([0, 1], [0, 1]) job = execute(grover_2q_2, simulator, shots = 10000) results = job.result() counts = results.get_counts(grover_2q_2) print(counts) plot_histogram(counts, figsize=(7, 5), color="#FF9999", title="two iterations - find 3")
https://github.com/KMU-quantum-classroom/qiskit-classroom-converter
KMU-quantum-classroom
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # pylint: disable=duplicate-code """ convert class """ import unittest import warnings from numpy import array from qiskit import QuantumCircuit from qiskit.circuit import Instruction from sympy.physics.quantum.qubit import Qubit from sympy import sqrt from sympy.physics.quantum import represent from qiskit_class_converter.converters.string_to_braket_notation \ import StringToBraketNotationConverter from qiskit_class_converter.converters.matrix_to_quantum_circuit \ import MatrixToQuantumCircuitConverter from qiskit_class_converter.converters.quantum_circuit_to_braket_notation \ import QuantumCircuitToBraketNotationConverter from qiskit_class_converter.converters.quantum_circuit_to_matrix \ import QuantumCircuitToMatrixConverter class TestConvertClass(unittest.TestCase): """Tests Impl class implementation.""" def test_str_to_bra_ket(self): """Tests run method implementation.""" main = StringToBraketNotationConverter() symbol = 1/sqrt(2)*(Qubit('00')+Qubit('11')) input_value = "sqrt(2)*|00>/2+sqrt(2)*|11>/2" result = main.convert(input_value=input_value) self.assertEqual(represent(result), represent(symbol)) def test_matrix_to_quantum_circuit(self): """Tests run method implementation.""" main = MatrixToQuantumCircuitConverter() input_value = [ [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0] ] expect_value = Instruction(name='unitary', num_qubits=2, num_clbits=0, params=[array([[1. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j], [0. + 0.j, 0. + 0.j, 0. + 0.j, 1. + 0.j], [0. + 0.j, 0. + 0.j, 1. + 0.j, 0. + 0.j], [0. + 0.j, 1. + 0.j, 0. + 0.j, 0. + 0.j]])]) result = main.convert(input_value=input_value) self.assertEqual(str(result), str(expect_value)) def test_quantum_circuit_to_bra_ket(self): """Tests run method implementation.""" main = QuantumCircuitToBraketNotationConverter() quantum_circuit = QuantumCircuit(2, 2) quantum_circuit.h(0) quantum_circuit.x(0) quantum_circuit.cx(0, 1) result = main.convert(input_value=quantum_circuit) self.assertEqual(result, "(sqrt(2)/2)*|0> + (sqrt(2)/2)*|11>") def test_quantum_circuit_to_matrix(self): """Tests run method implementation.""" warnings.filterwarnings('ignore') main = QuantumCircuitToMatrixConverter() quantum_circuit = QuantumCircuit(2, 2) quantum_circuit.cx(0, 1) result = main.convert(input_value=quantum_circuit) expect_value = array([ [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0] ]) self.assertTrue((result["result"].astype(int) & expect_value).any())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit import Parameter from qiskit import QuantumCircuit theta = Parameter('$\\theta$') chsh_circuits_no_meas = QuantumCircuit(2) chsh_circuits_no_meas.h(0) chsh_circuits_no_meas.cx(0, 1) chsh_circuits_no_meas.ry(theta, 0) chsh_circuits_no_meas.draw('mpl') import numpy as np number_of_phases = 21 phases = np.linspace(0, 2*np.pi, number_of_phases) # Phases need to be expressed as list of lists in order to work individual_phases = [[ph] for ph in phases] from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" # use the simulator from qiskit_ibm_runtime import Estimator, Session from qiskit.quantum_info import SparsePauliOp ZZ = SparsePauliOp.from_list([("ZZ", 1)]) ZX = SparsePauliOp.from_list([("ZX", 1)]) XZ = SparsePauliOp.from_list([("XZ", 1)]) XX = SparsePauliOp.from_list([("XX", 1)]) ops = [ZZ, ZX, XZ, XX] chsh_est_sim = [] # Simulator with Session(service=service, backend=backend): estimator = Estimator() for op in ops: job = estimator.run( circuits=[chsh_circuits_no_meas]*len(individual_phases), observables=[op]*len(individual_phases), parameter_values=individual_phases) est_result = job.result() chsh_est_sim.append(est_result) # <CHSH1> = <AB> - <Ab> + <aB> + <ab> chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values # <CHSH2> = <AB> + <Ab> - <aB> + <ab> chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values import matplotlib.pyplot as plt import matplotlib.ticker as tck fig, ax = plt.subplots(figsize=(10, 6)) # results from a simulator ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation') ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation') # classical bound +-2 ax.axhline(y=2, color='r', linestyle='--') ax.axhline(y=-2, color='r', linestyle='--') # quantum bound, +-2√2 ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.') ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.') # set x tick labels to the unit of pi ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$')) ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5)) # set title, labels, and legend plt.title('Violation of CHSH Inequality') plt.xlabel('Theta') plt.ylabel('CHSH witness') plt.legend() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit circ = QuantumCircuit(2, 2) circ.h(0) circ.cx(0, 1) circ.measure([0, 1], [0, 1]) circ.draw("mpl") from qiskit import transpile, schedule as build_schedule from qiskit.providers.fake_provider import FakeHanoi backend = FakeHanoi() transpiled_circ = transpile(circ, backend) # Undefined Hadamard is replaced by U1 schedule = build_schedule(transpiled_circ, backend) schedule.draw() from qiskit import pulse with pulse.build() as h_q0: pulse.play(pulse.library.Gaussian(duration=256, amp=0.2, sigma=50, name='custom'), pulse.DriveChannel(0)) circ.add_calibration('h', [0], h_q0) schedule = build_schedule(circ, backend) schedule.draw() circ = QuantumCircuit(2, 2) circ.x(0) circ.x(0) circ.x(1) circ.measure([0, 1], [0, 1]) circ.draw("mpl") schedule = build_schedule(circ, backend, method="as_late_as_possible") schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw() schedule = build_schedule(circ, backend, method="as_soon_as_possible") schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/BOBO1997/osp_solutions
BOBO1997
# -*- 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. import numpy as np from qiskit import compiler, BasicAer, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller def convert_to_basis_gates(circuit): # unroll the circuit using the basis u1, u2, u3, cx, and id gates unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id']) pm = PassManager(passes=[unroller]) qc = compiler.transpile(circuit, BasicAer.get_backend('qasm_simulator'), pass_manager=pm) return qc def is_qubit(qb): # check if the input is a qubit, which is in the form (QuantumRegister, int) return isinstance(qb, tuple) and isinstance(qb[0], QuantumRegister) and isinstance(qb[1], int) def is_qubit_list(qbs): # check if the input is a list of qubits for qb in qbs: if not is_qubit(qb): return False return True def summarize_circuits(circuits): """Summarize circuits based on QuantumCircuit, and four metrics are summarized. Number of qubits and classical bits, and number of operations and depth of circuits. The average statistic is provided if multiple circuits are inputed. Args: circuits (QuantumCircuit or [QuantumCircuit]): the to-be-summarized circuits """ if not isinstance(circuits, list): circuits = [circuits] ret = "" ret += "Submitting {} circuits.\n".format(len(circuits)) ret += "============================================================================\n" stats = np.zeros(4) for i, circuit in enumerate(circuits): dag = circuit_to_dag(circuit) depth = dag.depth() width = dag.width() size = dag.size() classical_bits = dag.num_cbits() op_counts = dag.count_ops() stats[0] += width stats[1] += classical_bits stats[2] += size stats[3] += depth ret = ''.join([ret, "{}-th circuit: {} qubits, {} classical bits and {} operations with depth {}\n op_counts: {}\n".format( i, width, classical_bits, size, depth, op_counts)]) if len(circuits) > 1: stats /= len(circuits) ret = ''.join([ret, "Average: {:.2f} qubits, {:.2f} classical bits and {:.2f} operations with depth {:.2f}\n".format( stats[0], stats[1], stats[2], stats[3])]) ret += "============================================================================\n" return ret
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qr = QuantumRegister(3) qc = QuantumCircuit(qr) c3h_gate = HGate().control(2) qc.append(c3h_gate, qr) qc.draw('mpl')
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit.chemistry.drivers import PySCFDriver, UnitsType, Molecule from qiskit.chemistry.transformations import FermionicTransformation, FermionicQubitMappingType molecule = Molecule(geometry=[['H', [0., 0., 0.]], ['H', [0., 0., 0.735]]], charge=0, multiplicity=1) driver = PySCFDriver(molecule = molecule, unit=UnitsType.ANGSTROM, basis='sto3g') transformation = FermionicTransformation(qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER) from qiskit import Aer from qiskit.aqua import QuantumInstance from qiskit.chemistry.algorithms.ground_state_solvers.minimum_eigensolver_factories import VQEUCCSDFactory vqe_solver = VQEUCCSDFactory(QuantumInstance(Aer.get_backend('statevector_simulator'))) from qiskit.chemistry.algorithms.ground_state_solvers import GroundStateEigensolver calc = GroundStateEigensolver(transformation, vqe_solver) res = calc.solve(driver) print(res) from qiskit.aqua.algorithms import NumPyMinimumEigensolver numpy_solver = NumPyMinimumEigensolver() calc = GroundStateEigensolver(transformation, numpy_solver) res = calc.solve(driver) print(res) import numpy as np distances = np.linspace(0.25, 3.0, 30) exact_energies = [] vqe_energies = [] for dist in distances: molecule = Molecule(geometry=[['H', [0., 0., 0.]], ['H', [0., 0., dist]]], charge=0, multiplicity=1) driver = PySCFDriver(molecule = molecule, unit=UnitsType.ANGSTROM, basis='sto3g') # Exact solver calc = GroundStateEigensolver(transformation, numpy_solver) res = calc.solve(driver) exact_energies.append(res.total_energies) # VQE calc = GroundStateEigensolver(transformation, vqe_solver) res = calc.solve(driver) vqe_energies.append(res.total_energies) import matplotlib.pyplot as plt plt.plot(exact_energies, label = 'Exact solver') plt.plot(vqe_energies, label = 'VQE') plt.title('Dissociation profile') plt.xlabel('Interatomic distance') plt.legend() plt.ylabel('Energy');
https://github.com/7enTropy7/Shor-s-Algorithm_Quantum
7enTropy7
import RSA_module bit_length = int(input("Enter bit_length: ")) public, private = RSA_module.generate_keypair(2**bit_length) msg = input("\nWrite message: ") encrypted_msg, encryption_obj = RSA_module.encrypt(msg, public) print("\nEncrypted message: " + encrypted_msg) decrypted_msg = RSA_module.decrypt(encryption_obj, private) print("\nDecrypted message using RSA Algorithm: " + decrypted_msg) from math import gcd,log from random import randint import numpy as np from qiskit import * qasm_sim = qiskit.Aer.get_backend('qasm_simulator') def period(a,N): available_qubits = 16 r=-1 if N >= 2**available_qubits: print(str(N)+' is too big for IBMQX') qr = QuantumRegister(available_qubits) cr = ClassicalRegister(available_qubits) qc = QuantumCircuit(qr,cr) x0 = randint(1, N-1) x_binary = np.zeros(available_qubits, dtype=bool) for i in range(1, available_qubits + 1): bit_state = (N%(2**i)!=0) if bit_state: N -= 2**(i-1) x_binary[available_qubits-i] = bit_state for i in range(0,available_qubits): if x_binary[available_qubits-i-1]: qc.x(qr[i]) x = x0 while np.logical_or(x != x0, r <= 0): r+=1 qc.measure(qr, cr) for i in range(0,3): qc.x(qr[i]) qc.cx(qr[2],qr[1]) qc.cx(qr[1],qr[2]) qc.cx(qr[2],qr[1]) qc.cx(qr[1],qr[0]) qc.cx(qr[0],qr[1]) qc.cx(qr[1],qr[0]) qc.cx(qr[3],qr[0]) qc.cx(qr[0],qr[1]) qc.cx(qr[1],qr[0]) result = execute(qc,backend = qasm_sim, shots=1024).result() counts = result.get_counts() #print(qc) results = [[],[]] for key,value in counts.items(): results[0].append(key) results[1].append(int(value)) s = results[0][np.argmax(np.array(results[1]))] return r def shors_breaker(N): N = int(N) while True: a=randint(0,N-1) g=gcd(a,N) if g!=1 or N==1: return g,N//g else: r=period(a,N) if r % 2 != 0: continue elif pow(a,r//2,N)==-1: continue else: p=gcd(pow(a,r//2)+1,N) q=gcd(pow(a,r//2)-1,N) if p==N or q==N: continue return p,q def modular_inverse(a,m): a = a % m; for x in range(1, m) : if ((a * x) % m == 1) : return x return 1 N_shor = public[1] assert N_shor>0,"Input must be positive" p,q = shors_breaker(N_shor) phi = (p-1) * (q-1) d_shor = modular_inverse(public[0], phi) decrypted_msg = RSA_module.decrypt(encryption_obj, (d_shor,N_shor)) print('\nMessage Cracked using Shors Algorithm: ' + decrypted_msg + "\n")
https://github.com/sjana01/QiskitNotebooks
sjana01
import sys sys.path.append('../') from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\ sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\ sampleCircuitF from entanglement import Ent import warnings warnings.filterwarnings('ignore') labels = [ 'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3', 'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F' ] samplers = [ sampleCircuitA, sampleCircuitB1, sampleCircuitB2, sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE, sampleCircuitF ] q = 4 for layer in range(1, 4): print(f'qubtis: {q}') print('-' * 25) for (label, sampler) in zip(labels, samplers): expr = Ent(sampler, layer=layer, epoch=3000) print(f'{label}(layer={layer}): {expr}') print()
https://github.com/danielzoch/QPEHashing
danielzoch
!pip install qiskit_ibm_provider !pip install pylatexenc !pip install qiskit !pip install qiskit-ibmq-provider from qiskit import QuantumCircuit, transpile, assemble from qiskit.visualization import plot_histogram from qiskit.providers.ibmq import least_busy, IBMQ import numpy as np # Function to create controlled addition gate def cadd(a, N): U = QuantumCircuit(3, name=f'cadd_{a}') for _ in range(a): U.x(0) U.mcx([0, 1], 2) U.x(0) return U # Function to create inverse Quantum Fourier Transform gate def qft_dagger(n): qc = QuantumCircuit(n) for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc def qpe_circuit(a, exponent, N, precision): # Quantum registers n_count = len(bin(N)[2:]) # Number of bits to represent N in binary qr = QuantumCircuit(n_count + precision + 1, precision) # Apply Hadamard gate to counting qubits qr.h(range(n_count + precision)) # Prepare counting qubits in state |1> qr.x(n_count + precision) # Controlled-U operations for q in range(precision): cu_gate = cadd(2**(n_count - 1), N) qr.append(cu_gate, [i for i in range(3)]) # Use only the first 3 qubits # Inverse QFT qr.append(qft_dagger(n_count + precision), [i for i in range(n_count + precision)]) # Do inverse QFT # Measure counting qubits qr.measure(range(n_count, n_count + precision), range(precision)) # Run on IBM Quantum device backend = get_backend() result = run_on_ibmq(qr, backend) # Extract counts of the first register first_register_counts = {key[:n_count]: val for key, val in result.items()} return first_register_counts, result # Function to get the least busy IBM Quantum device def get_backend(): IBMQ.save_account("ENTER_API_KEY_HERE", overwrite=True) # Load IBM Quantum account IBMQ.load_account() # Get the least busy IBM Quantum device provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) return backend # Function to run the circuit on an IBM Quantum device def run_on_ibmq(qc, backend): t_qpe = transpile(qc, backend, optimization_level=3) qpe_circuit_instance = assemble(t_qpe) result = backend.run(qpe_circuit_instance, shots=1).result() counts = result.get_counts() return counts a = 2 exponent = 3 N = 15 precision = 6 # Precision for Quantum Phase Estimation # Run the quantum circuit results = {} first_register_counts, all_counts = qpe_circuit(a, exponent, N, precision) # Plot histogram for the first register counts plot_histogram(first_register_counts, title='Measurement Histogram - ibmq', bar_labels=True, figsize=(10, 6), color='skyblue') # Print out the results of the first register sorted_dict = dict(sorted(first_register_counts.items())) print("Results of the First Register:") for key, value in sorted_dict.items(): print(f"{key}: {value}") import hashlib def quantum_hash(qpe_results): # Combine quantum results into a classical hash hash_value = 0 for result in qpe_results: # Assuming qpe_results are 0 or 1, XOR them into the hash_value hash_value ^= result return hash_value def sha2_hash(message): # Use SHA-256 from Python's hashlib library sha2 = hashlib.sha256() sha2.update(message.encode()) return sha2.hexdigest() def hybrid_hash(qpe_results, message): # Combine quantum and classical hashes quantum_part = quantum_hash(qpe_results) classical_part = sha2_hash(message) # XOR the quantum and classical hashes hybrid_result = quantum_part ^ int(classical_part, 16) # Convert the result to hexadecimal for representation hex_result = hex(hybrid_result)[2:] return hex_result # Example QPE results (replace this with your actual QPE results) qpe_results = [int(bit) for bit in list(first_register_counts.keys())[0]] # Example message to hash message = "Hello, Quantum World!" # Generate hybrid hash hybrid_result = hybrid_hash(qpe_results, message) # Output the hybrid hash result print("Hybrid Hash Value: " + hybrid_result)
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 %matplotlib inline def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QiskitCircuit(): def __init__(self,shots): self.theta = Parameter('Theta') self.phi = Parameter('Phi') self.shots = shots def create_circuit(): qr = QuantumRegister(1,'q') cr = ClassicalRegister(1,'c') ckt = QuantumCircuit(qr,cr) ckt.h(qr[0]) ckt.barrier() ckt.ry(self.theta,qr[0]) ckt.barrier() ckt.measure(qr,cr) return ckt self.circuit = create_circuit() def N_qubit_expectation_Z(self,counts, shots, nr_qubits): expects = np.zeros(nr_qubits) for key in counts.keys(): perc = counts[key]/shots check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)]) expects += check return expects def bind(self, parameters): [self.theta] = to_numbers(parameters) self.circuit.data[2][0]._params = to_numbers(parameters) 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) return self.N_qubit_expectation_Z(counts,self.shots,1) class TorchCircuit(Function): @staticmethod def forward(ctx, i): if not hasattr(ctx, 'QiskitCirc'): ctx.QiskitCirc = QiskitCircuit(shots=1000) 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) return result.float() * grad_output.float() # x = torch.tensor([np.pi/4, np.pi/4, np.pi/4], requires_grad=True) x = torch.tensor([[0.0]], requires_grad=True) qc = TorchCircuit.apply y1 = qc(x) y1.backward() print(x.grad) qc = TorchCircuit.apply def cost(x): target = -1 expval = qc(x) return torch.abs(qc(x) - target) ** 2, expval x = torch.tensor([[0.0]], requires_grad=True) opt = torch.optim.Adam([x], lr=0.1) num_epoch = 50 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 n=100 idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # concatenate their indices 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, 1) 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) # return F.softmax(x) # x = np.pi*F.tanh(x) # print(x) x = qc(x) x = (x+1)/2 x = torch.cat((x, 1-x), -1) return x network = Net() # optimizer = optim.SGD(network.parameters(), lr=learning_rate, # momentum=momentum) optimizer = optim.Adam(network.parameters(), lr=learning_rate/10) epochs = 30 loss_list = [] for epoch in range(epochs): total_loss = [] target_list = [] for batch_idx, (data, target) in enumerate(train_loader): target_list.append(target.item()) # print(batch_idx) optimizer.zero_grad() output = network(data) # loss = F.nll_loss(output, target) loss = F.cross_entropy(output, target) # print(output) # print(output[0][1].item(), target.item()) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print(loss_list[-1]) plt.plot(loss_list)
https://github.com/TuomasLe/Extended-basis-encoding-and-amplitude-encoding-algorithms-for-Qiskit
TuomasLe
from qiskit import IBMQ IBMQ.load_account() %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 * provider = IBMQ.load_account() from qiskit import QuantumCircuit, IBMQ, execute, Aer, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor,backend_overview from qiskit.visualization import plot_histogram from qiskit.quantum_info.states.statevector import Statevector from qiskit.circuit.library.standard_gates import RYGate, CXGate, XGate from qiskit.circuit import Parameter import math data = ['1111', '1111'] ### each data value must have the same length, but the length can be changed ### the length of the data vector must be a power of two nancilla = int(math.log2(len(data))) print(nancilla) nqubits = len(data[0]) + nancilla nclassical = nqubits q = QuantumRegister(nqubits) c = ClassicalRegister(nclassical) # anc = AncillaRegister(nancilla) circ = QuantumCircuit(q, c) def getCtrlState(j, ancillalength): ctrl_bin = str(bin(j)) ctrl_str = ctrl_bin.split('b')[1].zfill(ancillalength) ctrl_str = ''.join(reversed(ctrl_str)) ### Reverse because of Qiskit's most significant bit convention return ctrl_str maxqubit = nqubits - 1 max_encodable_qubit = maxqubit - nancilla for h in range(nancilla): circ.h(maxqubit - h) for i in range(len(data[0])): for j in range(len(data)): if (data[j][i] == '1'): ctrl = getCtrlState(j, nancilla) cx0 = XGate().control(nancilla, ctrl_state = ctrl) ancillaqubits = [] for k in range(nancilla): ancillaqubits.append(maxqubit - k) ancillaqubits.append(max_encodable_qubit - i) circ.append(cx0, ancillaqubits) circ.barrier() circ.measure(q, c) circ.draw(output='mpl') provider = IBMQ.get_provider() provider.backends() local_sim_backend = Aer.get_backend('qasm_simulator') sim_backend = provider.get_backend('ibmq_qasm_simulator') real_backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= nqubits and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", real_backend) print(real_backend) job1 = execute(circ,local_sim_backend) job2 = execute(circ,sim_backend) job3 = execute(circ,real_backend) job_monitor(job3) counts1 = job1.result().get_counts() counts2 = job2.result().get_counts() counts3 = job3.result().get_counts() legend = ['Local simulator', 'Remote simulator', 'Real processor'] circ.draw() plot_histogram([counts1, counts2, counts3], legend=legend)
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/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 preset pass manager API""" import unittest from test import combine from ddt import ddt, data import numpy as np import qiskit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.circuit import Qubit, Gate, ControlFlowOp, ForLoopOp from qiskit.compiler import transpile, assemble from qiskit.transpiler import CouplingMap, Layout, PassManager, TranspilerError, Target from qiskit.circuit.library import U2Gate, U3Gate, QuantumVolume, CXGate, CZGate, XGate from qiskit.transpiler.passes import ( ALAPScheduleAnalysis, PadDynamicalDecoupling, RemoveResetInZeroState, ) from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import ( FakeBelem, FakeTenerife, FakeMelbourne, FakeJohannesburg, FakeRueschlikon, FakeTokyo, FakePoughkeepsie, FakeLagosV2, ) from qiskit.converters import circuit_to_dag from qiskit.circuit.library import GraphState from qiskit.quantum_info import random_unitary from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.transpiler.preset_passmanagers import level0, level1, level2, level3 from qiskit.transpiler.passes import Collect2qBlocks, GatesInBasis from qiskit.transpiler.preset_passmanagers.builtin_plugins import OptimizationPassManager def mock_get_passmanager_stage( stage_name, plugin_name, pm_config, optimization_level=None, # pylint: disable=unused-argument ) -> PassManager: """Mock function for get_passmanager_stage.""" if stage_name == "translation" and plugin_name == "custom_stage_for_test": pm = PassManager([RemoveResetInZeroState()]) return pm elif stage_name == "scheduling" and plugin_name == "custom_stage_for_test": dd_sequence = [XGate(), XGate()] pm = PassManager( [ ALAPScheduleAnalysis(pm_config.instruction_durations), PadDynamicalDecoupling(pm_config.instruction_durations, dd_sequence), ] ) return pm elif stage_name == "init": return PassManager([]) elif stage_name == "routing": return PassManager([]) elif stage_name == "optimization": return OptimizationPassManager().pass_manager(pm_config, optimization_level) elif stage_name == "layout": return PassManager([]) else: raise Exception("Failure, unexpected stage plugin combo for test") def emptycircuit(): """Empty circuit""" return QuantumCircuit() def circuit_2532(): """See https://github.com/Qiskit/qiskit-terra/issues/2532""" circuit = QuantumCircuit(5) circuit.cx(2, 4) return circuit @ddt class TestPresetPassManager(QiskitTestCase): """Test preset passmanagers work as expected.""" @combine(level=[0, 1, 2, 3], name="level{level}") def test_no_coupling_map_with_sabre(self, level): """Test that coupling_map can be None with Sabre (level={level})""" q = QuantumRegister(2, name="q") circuit = QuantumCircuit(q) circuit.cz(q[0], q[1]) result = transpile( circuit, coupling_map=None, layout_method="sabre", routing_method="sabre", optimization_level=level, ) self.assertEqual(result, circuit) @combine(level=[0, 1, 2, 3], name="level{level}") def test_no_coupling_map(self, level): """Test that coupling_map can be None (level={level})""" q = QuantumRegister(2, name="q") circuit = QuantumCircuit(q) circuit.cz(q[0], q[1]) result = transpile(circuit, basis_gates=["u1", "u2", "u3", "cx"], optimization_level=level) self.assertIsInstance(result, QuantumCircuit) def test_layout_3239(self, level=3): """Test final layout after preset level3 passmanager does not include diagonal gates See: https://github.com/Qiskit/qiskit-terra/issues/3239 """ qc = QuantumCircuit(5, 5) qc.h(0) qc.cx(range(3), range(1, 4)) qc.z(range(4)) qc.measure(range(4), range(4)) result = transpile( qc, basis_gates=["u1", "u2", "u3", "cx"], layout_method="trivial", optimization_level=level, ) dag = circuit_to_dag(result) op_nodes = [node.name for node in dag.topological_op_nodes()] self.assertNotIn("u1", op_nodes) # Check if the diagonal Z-Gates (u1) were removed @combine(level=[0, 1, 2, 3], name="level{level}") def test_no_basis_gates(self, level): """Test that basis_gates can be None (level={level})""" q = QuantumRegister(2, name="q") circuit = QuantumCircuit(q) circuit.h(q[0]) circuit.cz(q[0], q[1]) result = transpile(circuit, basis_gates=None, optimization_level=level) self.assertEqual(result, circuit) def test_level0_keeps_reset(self): """Test level 0 should keep the reset instructions""" q = QuantumRegister(2, name="q") circuit = QuantumCircuit(q) circuit.reset(q[0]) circuit.reset(q[0]) result = transpile(circuit, basis_gates=None, optimization_level=0) self.assertEqual(result, circuit) @combine(level=[0, 1, 2, 3], name="level{level}") def test_unitary_is_preserved_if_in_basis(self, level): """Test that a unitary is not synthesized if in the basis.""" qc = QuantumCircuit(2) qc.unitary(random_unitary(4, seed=42), [0, 1]) qc.measure_all() result = transpile(qc, basis_gates=["cx", "u", "unitary"], optimization_level=level) self.assertEqual(result, qc) @combine(level=[0, 1, 2, 3], name="level{level}") def test_unitary_is_preserved_if_basis_is_None(self, level): """Test that a unitary is not synthesized if basis is None.""" qc = QuantumCircuit(2) qc.unitary(random_unitary(4, seed=4242), [0, 1]) qc.measure_all() result = transpile(qc, basis_gates=None, optimization_level=level) self.assertEqual(result, qc) @combine(level=[0, 1, 2, 3], name="level{level}") def test_unitary_is_preserved_if_in_basis_synthesis_translation(self, level): """Test that a unitary is not synthesized if in the basis with synthesis translation.""" qc = QuantumCircuit(2) qc.unitary(random_unitary(4, seed=424242), [0, 1]) qc.measure_all() result = transpile( qc, basis_gates=["cx", "u", "unitary"], optimization_level=level, translation_method="synthesis", ) self.assertEqual(result, qc) @combine(level=[0, 1, 2, 3], name="level{level}") def test_unitary_is_preserved_if_basis_is_None_synthesis_transltion(self, level): """Test that a unitary is not synthesized if basis is None with synthesis translation.""" qc = QuantumCircuit(2) qc.unitary(random_unitary(4, seed=42424242), [0, 1]) qc.measure_all() result = transpile( qc, basis_gates=None, optimization_level=level, translation_method="synthesis" ) self.assertEqual(result, qc) @combine(level=[0, 1, 2, 3], name="level{level}") def test_respect_basis(self, level): """Test that all levels respect basis""" qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.cp(np.pi / 8, 0, 1) qc.cp(np.pi / 4, 0, 2) basis_gates = ["id", "rz", "sx", "x", "cx"] result = transpile( qc, basis_gates=basis_gates, coupling_map=[[0, 1], [2, 1]], optimization_level=level ) dag = circuit_to_dag(result) circuit_ops = {node.name for node in dag.topological_op_nodes()} self.assertEqual(circuit_ops.union(set(basis_gates)), set(basis_gates)) @combine(level=[0, 1, 2, 3], name="level{level}") def test_alignment_constraints_called_with_by_default(self, level): """Test that TimeUnitConversion is not called if there is no delay in the circuit.""" q = QuantumRegister(2, name="q") circuit = QuantumCircuit(q) circuit.h(q[0]) circuit.cz(q[0], q[1]) with unittest.mock.patch("qiskit.transpiler.passes.TimeUnitConversion.run") as mock: transpile(circuit, backend=FakeJohannesburg(), optimization_level=level) mock.assert_not_called() @combine(level=[0, 1, 2, 3], name="level{level}") def test_alignment_constraints_called_with_delay_in_circuit(self, level): """Test that TimeUnitConversion is called if there is a delay in the circuit.""" q = QuantumRegister(2, name="q") circuit = QuantumCircuit(q) circuit.h(q[0]) circuit.cz(q[0], q[1]) circuit.delay(9.5, unit="ns") with unittest.mock.patch( "qiskit.transpiler.passes.TimeUnitConversion.run", return_value=circuit_to_dag(circuit) ) as mock: transpile(circuit, backend=FakeJohannesburg(), optimization_level=level) mock.assert_called_once() def test_unroll_only_if_not_gates_in_basis(self): """Test that the list of passes _unroll only runs if a gate is not in the basis.""" qcomp = FakeBelem() qv_circuit = QuantumVolume(3) gates_in_basis_true_count = 0 collect_2q_blocks_count = 0 # pylint: disable=unused-argument def counting_callback_func(pass_, dag, time, property_set, count): nonlocal gates_in_basis_true_count nonlocal collect_2q_blocks_count if isinstance(pass_, GatesInBasis) and property_set["all_gates_in_basis"]: gates_in_basis_true_count += 1 if isinstance(pass_, Collect2qBlocks): collect_2q_blocks_count += 1 transpile( qv_circuit, backend=qcomp, optimization_level=3, callback=counting_callback_func, translation_method="synthesis", ) self.assertEqual(gates_in_basis_true_count + 1, collect_2q_blocks_count) def test_get_vf2_call_limit_deprecated(self): """Test that calling test_get_vf2_call_limit emits deprecation warning.""" with self.assertWarns(DeprecationWarning): qiskit.transpiler.preset_passmanagers.common.get_vf2_call_limit(optimization_level=3) @ddt class TestTranspileLevels(QiskitTestCase): """Test transpiler on fake backend""" @combine( circuit=[emptycircuit, circuit_2532], level=[0, 1, 2, 3], backend=[ FakeTenerife(), FakeMelbourne(), FakeRueschlikon(), FakeTokyo(), FakePoughkeepsie(), None, ], dsc="Transpiler {circuit.__name__} on {backend} backend at level {level}", name="{circuit.__name__}_{backend}_level{level}", ) def test(self, circuit, level, backend): """All the levels with all the backends""" result = transpile(circuit(), backend=backend, optimization_level=level, seed_transpiler=42) self.assertIsInstance(result, QuantumCircuit) @ddt class TestPassesInspection(QiskitTestCase): """Test run passes under different conditions""" def setUp(self): """Sets self.callback to set self.passes with the passes that have been executed""" super().setUp() self.passes = [] def callback(**kwargs): self.passes.append(kwargs["pass_"].__class__.__name__) self.callback = callback @data(0, 1, 2, 3) def test_no_coupling_map(self, level): """Without coupling map, no layout selection nor swapper""" qr = QuantumRegister(3, "q") qc = QuantumCircuit(qr) qc.cx(qr[2], qr[1]) qc.cx(qr[2], qr[0]) _ = transpile(qc, optimization_level=level, callback=self.callback) self.assertNotIn("SetLayout", self.passes) self.assertNotIn("TrivialLayout", self.passes) self.assertNotIn("ApplyLayout", self.passes) self.assertNotIn("StochasticSwap", self.passes) self.assertNotIn("SabreSwap", self.passes) self.assertNotIn("CheckGateDirection", self.passes) @data(0, 1, 2, 3) def test_backend(self, level): """With backend a layout and a swapper is run""" qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(qr[2], qr[4]) backend = FakeMelbourne() _ = transpile(qc, backend, optimization_level=level, callback=self.callback) self.assertIn("SetLayout", self.passes) self.assertIn("ApplyLayout", self.passes) self.assertIn("CheckGateDirection", self.passes) @data(0, 1, 2, 3) def test_5409(self, level): """The parameter layout_method='noise_adaptive' should be honored See: https://github.com/Qiskit/qiskit-terra/issues/5409 """ qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(qr[2], qr[4]) backend = FakeMelbourne() _ = transpile( qc, backend, layout_method="noise_adaptive", optimization_level=level, callback=self.callback, ) self.assertIn("SetLayout", self.passes) self.assertIn("ApplyLayout", self.passes) self.assertIn("NoiseAdaptiveLayout", self.passes) @data(0, 1, 2, 3) def test_symmetric_coupling_map(self, level): """Symmetric coupling map does not run CheckGateDirection""" qr = QuantumRegister(2, "q") qc = QuantumCircuit(qr) qc.cx(qr[0], qr[1]) coupling_map = [[0, 1], [1, 0]] _ = transpile( qc, coupling_map=coupling_map, initial_layout=[0, 1], optimization_level=level, callback=self.callback, ) self.assertIn("SetLayout", self.passes) self.assertIn("ApplyLayout", self.passes) self.assertNotIn("CheckGateDirection", self.passes) @data(0, 1, 2, 3) def test_initial_layout_fully_connected_cm(self, level): """Honor initial_layout when coupling_map=None See: https://github.com/Qiskit/qiskit-terra/issues/5345 """ qr = QuantumRegister(2, "q") qc = QuantumCircuit(qr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) transpiled = transpile( qc, initial_layout=[0, 1], optimization_level=level, callback=self.callback ) self.assertIn("SetLayout", self.passes) self.assertIn("ApplyLayout", self.passes) self.assertEqual(transpiled._layout.initial_layout, Layout.from_qubit_list([qr[0], qr[1]])) @data(0, 1, 2, 3) def test_partial_layout_fully_connected_cm(self, level): """Honor initial_layout (partially defined) when coupling_map=None See: https://github.com/Qiskit/qiskit-terra/issues/5345 """ qr = QuantumRegister(2, "q") qc = QuantumCircuit(qr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) transpiled = transpile( qc, initial_layout=[4, 2], optimization_level=level, callback=self.callback ) self.assertIn("SetLayout", self.passes) self.assertIn("ApplyLayout", self.passes) ancilla = QuantumRegister(3, "ancilla") self.assertEqual( transpiled._layout.initial_layout, Layout.from_qubit_list([ancilla[0], ancilla[1], qr[1], ancilla[2], qr[0]]), ) @unittest.mock.patch.object( level0.PassManagerStagePluginManager, "get_passmanager_stage", wraps=mock_get_passmanager_stage, ) def test_backend_with_custom_stages(self, _plugin_manager_mock): """Test transpile() executes backend specific custom stage.""" optimization_level = 1 class TargetBackend(FakeLagosV2): """Fake lagos subclass with custom transpiler stages.""" def get_scheduling_stage_plugin(self): """Custom scheduling stage.""" return "custom_stage_for_test" def get_translation_stage_plugin(self): """Custom post translation stage.""" return "custom_stage_for_test" target = TargetBackend() qr = QuantumRegister(2, "q") qc = QuantumCircuit(qr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) _ = transpile(qc, target, optimization_level=optimization_level, callback=self.callback) self.assertIn("ALAPScheduleAnalysis", self.passes) self.assertIn("PadDynamicalDecoupling", self.passes) self.assertIn("RemoveResetInZeroState", self.passes) def test_level1_runs_vf2post_layout_when_routing_required(self): """Test that if we run routing as part of sabre layout VF2PostLayout runs.""" target = FakeLagosV2() qc = QuantumCircuit(5) qc.h(0) qc.cy(0, 1) qc.cy(0, 2) qc.cy(0, 3) qc.cy(0, 4) qc.measure_all() _ = transpile(qc, target, optimization_level=1, callback=self.callback) # Expected call path for layout and routing is: # 1. TrivialLayout (no perfect match) # 2. VF2Layout (no perfect match) # 3. SabreLayout (heuristic layout and also runs routing) # 4. VF2PostLayout (applies a better layout) self.assertIn("TrivialLayout", self.passes) self.assertIn("VF2Layout", self.passes) self.assertIn("SabreLayout", self.passes) self.assertIn("VF2PostLayout", self.passes) # Assert we don't run standalone sabre swap self.assertNotIn("SabreSwap", self.passes) def test_level1_runs_vf2post_layout_when_routing_method_set_and_required(self): """Test that if we run routing as part of sabre layout VF2PostLayout runs.""" target = FakeLagosV2() qc = QuantumCircuit(5) qc.h(0) qc.cy(0, 1) qc.cy(0, 2) qc.cy(0, 3) qc.cy(0, 4) qc.measure_all() _ = transpile( qc, target, optimization_level=1, routing_method="stochastic", callback=self.callback ) # Expected call path for layout and routing is: # 1. TrivialLayout (no perfect match) # 2. VF2Layout (no perfect match) # 3. SabreLayout (heuristic layout and also runs routing) # 4. VF2PostLayout (applies a better layout) self.assertIn("TrivialLayout", self.passes) self.assertIn("VF2Layout", self.passes) self.assertIn("SabreLayout", self.passes) self.assertIn("VF2PostLayout", self.passes) self.assertIn("StochasticSwap", self.passes) def test_level1_not_runs_vf2post_layout_when_layout_method_set(self): """Test that if we don't run VF2PostLayout with custom layout_method.""" target = FakeLagosV2() qc = QuantumCircuit(5) qc.h(0) qc.cy(0, 1) qc.cy(0, 2) qc.cy(0, 3) qc.cy(0, 4) qc.measure_all() _ = transpile( qc, target, optimization_level=1, layout_method="dense", callback=self.callback ) self.assertNotIn("TrivialLayout", self.passes) self.assertNotIn("VF2Layout", self.passes) self.assertNotIn("SabreLayout", self.passes) self.assertNotIn("VF2PostLayout", self.passes) self.assertIn("DenseLayout", self.passes) self.assertIn("SabreSwap", self.passes) def test_level1_not_run_vf2post_layout_when_trivial_is_perfect(self): """Test that if we find a trivial perfect layout we don't run vf2post.""" target = FakeLagosV2() qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() _ = transpile(qc, target, optimization_level=1, callback=self.callback) self.assertIn("TrivialLayout", self.passes) self.assertNotIn("VF2Layout", self.passes) self.assertNotIn("SabreLayout", self.passes) self.assertNotIn("VF2PostLayout", self.passes) # Assert we don't run standalone sabre swap self.assertNotIn("SabreSwap", self.passes) def test_level1_not_run_vf2post_layout_when_vf2layout_is_perfect(self): """Test that if we find a vf2 perfect layout we don't run vf2post.""" target = FakeLagosV2() qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.measure_all() _ = transpile(qc, target, optimization_level=1, callback=self.callback) self.assertIn("TrivialLayout", self.passes) self.assertIn("VF2Layout", self.passes) self.assertNotIn("SabreLayout", self.passes) self.assertNotIn("VF2PostLayout", self.passes) # Assert we don't run standalone sabre swap self.assertNotIn("SabreSwap", self.passes) def test_level1_runs_vf2post_layout_when_routing_required_control_flow(self): """Test that if we run routing as part of sabre layout VF2PostLayout runs.""" target = FakeLagosV2() _target = target.target target._target.add_instruction(ForLoopOp, name="for_loop") qc = QuantumCircuit(5) qc.h(0) qc.cy(0, 1) qc.cy(0, 2) qc.cy(0, 3) qc.cy(0, 4) with qc.for_loop((1,)): qc.cx(0, 1) qc.measure_all() _ = transpile(qc, target, optimization_level=1, callback=self.callback) # Expected call path for layout and routing is: # 1. TrivialLayout (no perfect match) # 2. VF2Layout (no perfect match) # 3. SabreLayout (heuristic layout) # 4. VF2PostLayout (applies a better layout) self.assertIn("TrivialLayout", self.passes) self.assertIn("VF2Layout", self.passes) self.assertIn("SabreLayout", self.passes) self.assertIn("VF2PostLayout", self.passes) def test_level1_not_runs_vf2post_layout_when_layout_method_set_control_flow(self): """Test that if we don't run VF2PostLayout with custom layout_method.""" target = FakeLagosV2() _target = target.target target._target.add_instruction(ForLoopOp, name="for_loop") qc = QuantumCircuit(5) qc.h(0) qc.cy(0, 1) qc.cy(0, 2) qc.cy(0, 3) qc.cy(0, 4) with qc.for_loop((1,)): qc.cx(0, 1) qc.measure_all() _ = transpile( qc, target, optimization_level=1, layout_method="dense", callback=self.callback ) self.assertNotIn("TrivialLayout", self.passes) self.assertNotIn("VF2Layout", self.passes) self.assertNotIn("SabreLayout", self.passes) self.assertNotIn("VF2PostLayout", self.passes) self.assertIn("DenseLayout", self.passes) self.assertIn("SabreSwap", self.passes) def test_level1_not_run_vf2post_layout_when_trivial_is_perfect_control_flow(self): """Test that if we find a trivial perfect layout we don't run vf2post.""" target = FakeLagosV2() _target = target.target target._target.add_instruction(ForLoopOp, name="for_loop") qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) with qc.for_loop((1,)): qc.cx(0, 1) qc.measure_all() _ = transpile(qc, target, optimization_level=1, callback=self.callback) self.assertIn("TrivialLayout", self.passes) self.assertNotIn("VF2Layout", self.passes) self.assertNotIn("SabreLayout", self.passes) self.assertNotIn("SabreSwap", self.passes) self.assertNotIn("VF2PostLayout", self.passes) def test_level1_not_run_vf2post_layout_when_vf2layout_is_perfect_control_flow(self): """Test that if we find a vf2 perfect layout we don't run vf2post.""" target = FakeLagosV2() _target = target.target target._target.add_instruction(ForLoopOp, name="for_loop") qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) with qc.for_loop((1,)): qc.cx(0, 1) qc.measure_all() _ = transpile(qc, target, optimization_level=1, callback=self.callback) self.assertIn("TrivialLayout", self.passes) self.assertIn("VF2Layout", self.passes) self.assertNotIn("SabreLayout", self.passes) self.assertNotIn("VF2PostLayout", self.passes) self.assertNotIn("SabreSwap", self.passes) @ddt class TestInitialLayouts(QiskitTestCase): """Test transpiling with different layouts""" @data(0, 1, 2, 3) def test_layout_1711(self, level): """Test that a user-given initial layout is respected, in the qobj. See: https://github.com/Qiskit/qiskit-terra/issues/1711 """ # build a circuit which works as-is on the coupling map, using the initial layout qr = QuantumRegister(3, "q") cr = ClassicalRegister(3) ancilla = QuantumRegister(13, "ancilla") qc = QuantumCircuit(qr, cr) qc.cx(qr[2], qr[1]) qc.cx(qr[2], qr[0]) initial_layout = {0: qr[1], 2: qr[0], 15: qr[2]} final_layout = { 0: qr[1], 1: ancilla[0], 2: qr[0], 3: ancilla[1], 4: ancilla[2], 5: ancilla[3], 6: ancilla[4], 7: ancilla[5], 8: ancilla[6], 9: ancilla[7], 10: ancilla[8], 11: ancilla[9], 12: ancilla[10], 13: ancilla[11], 14: ancilla[12], 15: qr[2], } backend = FakeRueschlikon() qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level) qobj = assemble(qc_b) self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout) compiled_ops = qobj.experiments[0].instructions for operation in compiled_ops: if operation.name == "cx": self.assertIn(operation.qubits, backend.configuration().coupling_map) self.assertIn(operation.qubits, [[15, 0], [15, 2]]) @data(0, 1, 2, 3) def test_layout_2532(self, level): """Test that a user-given initial layout is respected, in the transpiled circuit. See: https://github.com/Qiskit/qiskit-terra/issues/2532 """ # build a circuit which works as-is on the coupling map, using the initial layout qr = QuantumRegister(5, "q") cr = ClassicalRegister(2) ancilla = QuantumRegister(9, "ancilla") qc = QuantumCircuit(qr, cr) qc.cx(qr[2], qr[4]) initial_layout = { qr[2]: 11, qr[4]: 3, # map to [11, 3] connection qr[0]: 1, qr[1]: 5, qr[3]: 9, } final_layout = { 0: ancilla[0], 1: qr[0], 2: ancilla[1], 3: qr[4], 4: ancilla[2], 5: qr[1], 6: ancilla[3], 7: ancilla[4], 8: ancilla[5], 9: qr[3], 10: ancilla[6], 11: qr[2], 12: ancilla[7], 13: ancilla[8], } backend = FakeMelbourne() qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level) self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout) output_qr = qc_b.qregs[0] for instruction in qc_b: if instruction.operation.name == "cx": for qubit in instruction.qubits: self.assertIn(qubit, [output_qr[11], output_qr[3]]) @data(0, 1, 2, 3) def test_layout_2503(self, level): """Test that a user-given initial layout is respected, even if cnots are not in the coupling map. See: https://github.com/Qiskit/qiskit-terra/issues/2503 """ # build a circuit which works as-is on the coupling map, using the initial layout qr = QuantumRegister(3, "q") cr = ClassicalRegister(2) ancilla = QuantumRegister(17, "ancilla") qc = QuantumCircuit(qr, cr) qc.append(U3Gate(0.1, 0.2, 0.3), [qr[0]]) qc.append(U2Gate(0.4, 0.5), [qr[2]]) qc.barrier() qc.cx(qr[0], qr[2]) initial_layout = [6, 7, 12] final_layout = { 0: ancilla[0], 1: ancilla[1], 2: ancilla[2], 3: ancilla[3], 4: ancilla[4], 5: ancilla[5], 6: qr[0], 7: qr[1], 8: ancilla[6], 9: ancilla[7], 10: ancilla[8], 11: ancilla[9], 12: qr[2], 13: ancilla[10], 14: ancilla[11], 15: ancilla[12], 16: ancilla[13], 17: ancilla[14], 18: ancilla[15], 19: ancilla[16], } backend = FakePoughkeepsie() qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level) self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout) output_qr = qc_b.qregs[0] self.assertIsInstance(qc_b[0].operation, U3Gate) self.assertEqual(qc_b[0].qubits[0], output_qr[6]) self.assertIsInstance(qc_b[1].operation, U2Gate) self.assertEqual(qc_b[1].qubits[0], output_qr[12]) @ddt class TestFinalLayouts(QiskitTestCase): """Test final layouts after preset transpilation""" @data(0, 1, 2, 3) def test_layout_tokyo_2845(self, level): """Test that final layout in tokyo #2845 See: https://github.com/Qiskit/qiskit-terra/issues/2845 """ qr1 = QuantumRegister(3, "qr1") qr2 = QuantumRegister(2, "qr2") qc = QuantumCircuit(qr1, qr2) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[2], qr2[0]) qc.cx(qr2[0], qr2[1]) trivial_layout = { 0: Qubit(QuantumRegister(3, "qr1"), 0), 1: Qubit(QuantumRegister(3, "qr1"), 1), 2: Qubit(QuantumRegister(3, "qr1"), 2), 3: Qubit(QuantumRegister(2, "qr2"), 0), 4: Qubit(QuantumRegister(2, "qr2"), 1), 5: Qubit(QuantumRegister(15, "ancilla"), 0), 6: Qubit(QuantumRegister(15, "ancilla"), 1), 7: Qubit(QuantumRegister(15, "ancilla"), 2), 8: Qubit(QuantumRegister(15, "ancilla"), 3), 9: Qubit(QuantumRegister(15, "ancilla"), 4), 10: Qubit(QuantumRegister(15, "ancilla"), 5), 11: Qubit(QuantumRegister(15, "ancilla"), 6), 12: Qubit(QuantumRegister(15, "ancilla"), 7), 13: Qubit(QuantumRegister(15, "ancilla"), 8), 14: Qubit(QuantumRegister(15, "ancilla"), 9), 15: Qubit(QuantumRegister(15, "ancilla"), 10), 16: Qubit(QuantumRegister(15, "ancilla"), 11), 17: Qubit(QuantumRegister(15, "ancilla"), 12), 18: Qubit(QuantumRegister(15, "ancilla"), 13), 19: Qubit(QuantumRegister(15, "ancilla"), 14), } vf2_layout = { 0: Qubit(QuantumRegister(15, "ancilla"), 0), 1: Qubit(QuantumRegister(15, "ancilla"), 1), 2: Qubit(QuantumRegister(15, "ancilla"), 2), 3: Qubit(QuantumRegister(15, "ancilla"), 3), 4: Qubit(QuantumRegister(15, "ancilla"), 4), 5: Qubit(QuantumRegister(15, "ancilla"), 5), 6: Qubit(QuantumRegister(3, "qr1"), 1), 7: Qubit(QuantumRegister(15, "ancilla"), 6), 8: Qubit(QuantumRegister(15, "ancilla"), 7), 9: Qubit(QuantumRegister(15, "ancilla"), 8), 10: Qubit(QuantumRegister(3, "qr1"), 0), 11: Qubit(QuantumRegister(3, "qr1"), 2), 12: Qubit(QuantumRegister(15, "ancilla"), 9), 13: Qubit(QuantumRegister(15, "ancilla"), 10), 14: Qubit(QuantumRegister(15, "ancilla"), 11), 15: Qubit(QuantumRegister(15, "ancilla"), 12), 16: Qubit(QuantumRegister(2, "qr2"), 0), 17: Qubit(QuantumRegister(2, "qr2"), 1), 18: Qubit(QuantumRegister(15, "ancilla"), 13), 19: Qubit(QuantumRegister(15, "ancilla"), 14), } # Trivial layout expected_layout_level0 = trivial_layout # Dense layout expected_layout_level1 = vf2_layout # CSP layout expected_layout_level2 = vf2_layout expected_layout_level3 = vf2_layout expected_layouts = [ expected_layout_level0, expected_layout_level1, expected_layout_level2, expected_layout_level3, ] backend = FakeTokyo() result = transpile(qc, backend, optimization_level=level, seed_transpiler=42) self.assertEqual(result._layout.initial_layout._p2v, expected_layouts[level]) @data(0, 1, 2, 3) def test_layout_tokyo_fully_connected_cx(self, level): """Test that final layout in tokyo in a fully connected circuit""" qr = QuantumRegister(5, "qr") qc = QuantumCircuit(qr) for qubit_target in qr: for qubit_control in qr: if qubit_control != qubit_target: qc.cx(qubit_control, qubit_target) ancilla = QuantumRegister(15, "ancilla") trivial_layout = { 0: qr[0], 1: qr[1], 2: qr[2], 3: qr[3], 4: qr[4], 5: ancilla[0], 6: ancilla[1], 7: ancilla[2], 8: ancilla[3], 9: ancilla[4], 10: ancilla[5], 11: ancilla[6], 12: ancilla[7], 13: ancilla[8], 14: ancilla[9], 15: ancilla[10], 16: ancilla[11], 17: ancilla[12], 18: ancilla[13], 19: ancilla[14], } sabre_layout = { 0: ancilla[0], 1: qr[4], 2: ancilla[1], 3: ancilla[2], 4: ancilla[3], 5: qr[1], 6: qr[0], 7: ancilla[4], 8: ancilla[5], 9: ancilla[6], 10: qr[2], 11: qr[3], 12: ancilla[7], 13: ancilla[8], 14: ancilla[9], 15: ancilla[10], 16: ancilla[11], 17: ancilla[12], 18: ancilla[13], 19: ancilla[14], } sabre_layout_lvl_2 = { 0: ancilla[0], 1: qr[4], 2: ancilla[1], 3: ancilla[2], 4: ancilla[3], 5: qr[1], 6: qr[0], 7: ancilla[4], 8: ancilla[5], 9: ancilla[6], 10: qr[2], 11: qr[3], 12: ancilla[7], 13: ancilla[8], 14: ancilla[9], 15: ancilla[10], 16: ancilla[11], 17: ancilla[12], 18: ancilla[13], 19: ancilla[14], } sabre_layout_lvl_3 = { 0: ancilla[0], 1: qr[4], 2: ancilla[1], 3: ancilla[2], 4: ancilla[3], 5: qr[1], 6: qr[0], 7: ancilla[4], 8: ancilla[5], 9: ancilla[6], 10: qr[2], 11: qr[3], 12: ancilla[7], 13: ancilla[8], 14: ancilla[9], 15: ancilla[10], 16: ancilla[11], 17: ancilla[12], 18: ancilla[13], 19: ancilla[14], } expected_layout_level0 = trivial_layout expected_layout_level1 = sabre_layout expected_layout_level2 = sabre_layout_lvl_2 expected_layout_level3 = sabre_layout_lvl_3 expected_layouts = [ expected_layout_level0, expected_layout_level1, expected_layout_level2, expected_layout_level3, ] backend = FakeTokyo() result = transpile(qc, backend, optimization_level=level, seed_transpiler=42) self.assertEqual(result._layout.initial_layout._p2v, expected_layouts[level]) @data(0, 1, 2, 3) def test_all_levels_use_trivial_if_perfect(self, level): """Test that we always use trivial if it's a perfect match. See: https://github.com/Qiskit/qiskit-terra/issues/5694 for more details """ backend = FakeTokyo() config = backend.configuration() rows = [x[0] for x in config.coupling_map] cols = [x[1] for x in config.coupling_map] adjacency_matrix = np.zeros((20, 20)) adjacency_matrix[rows, cols] = 1 qc = GraphState(adjacency_matrix) qc.measure_all() expected = { 0: Qubit(QuantumRegister(20, "q"), 0), 1: Qubit(QuantumRegister(20, "q"), 1), 2: Qubit(QuantumRegister(20, "q"), 2), 3: Qubit(QuantumRegister(20, "q"), 3), 4: Qubit(QuantumRegister(20, "q"), 4), 5: Qubit(QuantumRegister(20, "q"), 5), 6: Qubit(QuantumRegister(20, "q"), 6), 7: Qubit(QuantumRegister(20, "q"), 7), 8: Qubit(QuantumRegister(20, "q"), 8), 9: Qubit(QuantumRegister(20, "q"), 9), 10: Qubit(QuantumRegister(20, "q"), 10), 11: Qubit(QuantumRegister(20, "q"), 11), 12: Qubit(QuantumRegister(20, "q"), 12), 13: Qubit(QuantumRegister(20, "q"), 13), 14: Qubit(QuantumRegister(20, "q"), 14), 15: Qubit(QuantumRegister(20, "q"), 15), 16: Qubit(QuantumRegister(20, "q"), 16), 17: Qubit(QuantumRegister(20, "q"), 17), 18: Qubit(QuantumRegister(20, "q"), 18), 19: Qubit(QuantumRegister(20, "q"), 19), } trans_qc = transpile(qc, backend, optimization_level=level, seed_transpiler=42) self.assertEqual(trans_qc._layout.initial_layout._p2v, expected) @data(0) def test_trivial_layout(self, level): """Test that trivial layout is preferred in level 0 See: https://github.com/Qiskit/qiskit-terra/pull/3657#pullrequestreview-342012465 """ qr = QuantumRegister(10, "qr") qc = QuantumCircuit(qr) qc.cx(qr[0], qr[1]) qc.cx(qr[1], qr[2]) qc.cx(qr[2], qr[6]) qc.cx(qr[3], qr[8]) qc.cx(qr[4], qr[9]) qc.cx(qr[9], qr[8]) qc.cx(qr[8], qr[7]) qc.cx(qr[7], qr[6]) qc.cx(qr[6], qr[5]) qc.cx(qr[5], qr[0]) ancilla = QuantumRegister(10, "ancilla") trivial_layout = { 0: qr[0], 1: qr[1], 2: qr[2], 3: qr[3], 4: qr[4], 5: qr[5], 6: qr[6], 7: qr[7], 8: qr[8], 9: qr[9], 10: ancilla[0], 11: ancilla[1], 12: ancilla[2], 13: ancilla[3], 14: ancilla[4], 15: ancilla[5], 16: ancilla[6], 17: ancilla[7], 18: ancilla[8], 19: ancilla[9], } expected_layouts = [trivial_layout, trivial_layout] backend = FakeTokyo() result = transpile(qc, backend, optimization_level=level, seed_transpiler=42) self.assertEqual(result._layout.initial_layout._p2v, expected_layouts[level]) @data(0, 1, 2, 3) def test_initial_layout(self, level): """When a user provides a layout (initial_layout), it should be used.""" qr = QuantumRegister(10, "qr") qc = QuantumCircuit(qr) qc.cx(qr[0], qr[1]) qc.cx(qr[1], qr[2]) qc.cx(qr[2], qr[3]) qc.cx(qr[3], qr[9]) qc.cx(qr[4], qr[9]) qc.cx(qr[9], qr[8]) qc.cx(qr[8], qr[7]) qc.cx(qr[7], qr[6]) qc.cx(qr[6], qr[5]) qc.cx(qr[5], qr[0]) initial_layout = { 0: qr[0], 2: qr[1], 4: qr[2], 6: qr[3], 8: qr[4], 10: qr[5], 12: qr[6], 14: qr[7], 16: qr[8], 18: qr[9], } backend = FakeTokyo() result = transpile( qc, backend, optimization_level=level, initial_layout=initial_layout, seed_transpiler=42 ) for physical, virtual in initial_layout.items(): self.assertEqual(result._layout.initial_layout._p2v[physical], virtual) @ddt class TestTranspileLevelsSwap(QiskitTestCase): """Test if swap is in the basis, do not unroll See https://github.com/Qiskit/qiskit-terra/pull/3963 The circuit in combine should require a swap and that swap should exit at the end for the transpilation""" @combine( circuit=[circuit_2532], level=[0, 1, 2, 3], dsc="circuit: {circuit.__name__}, level: {level}", name="{circuit.__name__}_level{level}", ) def test_1(self, circuit, level): """Simple coupling map (linear 5 qubits).""" basis = ["u1", "u2", "cx", "swap"] coupling_map = CouplingMap([(0, 1), (1, 2), (2, 3), (3, 4)]) result = transpile( circuit(), optimization_level=level, basis_gates=basis, coupling_map=coupling_map, seed_transpiler=42, initial_layout=[0, 1, 2, 3, 4], ) self.assertIsInstance(result, QuantumCircuit) resulting_basis = {node.name for node in circuit_to_dag(result).op_nodes()} self.assertIn("swap", resulting_basis) # Skipping optimization level 3 because the swap gates get absorbed into # a unitary block as part of the KAK decompostion optimization passes and # optimized away. @combine( level=[0, 1, 2], dsc="If swap in basis, do not decompose it. level: {level}", name="level{level}", ) def test_2(self, level): """Simple coupling map (linear 5 qubits). The circuit requires a swap and that swap should exit at the end for the transpilation""" basis = ["u1", "u2", "cx", "swap"] circuit = QuantumCircuit(5) circuit.cx(0, 4) circuit.cx(1, 4) circuit.cx(2, 4) circuit.cx(3, 4) coupling_map = CouplingMap([(0, 1), (1, 2), (2, 3), (3, 4)]) result = transpile( circuit, optimization_level=level, basis_gates=basis, coupling_map=coupling_map, seed_transpiler=421234242, ) self.assertIsInstance(result, QuantumCircuit) resulting_basis = {node.name for node in circuit_to_dag(result).op_nodes()} self.assertIn("swap", resulting_basis) @ddt class TestOptimizationWithCondition(QiskitTestCase): """Test optimization levels with condition in the circuit""" @data(0, 1, 2, 3) def test_optimization_condition(self, level): """Test optimization levels with condition in the circuit""" qr = QuantumRegister(2) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.cx(0, 1).c_if(cr, 1) backend = FakeJohannesburg() circ = transpile(qc, backend, optimization_level=level) self.assertIsInstance(circ, QuantumCircuit) def test_input_dag_copy(self): """Test substitute_node_with_dag input_dag copy on condition""" qc = QuantumCircuit(2, 1) qc.cx(0, 1).c_if(qc.cregs[0], 1) qc.cx(1, 0) circ = transpile(qc, basis_gates=["u3", "cz"]) self.assertIsInstance(circ, QuantumCircuit) @ddt class TestOptimizationOnSize(QiskitTestCase): """Test the optimization levels for optimization based on both size and depth of the circuit. See https://github.com/Qiskit/qiskit-terra/pull/7542 """ @data(2, 3) def test_size_optimization(self, level): """Test the levels for optimization based on size of circuit""" qc = QuantumCircuit(8) qc.cx(1, 2) qc.cx(2, 3) qc.cx(5, 4) qc.cx(6, 5) qc.cx(4, 5) qc.cx(3, 4) qc.cx(5, 6) qc.cx(5, 4) qc.cx(3, 4) qc.cx(2, 3) qc.cx(1, 2) qc.cx(6, 7) qc.cx(6, 5) qc.cx(5, 4) qc.cx(7, 6) qc.cx(6, 7) circ = transpile(qc, optimization_level=level).decompose() circ_data = circ.data free_qubits = {0, 1, 2, 3} # ensure no gates are using qubits - [0,1,2,3] for gate in circ_data: indices = {circ.find_bit(qubit).index for qubit in gate.qubits} common = indices.intersection(free_qubits) for common_qubit in common: self.assertTrue(common_qubit not in free_qubits) self.assertLess(circ.size(), qc.size()) self.assertLessEqual(circ.depth(), qc.depth()) @ddt class TestGeenratePresetPassManagers(QiskitTestCase): """Test generate_preset_pass_manager function.""" @data(0, 1, 2, 3) def test_with_backend(self, optimization_level): """Test a passmanager is constructed when only a backend and optimization level.""" target = FakeTokyo() pm = generate_preset_pass_manager(optimization_level, target) self.assertIsInstance(pm, PassManager) @data(0, 1, 2, 3) def test_with_no_backend(self, optimization_level): """Test a passmanager is constructed with no backend and optimization level.""" target = FakeLagosV2() pm = generate_preset_pass_manager( optimization_level, coupling_map=target.coupling_map, basis_gates=target.operation_names, inst_map=target.instruction_schedule_map, instruction_durations=target.instruction_durations, timing_constraints=target.target.timing_constraints(), target=target.target, ) self.assertIsInstance(pm, PassManager) @data(0, 1, 2, 3) def test_with_no_backend_only_target(self, optimization_level): """Test a passmanager is constructed with a manual target and optimization level.""" target = FakeLagosV2() pm = generate_preset_pass_manager(optimization_level, target=target.target) self.assertIsInstance(pm, PassManager) def test_invalid_optimization_level(self): """Assert we fail with an invalid optimization_level.""" with self.assertRaises(ValueError): generate_preset_pass_manager(42) @unittest.mock.patch.object( level2.PassManagerStagePluginManager, "get_passmanager_stage", wraps=mock_get_passmanager_stage, ) def test_backend_with_custom_stages_level2(self, _plugin_manager_mock): """Test generated preset pass manager includes backend specific custom stages.""" optimization_level = 2 class TargetBackend(FakeLagosV2): """Fake lagos subclass with custom transpiler stages.""" def get_scheduling_stage_plugin(self): """Custom scheduling stage.""" return "custom_stage_for_test" def get_translation_stage_plugin(self): """Custom post translation stage.""" return "custom_stage_for_test" target = TargetBackend() pm = generate_preset_pass_manager(optimization_level, backend=target) self.assertIsInstance(pm, PassManager) pass_list = [y.__class__.__name__ for x in pm.passes() for y in x["passes"]] self.assertIn("PadDynamicalDecoupling", pass_list) self.assertIn("ALAPScheduleAnalysis", pass_list) post_translation_pass_list = [ y.__class__.__name__ for x in pm.translation.passes() # pylint: disable=no-member for y in x["passes"] ] self.assertIn("RemoveResetInZeroState", post_translation_pass_list) @unittest.mock.patch.object( level1.PassManagerStagePluginManager, "get_passmanager_stage", wraps=mock_get_passmanager_stage, ) def test_backend_with_custom_stages_level1(self, _plugin_manager_mock): """Test generated preset pass manager includes backend specific custom stages.""" optimization_level = 1 class TargetBackend(FakeLagosV2): """Fake lagos subclass with custom transpiler stages.""" def get_scheduling_stage_plugin(self): """Custom scheduling stage.""" return "custom_stage_for_test" def get_translation_stage_plugin(self): """Custom post translation stage.""" return "custom_stage_for_test" target = TargetBackend() pm = generate_preset_pass_manager(optimization_level, backend=target) self.assertIsInstance(pm, PassManager) pass_list = [y.__class__.__name__ for x in pm.passes() for y in x["passes"]] self.assertIn("PadDynamicalDecoupling", pass_list) self.assertIn("ALAPScheduleAnalysis", pass_list) post_translation_pass_list = [ y.__class__.__name__ for x in pm.translation.passes() # pylint: disable=no-member for y in x["passes"] ] self.assertIn("RemoveResetInZeroState", post_translation_pass_list) @unittest.mock.patch.object( level3.PassManagerStagePluginManager, "get_passmanager_stage", wraps=mock_get_passmanager_stage, ) def test_backend_with_custom_stages_level3(self, _plugin_manager_mock): """Test generated preset pass manager includes backend specific custom stages.""" optimization_level = 3 class TargetBackend(FakeLagosV2): """Fake lagos subclass with custom transpiler stages.""" def get_scheduling_stage_plugin(self): """Custom scheduling stage.""" return "custom_stage_for_test" def get_translation_stage_plugin(self): """Custom post translation stage.""" return "custom_stage_for_test" target = TargetBackend() pm = generate_preset_pass_manager(optimization_level, backend=target) self.assertIsInstance(pm, PassManager) pass_list = [y.__class__.__name__ for x in pm.passes() for y in x["passes"]] self.assertIn("PadDynamicalDecoupling", pass_list) self.assertIn("ALAPScheduleAnalysis", pass_list) post_translation_pass_list = [ y.__class__.__name__ for x in pm.translation.passes() # pylint: disable=no-member for y in x["passes"] ] self.assertIn("RemoveResetInZeroState", post_translation_pass_list) @unittest.mock.patch.object( level0.PassManagerStagePluginManager, "get_passmanager_stage", wraps=mock_get_passmanager_stage, ) def test_backend_with_custom_stages_level0(self, _plugin_manager_mock): """Test generated preset pass manager includes backend specific custom stages.""" optimization_level = 0 class TargetBackend(FakeLagosV2): """Fake lagos subclass with custom transpiler stages.""" def get_scheduling_stage_plugin(self): """Custom scheduling stage.""" return "custom_stage_for_test" def get_translation_stage_plugin(self): """Custom post translation stage.""" return "custom_stage_for_test" target = TargetBackend() pm = generate_preset_pass_manager(optimization_level, backend=target) self.assertIsInstance(pm, PassManager) pass_list = [y.__class__.__name__ for x in pm.passes() for y in x["passes"]] self.assertIn("PadDynamicalDecoupling", pass_list) self.assertIn("ALAPScheduleAnalysis", pass_list) post_translation_pass_list = [ y.__class__.__name__ for x in pm.translation.passes() # pylint: disable=no-member for y in x["passes"] ] self.assertIn("RemoveResetInZeroState", post_translation_pass_list) @ddt class TestIntegrationControlFlow(QiskitTestCase): """Integration tests for control-flow circuits through the preset pass managers.""" @data(0, 1, 2, 3) def test_default_compilation(self, optimization_level): """Test that a simple circuit with each type of control-flow passes a full transpilation pipeline with the defaults.""" class CustomCX(Gate): """Custom CX""" def __init__(self): super().__init__("custom_cx", 2, []) def _define(self): self._definition = QuantumCircuit(2) self._definition.cx(0, 1) circuit = QuantumCircuit(6, 1) circuit.h(0) circuit.measure(0, 0) circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with circuit.for_loop((1,)): circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with else_: circuit.cx(3, 4) circuit.cz(3, 5) circuit.append(CustomCX(), [4, 5], []) with circuit.while_loop((circuit.clbits[0], True)): circuit.cx(3, 4) circuit.cz(3, 5) circuit.append(CustomCX(), [4, 5], []) coupling_map = CouplingMap.from_line(6) transpiled = transpile( circuit, basis_gates=["sx", "rz", "cx", "if_else", "for_loop", "while_loop"], coupling_map=coupling_map, optimization_level=optimization_level, seed_transpiler=2022_10_04, ) # Tests of the complete validity of a circuit are mostly done at the indiviual pass level; # here we're just checking that various passes do appear to have run. self.assertIsInstance(transpiled, QuantumCircuit) # Assert layout ran. self.assertIsNot(getattr(transpiled, "_layout", None), None) def _visit_block(circuit, stack=None): """Assert that every block contains at least one swap to imply that routing has run.""" if stack is None: # List of (instruction_index, block_index). stack = () seen_cx = 0 for i, instruction in enumerate(circuit): if isinstance(instruction.operation, ControlFlowOp): for j, block in enumerate(instruction.operation.blocks): _visit_block(block, stack + ((i, j),)) elif isinstance(instruction.operation, CXGate): seen_cx += 1 # Assert unrolling ran. self.assertNotIsInstance(instruction.operation, CustomCX) # Assert translation ran. self.assertNotIsInstance(instruction.operation, CZGate) # There are three "natural" swaps in each block (one for each 2q operation), so if # routing ran, we should see more than that. self.assertGreater(seen_cx, 3, msg=f"no swaps in block at indices: {stack}") # Assert routing ran. _visit_block(transpiled) @data(0, 1, 2, 3) def test_allow_overriding_defaults(self, optimization_level): """Test that the method options can be overridden.""" circuit = QuantumCircuit(3, 1) circuit.h(0) circuit.measure(0, 0) with circuit.for_loop((1,)): circuit.h(0) circuit.cx(0, 1) circuit.cz(0, 2) circuit.cx(1, 2) coupling_map = CouplingMap.from_line(3) calls = set() def callback(pass_, **_): calls.add(pass_.name()) transpiled = transpile( circuit, basis_gates=["u3", "cx", "if_else", "for_loop", "while_loop"], layout_method="trivial", translation_method="unroller", coupling_map=coupling_map, optimization_level=optimization_level, seed_transpiler=2022_10_04, callback=callback, ) self.assertIsInstance(transpiled, QuantumCircuit) self.assertIsNot(getattr(transpiled, "_layout", None), None) self.assertIn("TrivialLayout", calls) self.assertIn("Unroller", calls) self.assertNotIn("DenseLayout", calls) self.assertNotIn("SabreLayout", calls) self.assertNotIn("BasisTranslator", calls) @data(0, 1, 2, 3) def test_invalid_methods_raise_on_control_flow(self, optimization_level): """Test that trying to use an invalid method with control flow fails.""" qc = QuantumCircuit(1) with qc.for_loop((1,)): qc.x(0) with self.assertRaisesRegex(TranspilerError, "Got routing_method="): transpile(qc, routing_method="lookahead", optimization_level=optimization_level) with self.assertRaisesRegex(TranspilerError, "Got scheduling_method="): transpile(qc, scheduling_method="alap", optimization_level=optimization_level) @data(0, 1, 2, 3) def test_unsupported_basis_gates_raise(self, optimization_level): """Test that trying to transpile a control-flow circuit for a backend that doesn't support the necessary operations in its `basis_gates` will raise a sensible error.""" backend = FakeTokyo() qc = QuantumCircuit(1, 1) with qc.for_loop((0,)): pass with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"): transpile(qc, backend, optimization_level=optimization_level) qc = QuantumCircuit(1, 1) with qc.if_test((qc.clbits[0], False)): pass with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"): transpile(qc, backend, optimization_level=optimization_level) qc = QuantumCircuit(1, 1) with qc.while_loop((qc.clbits[0], False)): pass with qc.for_loop((0, 1, 2)): pass with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"): transpile(qc, backend, optimization_level=optimization_level) @data(0, 1, 2, 3) def test_unsupported_targets_raise(self, optimization_level): """Test that trying to transpile a control-flow circuit for a backend that doesn't support the necessary operations in its `Target` will raise a more sensible error.""" target = Target(num_qubits=2) target.add_instruction(CXGate(), {(0, 1): None}) qc = QuantumCircuit(1, 1) with qc.for_loop((0,)): pass with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"): transpile(qc, target=target, optimization_level=optimization_level) qc = QuantumCircuit(1, 1) with qc.if_test((qc.clbits[0], False)): pass with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"): transpile(qc, target=target, optimization_level=optimization_level) qc = QuantumCircuit(1, 1) with qc.while_loop((qc.clbits[0], False)): pass with qc.for_loop((0, 1, 2)): pass with self.assertRaisesRegex(TranspilerError, "The control-flow construct.*not supported"): transpile(qc, target=target, optimization_level=optimization_level)
https://github.com/acfilok96/Quantum-Computation
acfilok96
import qiskit from qiskit import * print(qiskit.__version__) %matplotlib inline from qiskit.tools.visualization import plot_histogram secret_number = '101001' # here work is happen like buttom to up for position,value in enumerate(reversed(secret_number)): if value == '1': print(position, value) circuit = QuantumCircuit(6+1, 6) circuit.h([0,1,2,3,4,5]) circuit.x(6) circuit.h(6) circuit.barrier() circuit.draw(output='mpl') circuit.cx(5, 6) circuit.cx(3, 6) circuit.cx(0, 6) circuit.barrier() circuit.draw(output='mpl') circuit.h([0,1,2,3,4,5]) circuit.draw(output='mpl') circuit.barrier() circuit.measure([i for i in range(5)],[i for i in range(5)]) circuit.barrier() circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, backend=simulator, shots=1) result = job.result() counts = result.get_counts() print(counts) circuit = QuantumCircuit(len(secret_number)+1, len(secret_number)) circuit.h(range(len(secret_number))) circuit.x(len(secret_number)) circuit.h(len(secret_number)) circuit.barrier() for position,value in enumerate(reversed(secret_number)): if value == '1': circuit.cx(position, len(secret_number)) circuit.barrier() circuit.h(range(len(secret_number))) circuit.barrier() circuit.measure(range(len(secret_number)), range(len(secret_number))) circuit.barrier() circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, backend=simulator, shots=1) result = job.result() counts = result.get_counts() print(counts) def find_secret_number(secter_number): secret_number = str(secter_number) # Using Bernstein Vazirani Algorithm circuit = QuantumCircuit(len(secret_number)+1, len(secret_number)) circuit.h(range(len(secret_number))) circuit.x(len(secret_number)) circuit.h(len(secret_number)) circuit.barrier() for position,value in enumerate(reversed(secret_number)): if value == '1': circuit.cx(position, len(secret_number)) circuit.barrier() circuit.h(range(len(secret_number))) circuit.barrier() circuit.measure(range(len(secret_number)), range(len(secret_number))) circuit.barrier() circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, backend=simulator, shots=1) result = job.result() counts = result.get_counts() print(counts) secret_number = int(input("enter number(digits should be 0 or 1): ")) find_secret_number(secret_number)
https://github.com/tybens/quantum-data-fitting-HHL
tybens
import numpy as np from qiskit import ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram F = np.matrix([[1, 1, 1], [0, 0, 1], [1, 0, 0], [0.5, 1, 0]]) print("rank", np.linalg.matrix_rank(F)) y = np.array([0, 0, 1, 0]) y.resize((4, 1)) print("F=", F) print("y=", y) A = F.getH() * F A = np.pad(A, ((0, 1), (0, 1))) A[-1][-1] = 1 b = F.getH() * y b = np.vstack((b, [0])) from qiskit.algorithms.linear_solvers.hhl import HHL backend = Aer.get_backend('aer_simulator') hhl = HHL(quantum_instance=backend) accurate_solution = hhl.solve(A, b) nShots = 10000 c = ClassicalRegister(2, 'c') qc = QuantumCircuit(c) lambda_circ = accurate_solution.state lambda_circ = lambda_circ.compose(qc) lambda_circ.measure(range(2), c) backend_qasm = Aer.get_backend('qasm_simulator') res = execute(lambda_circ, backend_qasm, shots=nShots).result() counts = res.get_counts() plot_histogram(counts)