repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
MonitSharma
from PIL import Image import numpy as np import matplotlib.pyplot as plt cut=128 img = Image.open('nasa_image.jpg').convert('L') plt.imshow(img) img = np.asarray(img.getdata()).reshape((2463,2895)) for i in range(2463//cut): for j in range(2895//cut): cutimg = img[i*cut:(i+1)*cut] cutimg = cutimg[:,list(range(j*cut,(j+1)*cut))] plt.imsave('result/{} {}.jpg'.format(i,j), cutimg ,cmap='gray') for i in range(2463//cut): for j in range(2895//cut): img16 = Image.open('result/{} {}.jpg'.format(i,j)).resize((16,16)).convert('L') img16 = np.asarray(img16.getdata()).reshape((16,16)) img16 = Image.open('result/{} {}.jpg'.format(5,1)).resize((16,16)).convert('L') plt.imshow(img16, cmap='gray') img16 = np.asarray(img16.getdata(), dtype=np.float64).reshape((16,16)) import random import numpy as np import matplotlib.pyplot as plt import sys sys.path.append('../PyFiles') # where the Helper files are saved # Pull in the helper files. from ImageRead import * # the helper files we created to read Images from QNN import * # the helper file that creates the QNN target_o = [1 for i in range(25)]+[0 for i in range(25)] pathY=r'../dataset/Original/galaxy/' pathN=r'../dataset/Original/No-galaxy/' nameN='' nameY='' inputY=[imageResize(callImage(i+1,pathY,nameY),16) for i in range(25)] inputN=[imageResize(callImage(i+1,pathN,nameN),16) for i in range(25)] input_combine = inputY+inputN np.random.seed(0) idx=np.array([int(i) for i in range(50)]).flatten() np.random.shuffle(idx) dataInput = list(input_combine[i] for i in idx ) dataTarget = list( imageBinarize(input_combine[i]) for i in idx ) data_target_o=list( target_o[i] for i in idx ) n_samples_show = 10 fig, axes = plt.subplots(nrows=2, ncols=n_samples_show, figsize=(20, 6)) for i in range(n_samples_show): axes[0,i].imshow(dataInput[i], cmap='gray') axes[0,i].set_xticks([]) axes[0,i].set_yticks([]) axes[1,i].imshow(dataInput[i+5], cmap='gray') axes[1,i].set_xticks([]) axes[1,i].set_yticks([]) from qiskit.circuit.parameter import Parameter from qiskit_machine_learning.neural_networks import CircuitQNN from qiskit_machine_learning.connectors import TorchConnector from qiskit.utils import QuantumInstance from torch.nn import Linear, CrossEntropyLoss, MSELoss from torch.optim import LBFGS, SGD,Adam qi = QuantumInstance(Aer.get_backend('statevector_simulator')) from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B # Model for LBFGS # Combining the circuit together with CircuitQNN np.random.seed(3) nqubits=6 num_inputs=256 qc = QuantumCircuit(nqubits) # Encoding param_x=[]; for i in range(num_inputs): param_x.append(Parameter('x'+str(i))) for i in range(8): param_x.append(np.pi/2) feature_map = encoding(qc,param_x,22) # Optimzing circuit PQC param_y=[]; for i in range(nqubits*2): param_y.append(Parameter('θ'+str(i))) ansatz=circuit15(qc,param_y) qc.append(feature_map, range(nqubits)) qc.append(ansatz, range(nqubits)) qnn2 = CircuitQNN(qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=2, quantum_instance=qi) initial_weights = 0.1*(2*np.random.rand(qnn2.num_weights) - 1) # define optimizer and loss function model2 = TorchConnector(qnn2, initial_weights) optimizer = LBFGS(model2.parameters(),lr=0.05) f_loss = CrossEntropyLoss() X= [normlaizeData(dataInput[i].flatten()) for i in range(50)] y01= [data_target_o[i] for i in range(50)] from torch import Tensor # traning model accuracy y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01))) # define optimizer and loss function model2 = TorchConnector(qnn2, initial_weights) optimizer = LBFGS(model2.parameters(),lr=0.05) f_loss = CrossEntropyLoss() X= [normlaizeData(dataInput[i].flatten()) for i in range(50)] y01= [data_target_o[i] for i in range(50)] from torch import Tensor # start training model2.train() # set model to training mode # define objective function def closure(): optimizer.zero_grad() # initialize gradient loss = 0.0 # initialize loss for x, y_target in zip(X, y01): # evaluate batch loss output = model2(Tensor(x)).reshape(1, 2) # forward pass loss += f_loss(output, Tensor([y_target]).long()) loss.backward() # backward pass print(loss.item()) # print loss return loss # run optimizer optimizer.step(closure) optimizer.step(closure) # traning model accuracy y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01))) # define optimizer and loss function from torch import Tensor model2 = TorchConnector(qnn2, initial_weights) optimizer = LBFGS(model2.parameters(),lr=0.06) f_loss = CrossEntropyLoss() X= [normlaizeData(dataInput[i].flatten()) for i in range(50)] y01= [data_target_o[i] for i in range(50)] y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01))) from torch import Tensor # start training model2.train() # set model to training mode # define objective function def closure(): optimizer.zero_grad() # initialize gradient loss = 0.0 # initialize loss for x, y_target in zip(X, y01): # evaluate batch loss output = model2(Tensor(x)).reshape(1, 2) # forward pass loss += f_loss(output, Tensor([y_target]).long()) loss.backward() # backward pass print(loss.item()) # print loss return loss # run optimizer optimizer.step(closure) optimizer.step(closure) # traning model accuracy y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01))) # define optimizer and loss function from torch import Tensor model2 = TorchConnector(qnn2, initial_weights) optimizer = LBFGS(model2.parameters(),lr=0.07) f_loss = CrossEntropyLoss() X= [normlaizeData(dataInput[i].flatten()) for i in range(50)] y01= [data_target_o[i] for i in range(50)] y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01))) from torch import Tensor # start training model2.train() # set model to training mode # define objective function def closure(): optimizer.zero_grad() # initialize gradient loss = 0.0 # initialize loss for x, y_target in zip(X, y01): # evaluate batch loss output = model2(Tensor(x)).reshape(1, 2) # forward pass loss += f_loss(output, Tensor([y_target]).long()) loss.backward() # backward pass print(loss.item()) # print loss return loss # run optimizer optimizer.step(closure) optimizer.step(closure) # traning model accuracy y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01))) target_o = [1 for i in range(25)]+[0 for i in range(25)] pathY=r'../dataset/Original/galaxy1/' pathN=r'../dataset/Original/no-galaxy1/' nameN='' nameY='' inputY=[imageResize(callImage(i+1,pathY,nameY),16) for i in range(25)] inputN=[imageResize(callImage(i+1,pathN,nameN),16) for i in range(25)] input_combine = inputY+inputN np.random.seed(0) idx=np.array([int(i) for i in range(50)]).flatten() np.random.shuffle(idx) dataInput = list(input_combine[i] for i in idx ) dataTarget = list( imageBinarize(input_combine[i]) for i in idx ) data_target_o=list( target_o[i] for i in idx ) Xtest= [normlaizeData(dataInput[i].flatten()) for i in range(25)] y01test= [data_target_o[i] for i in range(25)] Xtest1= [normlaizeData(dataInput[i].flatten()) for i in range(50)] y01test1= [data_target_o[i] for i in range(50)] y_predict = [] for x in Xtest: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print('Accuracy25data:', sum(y_predict == np.array(y01test))/len(np.array(y01test))) y_predict1 = [] for x in Xtest1: output = model2(Tensor(x)) y_predict1 += [np.argmax(output.detach().numpy())] print('Accuracy50data:', sum(y_predict1 == np.array(y01test1))/len(np.array(y01test1)))
https://github.com/RevanthK/ShorsAlgorithmIBMQiskit
RevanthK
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute, Aer from qiskit.tools.jupyter import * provider = IBMQ.load_account() # import basic plot tools from qiskit.visualization import plot_histogram def initialize(circuit, n, m): circuit.h(range(n)) # Hadamard transform on measurment register circuit.x(n+m-1) # X gate on last qubit def c_amod15(a, x): if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") # remember that a needs to be co-prime with N unitary = QuantumCircuit(4) for iteration in range(x): # bitwise arithmetic to represent modular exponentiation function if a in [2,13]: unitary.swap(0,1) unitary.swap(1,2) unitary.swap(2,3) if a in [7,8]: unitary.swap(2,3) unitary.swap(1,2) unitary.swap(0,1) if a == 11: unitary.swap(1,3) unitary.swap(0,2) if a in [7,11,13]: for q in range(4): unitary.x(q) unitary = unitary.to_gate() unitary.name = "%i^%i mod 15" % (a, x) # But we need to make it a controlled operation for phase kickback c_unitary = unitary.control() return c_unitary def modular_exponentiation(circuit, n, m, a): for exp in range(n): exponent = 2**exp circuit.append(a_x_mod15(a, exponent), [exp] + list(range(n, n+m))) from qiskit.circuit.library import QFT def apply_iqft(circuit, measurement_qubits): circuit.append(QFT( len(measurement_qubits), do_swaps=False).inverse(), measurement_qubits) def shor_algo(n, m, a): # set up the circuit circ = QuantumCircuit(n+m, n) # initialize the registers initialize(circ, n, m) circ.barrier() # map modular exponentiation problem onto qubits modular_exponentiation(circ, n, m, a) circ.barrier() # apply inverse QFT -- expose period apply_iqft(circ, range(n)) # measure the measurement register circ.measure(range(n), range(n)) return circ n = 4; m = 4; a = 11 mycircuit = shor_algo(n, m, a) mycircuit.draw('mpl') simulator = Aer.get_backend('qasm_simulator') counts = execute(mycircuit, backend=simulator, shots=1024).result().get_counts(mycircuit) plot_histogram(counts) for measured_value in counts: print(f"Measured {int(measured_value[::-1], 2)}") from math import gcd from math import sqrt from itertools import count, islice for measured_value in counts: measured_value_decimal = int(measured_value[::-1], 2) print(f"Measured {measured_value_decimal}") if measured_value_decimal % 2 != 0: print("Failed. Measured value is not an even number") continue x = int((a ** (measured_value_decimal/2)) % 15) if (x + 1) % 15 == 0: print("Failed. x + 1 = 0 (mod N) where x = a^(r/2) (mod N)") continue guesses = gcd(x + 1, 15), gcd(x - 1, 15) print(guesses) def is_prime(n): return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n)-1))) if is_prime(guesses[0]) and is_prime(guesses[1]): print(f"**The prime factors are {guesses[0]} and {guesses[1]}**")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.visualization.timeline import draw as timeline_draw from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") timeline_draw(circ)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # Copyright 2019, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """Helper class used to convert a pulse instruction into PulseQobjInstruction.""" import re import math import warnings from sympy.parsing.sympy_parser import (parse_expr, standard_transformations, implicit_multiplication_application, function_exponentiation) from sympy import Symbol from qiskit.pulse import commands, channels, Schedule from qiskit.pulse.schedule import ParameterizedSchedule from qiskit.pulse.exceptions import PulseError from qiskit.qobj import QobjMeasurementOption from qiskit import QiskitError class ConversionMethodBinder: """Conversion method registrar.""" def __init__(self): """Acts as method registration decorator and tracker for conversion methods.""" self._bound_instructions = {} def __call__(self, bound): """ Converter decorator method. Converter is defined for object to be converted matched on hash Args: bound (Hashable): Hashable object to bind to the converter. """ # pylint: disable=missing-return-doc, missing-return-type-doc def _apply_converter(converter): """Return decorated converter function.""" # Track conversion methods for class. self._bound_instructions[bound] = converter return converter return _apply_converter def get_bound_method(self, bound): """Get conversion method for bound object.""" try: return self._bound_instructions[bound] except KeyError: raise PulseError('Bound method for %s is not found.' % bound) class InstructionToQobjConverter: """Converts pulse Instructions to Qobj models. Converter is constructed with qobj model and experimental configuration, and returns proper qobj instruction to each backend. Third party providers can be add their own custom pulse instructions by providing custom converter methods. To create a custom converter for custom instruction ``` class CustomConverter(InstructionToQobjConverter): @bind_instruction(CustomInstruction) def convert_custom_command(self, shift, instruction): command_dict = { 'name': 'custom_command', 't0': shift+instruction.start_time, 'param1': instruction.param1, 'param2': instruction.param2 } if self._run_config('option1', True): command_dict.update({ 'param3': instruction.param3 }) return self.qobj_model(**command_dict) ``` """ # class level tracking of conversion methods bind_instruction = ConversionMethodBinder() def __init__(self, qobj_model, **run_config): """Create new converter. Args: qobj_model (QobjInstruction): marshmallow model to serialize to object. run_config (dict): experimental configuration. """ self._qobj_model = qobj_model self._run_config = run_config def __call__(self, shift, instruction): method = self.bind_instruction.get_bound_method(type(instruction)) return method(self, shift, instruction) @bind_instruction(commands.AcquireInstruction) def convert_acquire(self, shift, instruction): """Return converted `AcquireInstruction`. Args: shift(int): Offset time. instruction (AcquireInstruction): acquire instruction. Returns: dict: Dictionary of required parameters. """ meas_level = self._run_config.get('meas_level', 2) command_dict = { 'name': 'acquire', 't0': shift+instruction.start_time, 'duration': instruction.duration, 'qubits': [q.index for q in instruction.acquires], 'memory_slot': [m.index for m in instruction.mem_slots] } if meas_level == 2: # setup discriminators if instruction.command.discriminator: command_dict.update({ 'discriminators': [ QobjMeasurementOption( name=instruction.command.discriminator.name, params=instruction.command.discriminator.params) ] }) # setup register_slots if instruction.reg_slots: command_dict.update({ 'register_slot': [regs.index for regs in instruction.reg_slots] }) if meas_level >= 1: # setup kernels if instruction.command.kernel: command_dict.update({ 'kernels': [ QobjMeasurementOption( name=instruction.command.kernel.name, params=instruction.command.kernel.params) ] }) return self._qobj_model(**command_dict) @bind_instruction(commands.FrameChangeInstruction) def convert_frame_change(self, shift, instruction): """Return converted `FrameChangeInstruction`. Args: shift(int): Offset time. instruction (FrameChangeInstruction): frame change instruction. Returns: dict: Dictionary of required parameters. """ command_dict = { 'name': 'fc', 't0': shift+instruction.start_time, 'ch': instruction.channels[0].name, 'phase': instruction.command.phase } return self._qobj_model(**command_dict) @bind_instruction(commands.PersistentValueInstruction) def convert_persistent_value(self, shift, instruction): """Return converted `PersistentValueInstruction`. Args: shift(int): Offset time. instruction (PersistentValueInstruction): persistent value instruction. Returns: dict: Dictionary of required parameters. """ command_dict = { 'name': 'pv', 't0': shift+instruction.start_time, 'ch': instruction.channels[0].name, 'val': instruction.command.value } return self._qobj_model(**command_dict) @bind_instruction(commands.PulseInstruction) def convert_drive(self, shift, instruction): """Return converted `PulseInstruction`. Args: shift(int): Offset time. instruction (PulseInstruction): drive instruction. Returns: dict: Dictionary of required parameters. """ command_dict = { 'name': instruction.command.name, 't0': shift+instruction.start_time, 'ch': instruction.channels[0].name } return self._qobj_model(**command_dict) @bind_instruction(commands.Snapshot) def convert_snapshot(self, shift, instruction): """Return converted `Snapshot`. Args: shift(int): Offset time. instruction (Snapshot): snapshot instruction. Returns: dict: Dictionary of required parameters. """ command_dict = { 'name': 'snapshot', 't0': shift+instruction.start_time, 'label': instruction.name, 'type': instruction.type } return self._qobj_model(**command_dict) # pylint: disable=invalid-name # get math operations valid in python. Presumably these are valid in sympy _math_ops = [math_op for math_op in math.__dict__ if not math_op.startswith('__')] # only allow valid math ops _math_ops_regex = r"(" + ")|(".join(_math_ops) + ")" # match consecutive alphanumeric, and single consecutive math ops +-/.() # and multiple * for exponentiation _allowedchars = re.compile(r'(([+\/\-]?|\*{0,2})?[\(\)\s]*' # allow to start with math/bracket r'([a-zA-Z][a-zA-Z\d]*|' # match word r'[\d]+(\.\d*)?)[\(\)\s]*)*') # match decimal and bracket # match any sequence of chars and numbers _expr_regex = r'([a-zA-Z]+\d*)' # and valid params _param_regex = r'(P\d+)' # only valid sequences are P# for parameters and valid math operations above _valid_sub_expr = re.compile(_param_regex+'|'+_math_ops_regex) # pylint: enable=invalid-name def _is_math_expr_safe(expr): r"""Verify mathematical expression is sanitized. Only allow strings of form 'P\d+' and operations from `math`. Allowed chars are [a-zA-Z]. Allowed math operators are '+*/().' where only '*' are allowed to be consecutive. Args: expr (str): Expression to sanitize Returns: bool: Whether the string is safe to parse math from Raise: QiskitError: If math expression is not sanitized """ only_allowed_chars = _allowedchars.match(expr) if not only_allowed_chars: return False elif not only_allowed_chars.group(0) == expr: return False sub_expressions = re.findall(_expr_regex, expr) if not all([_valid_sub_expr.match(sub_exp) for sub_exp in sub_expressions]): return False return True def _parse_string_expr(expr): # pylint: disable=missing-return-type-doc """Parse a mathematical string expression and extract free parameters. Args: expr (str): String expression to parse Returns: (Callable, Tuple[str]): Returns a callable function and tuple of string symbols Raises: QiskitError: If expression is not safe """ # remove these strings from expression and hope sympy knows these math expressions # these are effectively reserved keywords subs = [('numpy.', ''), ('np.', ''), ('math.', '')] for match, sub in subs: expr = expr.replace(match, sub) if not _is_math_expr_safe(expr): raise QiskitError('Expression: "%s" is not safe to evaluate.' % expr) params = sorted(re.findall(_param_regex, expr)) local_dict = {param: Symbol(param) for param in params} symbols = list(local_dict.keys()) transformations = (standard_transformations + (implicit_multiplication_application,) + (function_exponentiation,)) parsed_expr = parse_expr(expr, local_dict=local_dict, transformations=transformations) def parsed_fun(*args, **kwargs): subs = {} matched_params = [] if args: subs.update({symbols[i]: arg for i, arg in enumerate(args)}) matched_params += list(params[i] for i in range(len(args))) elif kwargs: subs.update({local_dict[key]: value for key, value in kwargs.items() if key in local_dict}) matched_params += list(key for key in kwargs if key in params) if not set(matched_params).issuperset(set(params)): raise PulseError('Supplied params ({args}, {kwargs}) do not match ' '{params}'.format(args=args, kwargs=kwargs, params=params)) return complex(parsed_expr.evalf(subs=subs)) return parsed_fun, params class QobjToInstructionConverter: """Converts Qobj models to pulse Instructions """ # pylint: disable=invalid-name,missing-return-type-doc # class level tracking of conversion methods bind_name = ConversionMethodBinder() chan_regex = re.compile(r'([a-zA-Z]+)(\d+)') def __init__(self, pulse_library, buffer=0, **run_config): """Create new converter. Args: pulse_library (List[PulseLibraryItem]): Pulse library to be used in conversion buffer (int): Channel buffer run_config (dict): experimental configuration. """ self.buffer = buffer self._run_config = run_config # bind pulses to conversion methods for pulse in pulse_library: self.bind_pulse(pulse) def __call__(self, instruction): method = self.bind_name.get_bound_method(instruction.name) return method(self, instruction) def get_channel(self, channel): """Parse and retrieve channel from ch string. Args: channel (str): Channel to match Returns: (Channel, int): Matched channel Raises: PulseError: Is raised if valid channel is not matched """ match = self.chan_regex.match(channel) if match: prefix, index = match.group(1), int(match.group(2)) if prefix == channels.DriveChannel.prefix: return channels.DriveChannel(index, buffer=self.buffer) elif prefix == channels.MeasureChannel.prefix: return channels.MeasureChannel(index, buffer=self.buffer) elif prefix == channels.ControlChannel.prefix: return channels.ControlChannel(index, buffer=self.buffer) raise PulseError('Channel %s is not valid' % channel) @bind_name('acquire') def convert_acquire(self, instruction): """Return converted `AcquireInstruction`. Args: instruction (PulseQobjInstruction): acquire qobj Returns: Schedule: Converted and scheduled Instruction """ t0 = instruction.t0 duration = instruction.duration qubits = instruction.qubits qubit_channels = [channels.AcquireChannel(qubit, buffer=self.buffer) for qubit in qubits] mem_slots = [channels.MemorySlot(instruction.memory_slot[i]) for i in range(len(qubits))] if hasattr(instruction, 'register_slot'): register_slots = [channels.RegisterSlot(instruction.register_slot[i]) for i in range(len(qubits))] else: register_slots = None discriminators = (instruction.discriminators if hasattr(instruction, 'discriminators') else None) if not isinstance(discriminators, list): discriminators = [discriminators] if any(discriminators[i] != discriminators[0] for i in range(len(discriminators))): warnings.warn("Can currently only support one discriminator per acquire. Defaulting " "to first discriminator entry.") discriminator = discriminators[0] if discriminator: discriminator = commands.Discriminator(name=discriminators[0].name, params=discriminators[0].params) kernels = (instruction.kernels if hasattr(instruction, 'kernels') else None) if not isinstance(kernels, list): kernels = [kernels] if any(kernels[0] != kernels[i] for i in range(len(kernels))): warnings.warn("Can currently only support one kernel per acquire. Defaulting to first " "kernel entry.") kernel = kernels[0] if kernel: kernel = commands.Kernel(name=kernels[0].name, params=kernels[0].params) cmd = commands.Acquire(duration, discriminator=discriminator, kernel=kernel) schedule = Schedule() schedule |= commands.AcquireInstruction(cmd, qubit_channels, mem_slots, register_slots) << t0 return schedule @bind_name('fc') def convert_frame_change(self, instruction): """Return converted `FrameChangeInstruction`. Args: instruction (PulseQobjInstruction): frame change qobj Returns: Schedule: Converted and scheduled Instruction """ t0 = instruction.t0 channel = self.get_channel(instruction.ch) phase = instruction.phase # This is parameterized if isinstance(phase, str): phase_expr, params = _parse_string_expr(phase) def gen_fc_sched(*args, **kwargs): phase = abs(phase_expr(*args, **kwargs)) return commands.FrameChange(phase)(channel) << t0 return ParameterizedSchedule(gen_fc_sched, parameters=params) return commands.FrameChange(phase)(channel) << t0 @bind_name('pv') def convert_persistent_value(self, instruction): """Return converted `PersistentValueInstruction`. Args: instruction (PulseQobjInstruction): persistent value qobj Returns: Schedule: Converted and scheduled Instruction """ t0 = instruction.t0 channel = self.get_channel(instruction.ch) val = instruction.val # This is parameterized if isinstance(val, str): val_expr, params = _parse_string_expr(val) def gen_fc_sched(*args, **kwargs): val = complex(val_expr(*args, **kwargs)) return commands.PersistentValue(val)(channel) << t0 return ParameterizedSchedule(gen_fc_sched, parameters=params) return commands.PersistentValue(val)(channel) << t0 def bind_pulse(self, pulse): """Bind the supplied pulse to a converter method by pulse name. Args: pulse (PulseLibraryItem): Pulse to bind """ # pylint: disable=unused-variable pulse = commands.SamplePulse(pulse.samples, pulse.name) @self.bind_name(pulse.name) def convert_named_drive(self, instruction): """Return converted `PulseInstruction`. Args: instruction (PulseQobjInstruction): pulse qobj Returns: Schedule: Converted and scheduled pulse """ t0 = instruction.t0 channel = self.get_channel(instruction.ch) return pulse(channel) << t0 @bind_name('snapshot') def convert_snapshot(self, instruction): """Return converted `Snapshot`. Args: instruction (PulseQobjInstruction): snapshot qobj Returns: Schedule: Converted and scheduled Snapshot """ t0 = instruction.t0 return commands.Snapshot(instruction.label, instruction.type) << t0
https://github.com/qiskit-community/qopt-best-practices
qiskit-community
# SIMULATED FAKE BACKEND from qiskit_ibm_runtime.fake_provider import FakeGuadalupe backend = FakeGuadalupe() from qiskit.visualization import plot_gate_map plot_gate_map(backend) from qopt_best_practices.qubit_selection import BackendEvaluator num_qubits = 10 path_finder = BackendEvaluator(backend) path, fidelity, num_subsets = path_finder.evaluate(num_qubits) print("Best path: ", path) print("Best path fidelity", fidelity) print("Num. evaluated paths", num_subsets) from __future__ import annotations import numpy as np import rustworkx as rx from qiskit.transpiler import CouplingMap def find_lines(length: int, backend, coupling_map: CouplingMap | None = None) -> list[int]: """Finds all possible lines of length `length` for a specific backend topology. This method can take quite some time to run on large devices since there are many paths. Returns: The found paths. """ # might make sense to make backend the only input for simplicity if coupling_map is None: coupling_map = CouplingMap(backend.configuration().coupling_map) all_paths = rx.all_pairs_all_simple_paths( coupling_map.graph, min_depth=length, cutoff=length, ).values() paths = np.asarray( [ (list(c), list(sorted(list(c)))) for a in iter(all_paths) for b in iter(a) for c in iter(a[b]) ] ) # filter out duplicated paths _, unique_indices = np.unique(paths[:, 1], return_index=True, axis=0) paths = paths[:, 0][unique_indices].tolist() return paths def evaluate_fidelity(path: list[int], backend, edges) -> float: """Evaluates fidelity on a given list of qubits based on the two-qubit gate error for a specific backend. Returns: Path fidelity. """ two_qubit_fidelity = {} props = backend.properties() if "cx" in backend.configuration().basis_gates: gate_name = "cx" elif "ecr" in backend.configuration().basis_gates: gate_name = "ecr" else: raise ValueError("Could not identify two-qubit gate") for edge in edges: try: cx_error = props.gate_error(gate_name, edge) except: cx_error = props.gate_error(gate_name, edge[::-1]) two_qubit_fidelity[tuple(edge)] = 1 - cx_error if not path or len(path) == 1: return 0.0 fidelity = 1.0 for idx in range(len(path) - 1): fidelity *= two_qubit_fidelity[(path[idx], path[idx + 1])] return fidelity num_qubits = 10 path_finder = BackendEvaluator(backend) path, fidelity, num_subsets = path_finder.evaluate( num_qubits, subset_finder=find_lines, metric_eval=evaluate_fidelity ) print("Best path: ", path) print("Best path fidelity", fidelity) print("Num. evaluated paths", num_subsets)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import transpile from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() qc = QuantumCircuit(2, 1) qc.h(0) qc.x(1) qc.cp(np.pi/4, 0, 1) qc.h(0) qc.measure([0], [0]) qc_basis = transpile(qc, backend) qc_basis.draw(output='mpl')
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import os, shutil, time from random_qubo.random_qubo import RandomQubo DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y") def getPath(filename = "", directory = ""): return DIR + "/" + directory + "/" + filename bounds = {"matrix_q_lb": -5, "matrix_q_ub": 5, "c_lb": -5, "c_ub": 5} DIR shutil.rmtree(DIR, ignore_errors=True) os.makedirs(getPath(directory = "SPARSE")) os.makedirs(getPath(directory = "DENSE")) os.makedirs(getPath(directory = "MULTIPLE")) os.makedirs(getPath(directory = "CPLEX")) # create sparse random qubos # 3 variables connected # start with 3x1 qubits qaoa_max_qubits = 27 # number of qubits in Falcon r5.1 processors var = 3 multiple = 1 while True: qp = RandomQubo.create_random_qubo("test_" + str(multiple), var, multiple=multiple, **bounds) qp.write_to_lp_file(getPath(qp.name, directory = "SPARSE")) if qp.get_num_vars() > qaoa_max_qubits : print(multiple) break multiple = multiple + 1 # create dense random qubos # start with 3 variables while True: qp = RandomQubo.create_random_qubo("test_" + str(var), var, **bounds) qp.write_to_lp_file(getPath(qp.name, directory = "DENSE")) if qp.get_num_vars() > qaoa_max_qubits : print(var) break var = var + 3 # create more test data for pegasus # instances with several times the last instance which Mumbai is able to solve # 27 variables each # start with 27x2 qubits var = qaoa_max_qubits multiples = [2, 5, 10, 20] for multiple in multiples: qp = RandomQubo.create_random_qubo("test_" + str(multiple), var, multiple=multiple, **bounds) qp.write_to_lp_file(getPath(qp.name, directory = "MULTIPLE")) qp = RandomQubo.create_random_qubo("test_cplex", 100, **bounds) # used 10 for test data qp.write_to_lp_file(getPath(qp.name, directory = "CPLEX"))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) # plot probability distribution x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2.126 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective european_put = european_put_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, strike_price - x) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) exact_delta = -sum(uncertainty_model.probabilities[x <= strike_price]) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = -np.array(result_delta.confidence_interval)[::-1] print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % -result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The EfficientSU2 2-local circuit.""" from __future__ import annotations import typing from collections.abc import Callable from numpy import pi from qiskit.circuit import QuantumCircuit from qiskit.circuit.library.standard_gates import RYGate, RZGate, CXGate from .two_local import TwoLocal if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import class EfficientSU2(TwoLocal): r"""The hardware efficient SU(2) 2-local circuit. The ``EfficientSU2`` circuit consists of layers of single qubit operations spanned by SU(2) and :math:`CX` entanglements. This is a heuristic pattern that can be used to prepare trial wave functions for variational quantum algorithms or classification circuit for machine learning. SU(2) stands for special unitary group of degree 2, its elements are :math:`2 \times 2` unitary matrices with determinant 1, such as the Pauli rotation gates. On 3 qubits and using the Pauli :math:`Y` and :math:`Z` su2_gates as single qubit gates, the hardware efficient SU(2) circuit is represented by: .. parsed-literal:: ┌──────────┐┌──────────┐ ░ ░ ░ ┌───────────┐┌───────────┐ ┤ RY(θ[0]) ├┤ RZ(θ[3]) ├─░────────■───░─ ... ─░─┤ RY(θ[12]) ├┤ RZ(θ[15]) ├ ├──────────┤├──────────┤ ░ ┌─┴─┐ ░ ░ ├───────────┤├───────────┤ ┤ RY(θ[1]) ├┤ RZ(θ[4]) ├─░───■──┤ X ├─░─ ... ─░─┤ RY(θ[13]) ├┤ RZ(θ[16]) ├ ├──────────┤├──────────┤ ░ ┌─┴─┐└───┘ ░ ░ ├───────────┤├───────────┤ ┤ RY(θ[2]) ├┤ RZ(θ[5]) ├─░─┤ X ├──────░─ ... ─░─┤ RY(θ[14]) ├┤ RZ(θ[17]) ├ └──────────┘└──────────┘ ░ └───┘ ░ ░ └───────────┘└───────────┘ See :class:`~qiskit.circuit.library.RealAmplitudes` for more detail on the possible arguments and options such as skipping unentanglement qubits, which apply here too. Examples: >>> circuit = EfficientSU2(3, reps=1) >>> print(circuit) ┌──────────┐┌──────────┐ ┌──────────┐┌──────────┐ q_0: ┤ RY(θ[0]) ├┤ RZ(θ[3]) ├──■────■──┤ RY(θ[6]) ├┤ RZ(θ[9]) ├───────────── ├──────────┤├──────────┤┌─┴─┐ │ └──────────┘├──────────┤┌───────────┐ q_1: ┤ RY(θ[1]) ├┤ RZ(θ[4]) ├┤ X ├──┼───────■──────┤ RY(θ[7]) ├┤ RZ(θ[10]) ├ ├──────────┤├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤├───────────┤ q_2: ┤ RY(θ[2]) ├┤ RZ(θ[5]) ├─────┤ X ├───┤ X ├────┤ RY(θ[8]) ├┤ RZ(θ[11]) ├ └──────────┘└──────────┘ └───┘ └───┘ └──────────┘└───────────┘ >>> ansatz = EfficientSU2(4, su2_gates=['rx', 'y'], entanglement='circular', reps=1) >>> qc = QuantumCircuit(4) # create a circuit and append the RY variational form >>> qc.compose(ansatz, inplace=True) >>> qc.draw() ┌──────────┐┌───┐┌───┐ ┌──────────┐ ┌───┐ q_0: ┤ RX(θ[0]) ├┤ Y ├┤ X ├──■──┤ RX(θ[4]) ├───┤ Y ├───────────────────── ├──────────┤├───┤└─┬─┘┌─┴─┐└──────────┘┌──┴───┴───┐ ┌───┐ q_1: ┤ RX(θ[1]) ├┤ Y ├──┼──┤ X ├─────■──────┤ RX(θ[5]) ├───┤ Y ├───────── ├──────────┤├───┤ │ └───┘ ┌─┴─┐ └──────────┘┌──┴───┴───┐┌───┐ q_2: ┤ RX(θ[2]) ├┤ Y ├──┼──────────┤ X ├─────────■──────┤ RX(θ[6]) ├┤ Y ├ ├──────────┤├───┤ │ └───┘ ┌─┴─┐ ├──────────┤├───┤ q_3: ┤ RX(θ[3]) ├┤ Y ├──■──────────────────────┤ X ├────┤ RX(θ[7]) ├┤ Y ├ └──────────┘└───┘ └───┘ └──────────┘└───┘ """ def __init__( self, num_qubits: int | None = None, su2_gates: str | type | qiskit.circuit.Instruction | QuantumCircuit | list[str | type | qiskit.circuit.Instruction | QuantumCircuit] | None = None, entanglement: str | list[list[int]] | Callable[[int], list[int]] = "reverse_linear", reps: int = 3, skip_unentangled_qubits: bool = False, skip_final_rotation_layer: bool = False, parameter_prefix: str = "θ", insert_barriers: bool = False, initial_state: QuantumCircuit | None = None, name: str = "EfficientSU2", flatten: bool | None = None, ) -> None: """ Args: num_qubits: The number of qubits of the EfficientSU2 circuit. reps: Specifies how often the structure of a rotation layer followed by an entanglement layer is repeated. su2_gates: The SU(2) single qubit gates to apply in single qubit gate layers. If only one gate is provided, the same gate is applied to each qubit. If a list of gates is provided, all gates are applied to each qubit in the provided order. entanglement: Specifies the entanglement structure. Can be a string ('full', 'linear' , 'reverse_linear', 'circular' or 'sca'), a list of integer-pairs specifying the indices of qubits entangled with one another, or a callable returning such a list provided with the index of the entanglement layer. Default to 'reverse_linear' entanglement. Note that 'reverse_linear' entanglement provides the same unitary as 'full' with fewer entangling gates. See the Examples section of :class:`~qiskit.circuit.library.TwoLocal` for more detail. initial_state: A `QuantumCircuit` object to prepend to the circuit. skip_unentangled_qubits: If True, the single qubit gates are only applied to qubits that are entangled with another qubit. If False, the single qubit gates are applied to each qubit in the Ansatz. Defaults to False. skip_final_rotation_layer: If False, a rotation layer is added at the end of the ansatz. If True, no rotation layer is added. parameter_prefix: The parameterized gates require a parameter to be defined, for which we use :class:`~qiskit.circuit.ParameterVector`. insert_barriers: If True, barriers are inserted in between each layer. If False, no barriers are inserted. flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple layers of gate objects. By default currently the contents of the output circuit will be wrapped in nested objects for cleaner visualization. However, if you're using this circuit for anything besides visualization its **strongly** recommended to set this flag to ``True`` to avoid a large performance overhead for parameter binding. """ if su2_gates is None: su2_gates = [RYGate, RZGate] super().__init__( num_qubits=num_qubits, rotation_blocks=su2_gates, entanglement_blocks=CXGate, entanglement=entanglement, reps=reps, skip_unentangled_qubits=skip_unentangled_qubits, skip_final_rotation_layer=skip_final_rotation_layer, parameter_prefix=parameter_prefix, insert_barriers=insert_barriers, initial_state=initial_state, name=name, flatten=flatten, ) @property def parameter_bounds(self) -> list[tuple[float, float]]: """Return the parameter bounds. Returns: The parameter bounds. """ return self.num_parameters * [(-pi, pi)]
https://github.com/renatawong/quantum-maxcut
renatawong
#%%timeit ''' (C) Renata Wong (CGU-CoIC, NCTS-NTU) 2023 This is the accompanying code for the paper "Bioinspired Quantum Oracle Circuits for Biomolecular Solutions of the Maximum Cut Problem" by Weng-Long Chang, Renata Wong, Yu-Hao Chen, Wen-Yu Chung, Ju-Chin Chen, and Athanasios V. Vasilakos ''' from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile import numpy as np import time ''' Create the quantum circuit for the 3-vertex example num_vertices = n = number of vertices num_enges = m = number of edges ''' ''' PLEASE FILL IN THE EDGE LIST FOR YOUR GRAPH IN THE LINE BELOW ''' permanent_edge_list = [[0,1], [1,2]] # t is the maximum possible number of edges in a cut and is assumed to be known upfront t = 2 num_vertices = len({x for l in permanent_edge_list for x in l}) num_edges = len(permanent_edge_list) range_z = (num_edges * (num_edges + 3)) / 2 range_r = 2 * num_edges range_s = num_edges aux = QuantumRegister(1, 'aux') z_reg = QuantumRegister(range_z, 'z_reg') s_reg = QuantumRegister(range_s, 's_reg') r_reg = QuantumRegister(range_r, 'r_reg') x_reg = QuantumRegister(num_vertices, 'x_reg') readout = ClassicalRegister(num_vertices, 'out') qc = QuantumCircuit(x_reg, r_reg, s_reg, z_reg, aux, readout) system_size = qc.num_qubits print('System size:', system_size) ''' Create r_matrix to store indices of the register r_reg ''' r_matrix = [ [0 for j in range(2)] for i in range(num_edges)] rij = 0 for i in range(num_edges): for j in range(2): r_matrix[i][j] = rij rij += 1 #print('r matrix', r_matrix) ''' Create z_matrix to store indices of z_reg Note that i starts with index 1, not 0. ''' z_matrix = [ [ 0 for j in range(num_edges + 1) ] for i in range(num_edges + 1) ] zij = 0 for i in range(1, num_edges + 1): for j in range(i + 1): z_matrix[i][j] = zij zij += 1 #print('z matrix', z_matrix) ''' Define the EIIAC subcircuit ''' sq = QuantumRegister(5,'sq') sc = QuantumCircuit(sq, name='EIIAC') sc.x(sq[1]) sc.ccx(sq[0], sq[1], sq[2]) sc.x(sq[1]) sc.x(sq[0]) sc.ccx(sq[0], sq[1], sq[3]) sc.x(sq[0]) sc.x(sq[2]) sc.x(sq[3]) sc.ccx(sq[2], sq[3], sq[4]) sc.x(sq[2]) sc.x(sq[3]) eiiac = sc.to_instruction() ''' Initialize the system and set it in a uniform superpostion ''' for qubit in s_reg: qc.x(qubit) for qubit in x_reg: qc.h(qubit) qc.x(aux) qc.h(aux) #qc.barrier() ''' NOTE: There will always be an even number of solutions, since under maximum cut 101 is the same as 010. For Fig. 1 in the paper, we set the number of solutions to 2. YOU MAY NEED TO ADJUST THE NUMBER OF SOLUTIONS. ''' num_solutions = 2 num_runs = int(np.ceil(np.pi * np.sqrt((2**num_vertices) / num_solutions)) / 4) print('Number of iterations:', num_runs) ''' Amplitude amplification ''' for run in range(num_runs): # Apply EIIAC # It is assumed that the two vertices in the x_reg share an edge edge_list = permanent_edge_list.copy() for index, edge in enumerate(edge_list): [index_v1, index_v2] = edge cfe_qubits = [] cfe_qubits += [x_reg[index_v1]] cfe_qubits += [x_reg[index_v2]] cfe_qubits += [r_reg[k] for k in range(2*index, 2*index+2)] cfe_qubits += [s_reg[index]] qc.append(eiiac, cfe_qubits) #qc.barrier() # Apply INO if t > 0: qc.cx(s_reg[0], z_reg[1]) # Apply PNO if t < num_edges: qc.x(s_reg[0]) qc.cx(s_reg[0], z_reg[0]) qc.x(s_reg[0]) # Apply CIO and CPO for i in range(1, num_edges): for j in reversed(range(i+1)): if j+1 <= t and num_edges-i+j == t: qc.ccx(s_reg[i], z_reg[z_matrix[i][j]], z_reg[z_matrix[i+1][j+1]]) if j <= t and num_edges-i+j-1 == t: qc.x(s_reg[i]) qc.ccx(s_reg[i], z_reg[z_matrix[i][j]], z_reg[z_matrix[i+1][j+1]]) qc.x(s_reg[i]) ''' YOU MAY NEED TO ADJUST THE CONTROL QUBIT IN THE CX GATE. ''' #qc.barrier() qc.cx(z_reg[z_matrix[num_edges][t]], aux) #qc.barrier() ''' Uncomputing CIO, CPO, PNO, INO, and EIIAC, ''' # uncompute CIO and CPO for i in range(1, num_edges): for j in reversed(range(i+1)): if j+1 <= t and num_edges-i+j == t: qc.ccx(s_reg[i], z_reg[z_matrix[i][j]], z_reg[z_matrix[i+1][j+1]]) if j <= t and num_edges-i+j-1 == t: qc.x(s_reg[i]) qc.ccx(s_reg[i], z_reg[z_matrix[i][j]], z_reg[z_matrix[i+1][j+1]]) qc.x(s_reg[i]) # Uncompute PNO if t < num_edges: qc.x(s_reg[0]) qc.cx(s_reg[0], z_reg[0]) qc.x(s_reg[0]) # Uncompute INO if t > 0: qc.cx(s_reg[0], z_reg[1]) # Uncompute EIIAC index = len(edge_list) - 1 for edge in reversed(edge_list): [index_v1, index_v2] = edge cfe_qubits = [] cfe_qubits += [x_reg[index_v1]] cfe_qubits += [x_reg[index_v2]] cfe_qubits += [r_reg[k] for k in range(2*index, 2*index+2)] cfe_qubits += [s_reg[index]] index -= 1 qc.append(eiiac.inverse(), cfe_qubits) ''' Diffusion operations ''' qc.barrier() for qubit in x_reg: qc.h(qubit) qc.x(qubit) qc.h(x_reg[len(x_reg) - 1]) multiplexer = [x_reg[i] for i in range(len(x_reg) - 1)] qc.mcx(multiplexer, x_reg[len(x_reg) - 1]) qc.h(x_reg[len(x_reg) - 1]) for qubit in x_reg: qc.x(qubit) qc.h(qubit) #qc.barrier() ''' Measurement ''' cuts = [] for i in range(len(x_reg)): cuts.append(x_reg[i]) # Reverse the order in which the output is shown so that it can be read from left to right. cuts.reverse() qc.measure(cuts, readout) #from qiskit import Aer, execute from qiskit.visualization import plot_histogram from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(num_qubits=15) start_time = time.time() # Transpile the ideal circuit to a circuit that can be directly executed by the backend transpiled_circuit = transpile(qc, backend) transpiled_circuit.draw('mpl') job = backend.run(transpiled_circuit) elapsed_time = time.time() - start_time print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time))) counts = job.result().get_counts() plot_histogram(counts) # Uncomment to save the output #plot_histogram(counts).savefig('example.svg') qc.draw('mpl') print('Backend name: ', backend.name) print() t1_sum, t2_sum, fr_sum = 0, 0, 0 for qubit in range(qc.num_qubits): t1_sum += backend.qubit_properties(qubit).t1 t2_sum += backend.qubit_properties(qubit).t2 fr_sum += backend.qubit_properties(qubit).frequency print('Average qubit properties:') print('T1 in microsec: ', t1_sum/qc.num_qubits) print('T2 in microsec: ', t2_sum/qc.num_qubits) print('Frequency in Hz: ', fr_sum/qc.num_qubits) print() xdu_sum, xer_sum = 0, 0 sxdu_sum, sxer_sum = 0, 0 rzdu_sum, rzer_sum = 0, 0 iddu_sum, ider_sum = 0, 0 cxdu_sum, cxer_sum = 0, 0 #print(backend.instructions) #print('Instruction durations: ', backend.instruction_durations) for qubit in range(qc.num_qubits): xdu_sum += backend.target["x"][(qubit,)].duration xer_sum += backend.target["x"][(qubit,)].error sxdu_sum += backend.target["sx"][(qubit,)].duration sxer_sum += backend.target["sx"][(qubit,)].error rzdu_sum += backend.target["rz"][(qubit,)].duration rzer_sum += backend.target["rz"][(qubit,)].error iddu_sum += backend.target["id"][(qubit,)].duration ider_sum += backend.target["id"][(qubit,)].error for target in range(qc.num_qubits): if target != qubit: cxdu_sum += backend.target["cx"][(qubit,target)].duration cxer_sum += backend.target["cx"][(qubit,target)].error print('Average x gate properties: ') print('Duration: ', xdu_sum/qc.num_qubits) print('Error: ', xer_sum/qc.num_qubits) print() print('Average sx gate properties: ') print('Duration: ', sxdu_sum/qc.num_qubits) print('Error: ', sxer_sum/qc.num_qubits) print() print('Average rz gate properties: ') print('Duration: ', rzdu_sum/qc.num_qubits) print('Error: ', rzer_sum/qc.num_qubits) print() print('Average id gate properties: ') print('Duration: ', iddu_sum/qc.num_qubits) print('Error: ', ider_sum/qc.num_qubits) print() print('Average cx gate properties: ') print('Duration: ', cxdu_sum/qc.num_qubits) print('Error: ', cxer_sum/qc.num_qubits) print() num_gates = qc.count_ops() print('Number of gates:', num_gates) print('Gates in EIIAC:', sc.count_ops())
https://github.com/Qiskit/qiskit-transpiler-service
Qiskit
# -*- coding: utf-8 -*- # (C) Copyright 2024 IBM. All Rights Reserved. # # 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. """Unit-testing linear_function_collection""" from qiskit import QuantumCircuit from qiskit.transpiler import PassManager from qiskit_transpiler_service.ai.collection import CollectPermutations def test_permutation_collection_pass(random_circuit_transpiled): collect = PassManager( [ CollectPermutations(), ] ) collected_circuit = collect.run(random_circuit_transpiled) assert isinstance(collected_circuit, QuantumCircuit) def test_permutation_collection_pass_collect(swap_circ): collect = PassManager( [ CollectPermutations(min_block_size=1, max_block_size=5), ] ) collected_circuit = collect.run(swap_circ) assert isinstance(collected_circuit, QuantumCircuit) assert any(g.operation.name.lower() == "permutation" for g in collected_circuit) def test_permutation_collection_pass_no_collect(rzz_circ): collect = PassManager( [ CollectPermutations(min_block_size=7, max_block_size=12), ] ) collected_circuit = collect.run(rzz_circ) assert all(g.operation.name.lower() != "permutation" for g in collected_circuit) def test_permutation_collection_max_block_size(swap_circ): collect = PassManager( [ CollectPermutations(max_block_size=7), ] ) collected_circuit = collect.run(swap_circ) assert all(len(g.qubits) <= 7 for g in collected_circuit) def test_permutation_collection_min_block_size(swap_circ): collect = PassManager( [ CollectPermutations(min_block_size=7, max_block_size=12), ] ) collected_circuit = collect.run(swap_circ) assert all( len(g.qubits) >= 7 or g.operation.name.lower() != "permutation" for g in collected_circuit )
https://github.com/MonitSharma/qiskit-projects
MonitSharma
import numpy as np import random import matplotlib.pyplot as plt from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import NearestCentroid from IPython.display import clear_output import pandas as pd # ======================================================= import math import time from qiskit import Aer, QuantumCircuit, execute from qiskit.extensions import UnitaryGate from qiskit.providers.jobstatus import JobStatus # Use Aer's qasm_simulator by default backend = Aer.get_backend('qasm_simulator') # generate toy data: random N x N board def generate_board(N): ''' Generates a random board of dimensions N x N Inputs: N := 1D dimension of board, s.t. board.shape = (N,N) Outputs: board := flattened N x N array winner := red wins == 1, blue wins == -1 sum_red := sum of red pieces sum_blue := sum of blue pieces ''' board=np.zeros((N*N)) pieces=random.sample(range(1,N*N),1)[0] inds = random.sample(range(0,N*N),pieces) # pick random location to place pieces ratio = 1 while ratio == 1: # safeguard to remove possiblility of ties for n in range(pieces): board[inds[n]]=random.sample([-1,1],1)[0] # make space blue or red sum_red = np.sum(board==1) # sum of 1 values (i.e., red pieces) sum_blue = np.sum(board==-1) # sum of -1 values (i.e., blue pieces) ratio = (sum_red+1)/(sum_blue+1) # find ratio if ratio > 1: # red wins winner = 1 elif ratio < 1: # blue wins winner = -1 else: pass return board, winner, sum_red, sum_blue def generate_data(D,N,train_split): ''' Generates labelled data arrays + images. Inputs: D := desired number of data points N := 1D dimension of board, s.t. board.shape = (N,N) train_split := split of training/testing data, e.g., 0.9 => 90% training, 10% testing Outputs: training_data := split training data, data array: [# red pieces, # blue pieces, winner] dims: (D*train_split) x 3 training_images := split training data, corresponding board images; flattened dims: (D*train_split) x N**2 testing_data := split testing data, data array: [# red pieces, # blue pieces, winner] dims: (D*(1-train_split)) x 3 testing_images := split testing data, corresponding board images; flattened dims: (D*(1-train_split)) x N**2 ''' data = np.zeros((D,3)) # create array to populate each row with x1: black sum, x2: white sum, label: ratio images = np.zeros((D,N**2)) # create array to populate D rows with flattened N x N images in the columns for n in range(D): board,winner,sum_red,sum_blue = generate_board(N=N) data[n,[0,1,2]]=[sum_red,sum_blue,winner] images[n,:]=board training_data=data[:int(D*train_split),:] # labelled training data training_images=images[:int(D*train_split),:] # training images testing_data=data[int(D*train_split):,:] # labelled testing data testing_images=images[int(D*train_split):,:] # testing images return training_data, training_images, testing_data, testing_images # gameboard parameters N=8 # 1D of gameboard. Game board => N x N dimensions # generate training/testing data for the classical and quantum classifiers training_data, training_images, testing_data, testing_images =generate_data(D=300,N=8,train_split=0.9) def nCen_train_test(training_data, testing_data, N, shrink, plot_testing=False): ''' Train Nearest Centroid Neighbors algorithm. Plot results and accuracy. Output the best nCen. Inputs: training_data := split training data, data array: [# red pieces, # blue pieces, winner] dims: (D*train_split) x 3 testing_data := split testing data, data array: [# red pieces, # blue pieces, winner] dims: (D*(1-train_split)) x 3 N := 1D dimension of board, s.t. board.shape = (N,N); used here for normalizing the data shrink := list of shrink values to test, e.g., shrink=[0.0,0.1,0.5,0.9] plot_testing := True or False value; plots the testing dataset with classifier bounds Outputs: Plots the nearest centroid decision boundary, training data, test data, and accuracy plots nCen := nearest centroid object with the highest accuracy ''' # Assign training/test data training_data[:,[0,1]]=training_data[:,[0,1]]/(N**2) # standardize data. Max pieces is N*N testing_data[:,[0,1]]=testing_data[:,[0,1]]/(N**2) # standardize data. Max pieces is N*N X_train = training_data[:,[0,1]] # training features y_train = training_data[:,2] # training labels X_test = testing_data[:,[0,1]] # testing features y_test = testing_data[:,2] # testing labels # ============================================================================= # run accuracy with training data for k=k neighbors acc_list=[] nCen_list=[] for i in range(len(shrink)): # run kNN classification nCen_list.append(NearestCentroid(shrink_threshold=shrink[i])) # create k-NN object nCen_list[i].fit(X_train, y_train) # fit classifier decision boundary to training data # ============================================================================= # plot classification boundary with training data meshres=50 RED,BLUE=np.meshgrid(np.linspace(np.min([np.min(X_train[:,0]),np.min(X_test[:,0])]),np.max([np.max(X_train[:,0]),np.max(X_test[:,0])]),meshres), np.linspace(np.min([np.min(X_train[:,1]),np.min(X_test[:,1])]),np.max([np.max(X_train[:,1]),np.max(X_test[:,1])]),meshres)) boundary=nCen_list[i].predict(np.c_[RED.ravel(),BLUE.ravel()]) plt.figure() plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3) plt.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap='bwr',edgecolor='k') plt.xlabel('# red pieces\n[normalized]') plt.ylabel('# blue pieces\n[normalized]') cbar=plt.colorbar() cbar.ax.set_ylabel('Winner') plt.title('Centroid Classification, shrink = '+str(shrink[i])) plt.show() # plot testing data if plot_testing == True: plt.figure() plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3) testt=plt.scatter(X_test[:,0],X_test[:,1],c=y_test,cmap='bwr',edgecolor='k') plt.xlabel('# red pieces\n[normalized]') plt.ylabel('# blue pieces\n[normalized]') plt.title('Testing Data, n = '+str(X_test.shape[0])) cbar=plt.colorbar(testt) cbar.ax.set_ylabel('Winner') plt.show() else: pass # ============================================================================= # calculate accuracy with training data set predicted=nCen_list[i].predict(X_test) # calculate predicted label from training data acc=np.sum(predicted==y_test)/len(y_test) # calculate accuracy of where prediction is correct vs incorrect relative to actual labels acc_list.append(acc) print('shrink = ',shrink[i],'\nTraining Accuracy =',acc*100,'%\n','='*40,'\n\n') plt.figure() plt.plot(shrink,acc_list,marker='o') plt.xlabel('Centroid shrinking threshold') plt.xticks(shrink) plt.ylabel('Accuracy') plt.show() best_nCen=nCen_list[np.argmax(acc_list)] print('best shrink = ',shrink[np.argmax(acc_list)]) return best_nCen # generate best nearest centroid neighbors best_nCen = nCen_train_test(training_data=training_data, testing_data=testing_data, N=N, shrink=list(np.arange(0.0,0.9,0.1)),plot_testing=True) def player_prediction_classical(best_model,player_data): ''' Outputs the classically predicted result of the 5 player games, not within the training dataset. Inputs: best_model := NearestCentroid object player_data := generated data array: [# red pieces, # blue pieces, winner] dims: 5 x 3 Outputs: cCompData := list of 0 or 1 values. 1 == red wins, 0 == blue wins ''' X_player_data=player_data[:,[0,1]] cCompData = best_model.predict(X_player_data) cCompData[cCompData==-1.]=0 return list(cCompData.astype(int)) # Unit-normalized vector helper def normalize(x): return x / np.linalg.norm(x) # Since in a space R^n there are n-1 RBS gates, # in a 2-dimensional dataset (R^2), there is 1 # RBS parameter angle, as defined: def theta_in_2d(x): epsilon = math.pow(10, -10) return math.acos((x[0] + epsilon) / (np.linalg.norm(x) + epsilon)) + epsilon def estimation_circuit(x_theta, y_theta): # As defined in Johri et al. (III.A.1), an iRBS is functionally # identical in the distance estimation circuit to the RBS gate; # thus, the iRBS gate is defined in the QuantumCircuit class to # be used in the estimation circuit. # Unitary implementation (throws IonQ backend error) def irbs_unitary(theta): return UnitaryGate([[1, 0, 0, 0], [0, np.cos(theta), complex(0,-np.sin(theta)), 0], [0, complex(0, -np.sin(theta)), np.cos(theta), 0], [0, 0, 0, 1]], label=f'iRBS({np.around(theta, 3)})') # Circuit implementation from figure 7 in Johri et al. def irbs(qc, theta, qubits): qc.rz(np.pi/2, qubits[1]) qc.cx(qubits[1], qubits[0]) qc.ry(np.pi/2 - 2 * theta, qubits[1]) qc.rz(-np.pi/2, qubits[0]) qc.cx(qubits[0], qubits[1]) qc.ry(2 * theta - np.pi/2, qubits[1]) qc.cx(qubits[1], qubits[0]) qc.rz(-np.pi / 2, qubits[0]) qc = QuantumCircuit(2,2) qc.x(0) irbs(qc, x_theta, [0, 1]) irbs(qc, y_theta, [0, 1]) qc.measure([0, 1], [0, 1]) return qc # Returns estimated distance as defined in Johri et al. (Equation 3) def probability_uncorrected(result): counts = result.get_counts() shots = np.sum(list(counts.values())) if '10' in counts: return counts["10"]/shots else: return 0 def probability_corrected(result): counts = result.get_counts() corrected_counts = {} # Discard incorrect values (00, 11) if '10' in counts: corrected_counts['10'] = counts['10'] if '01' in counts: corrected_counts['01'] = counts['01'] shots = np.sum(list(corrected_counts.values())) if '10' in counts: return corrected_counts["10"]/shots else: return 0 def euclidian_distance(x, y, corrected=False): x_norm = np.linalg.norm(x) y_norm = np.linalg.norm(y) x_square_norm = x_norm**2 y_square_norm = y_norm**2 x_theta = theta_in_2d(x) y_theta = theta_in_2d(y) ec = estimation_circuit(x_theta, y_theta) if backend.name() == "qasm_simulator": job = execute(ec, backend, shots=1000) else: # IonQ job = backend.run(ec, shots=1000) job_id = job.job_id() while job.status() is not JobStatus.DONE: print(job.status()) time.sleep(1) result = job.result() if corrected: probability = probability_corrected(result) else: probability = probability_uncorrected(result) normalized_inner_product = math.sqrt(probability) return math.sqrt(x_square_norm + y_square_norm - 2*x_norm*y_norm*normalized_inner_product) import random # generate toy data: random N x N board def generate_board(N): ''' Generates a random board of dimensions N x N Inputs: N := 1D dimension of board, s.t. board.shape = (N,N) Outputs: board := flattened N x N array winner := red wins == 1, blue wins == -1 sum_red := sum of red pieces sum_blue := sum of blue pieces ''' board=np.zeros((N*N)) pieces=random.sample(range(1,N*N),1)[0] inds = random.sample(range(0,N*N),pieces) # pick random location to place pieces ratio = 1 while ratio == 1: # safeguard to remove possiblility of ties for n in range(pieces): board[inds[n]]=random.sample([-1,1],1)[0] # make space blue or red sum_red = np.sum(board==1) # sum of 1 values (i.e., red pieces) sum_blue = np.sum(board==-1) # sum of -1 values (i.e., blue pieces) ratio = sum_red/sum_blue # find ratio if ratio > 1: # red wins winner = 1 elif ratio < 1: # blue wins winner = -1 else: pass return board, winner, sum_red, sum_blue class QuantumNearestCentroid: def __init__(self): self.centroids = {} def centroid(self, x): return np.mean(x, axis=0) def fit(self, x, y): organized_values = {} for i, v in enumerate(y): if v in organized_values: organized_values[v].append(x[i]) else: organized_values[v] = [x[i]] for v in organized_values: self.centroids[v] = self.centroid(organized_values[v]) return self.centroids def predict(self, x): min_dist = np.inf closest_centroid = None for key, centroid in self.centroids.items(): res = euclidian_distance(x, centroid) if res < min_dist: min_dist = res closest_centroid = key return closest_centroid def player_prediction_quantum(best_model,player_data): ''' Outputs the quantum predicted result of the 5 player games, not within the training dataset. Inputs: best_model := NearestCentroid object player_data := generated data array: [# red pieces, # blue pieces, winner] dims: 5 x 3 Outputs: cCompData := list of 0 or 1 values. 1 == red wins, 0 == blue wins ''' X_player_data=player_data[:,[0,1]] qCompData = [] for i in range(5): qCompData.append(best_model.predict(X_player_data[i])) qCompData[qCompData==-1.]=0 return list(qCompData) def quantum_train_test(training_data, testing_data, N, plot_testing=False): ''' Train Nearest Centroid Neighbors algorithm. Plot results and accuracy. Output the best nCen. Inputs: training_data := split training data, data array: [# red pieces, # blue pieces, winner] dims: (D*train_split) x 3 testing_data := split testing data, data array: [# red pieces, # blue pieces, winner] dims: (D*(1-train_split)) x 3 N := 1D dimension of board, s.t. board.shape = (N,N); used here for normalizing the data shrink := list of shrink values to test, e.g., shrink=[0.0,0.1,0.5,0.9] plot_testing := True or False value; plots the testing dataset with classifier bounds Outputs: Plots the nearest centroid decision boundary, training data, test data, and accuracy plots nCen := nearest centroid object with the highest accuracy ''' # Assign training/test data X_train = training_data[:,[0,1]] # training features y_train = training_data[:,2] # training labels X_test = testing_data[:,[0,1]] # testing features y_test = testing_data[:,2] # testing labels # ============================================================================= model = QuantumNearestCentroid() centroid = model.fit(X_train.tolist(), y_train.flatten().tolist()) print(centroid) meshres=30 RED,BLUE=np.meshgrid(np.linspace(np.min([np.min(X_train[:,0]),np.min(X_test[:,0])]),np.max([np.max(X_train[:,0]),np.max(X_test[:,0])]),meshres), np.linspace(np.min([np.min(X_train[:,1]),np.min(X_test[:,1])]),np.max([np.max(X_train[:,1]),np.max(X_test[:,1])]),meshres)) print(len(np.c_[RED.ravel(),BLUE.ravel()])) boundary=[] for i, v in enumerate(np.c_[RED.ravel(),BLUE.ravel()]): print(f"{i} : {v.tolist()}") res = model.predict(list(v)) print(res) boundary.append(res) print(boundary) boundary = np.array(boundary) plt.figure() plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3) plt.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap='bwr',edgecolor='k') plt.xlabel('# red pieces\n[normalized]') plt.ylabel('# blue pieces\n[normalized]') cbar=plt.colorbar() cbar.ax.set_ylabel('Winner') plt.title('Centroid Classification') plt.show() # plot testing data if plot_testing == True: plt.figure() plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3) testt=plt.scatter(X_test[:,0],X_test[:,1],c=y_test,cmap='bwr',edgecolor='k') plt.xlabel('# red pieces\n[normalized]') plt.ylabel('# blue pieces\n[normalized]') plt.title('Testing Data, n = '+str(X_test.shape[0])) cbar=plt.colorbar(testt) cbar.ax.set_ylabel('Winner') plt.show() else: pass # ============================================================================= # calculate accuracy with training data set predicted=[] # calculate predicted label from training data for v in X_test: predicted.append(model.predict(v)) predicted = np.array(predicted) acc=np.sum(predicted==y_test)/len(y_test) # calculate accuracy of where prediction is correct vs incorrect relative to actual labels print('Training Accuracy =',acc*100,'%\n','='*40,'\n\n') return model def quantum_train(training_data, testing_data, N): # Assign training/test data X_train = training_data[:,[0,1]] # training features y_train = training_data[:,2] # training labels X_test = testing_data[:,[0,1]] # testing features y_test = testing_data[:,2] # testing labels model = QuantumNearestCentroid() centroid = model.fit(X_train.tolist(), y_train.flatten().tolist()) return model # Uncomment below if you want to run the analysis #best_quantum = quantum_train_test(training_data=training_data, testing_data=testing_data, N=N, plot_testing=True) # generate best nearest centroid neighbors best_quantum = quantum_train(training_data=training_data, testing_data=testing_data, N=N) compData = [] compResults = [] def generateCompData(cData = [0,0,0,0,0], qData = [0,0,0,0,0], gData = [0, 0, 0, 0,]): global compData global compResults ''' Here we take the 2d array gData and transpose it ''' pgData = pd.DataFrame(gData).T.values.tolist() pgData = [0 if x==-1.0 else 1 for x in pgData[2]] ''' These reset the compData and compResults array so there are no errors with the runtime ''' compData = [ [0,0,0,0], # Storing what the [Q, C, H, G] say the answer is. [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0] ] compResults = [ [0,0,0], # Storing [QvG, HvG, CvG] [0,0,0], [0,0,0], [0,0,0], [0,0,0] ] ''' The entirety of this function is to setup the enviroment for future functions ''' qCompData = qData # this will be the data from the QML on the 5 boards given cCompData = cData # this will be the data from the Classical on the 5 boards given gCompData = pgData # this is the ground truth answers ''' These take the original qCompData and cCompData arrays and put them together in the compData array for parrsing later in the program ''' count = 0 for i in qCompData: compData[count][1] = int(i) count += 1 count = 0 for i in cCompData: compData[count][0] = int(i) count += 1 count = 0 for i in gCompData: compData[count][3] = int(i) count += 1 def finalizeCompResults(): ''' The entirety of this function is to check if the quatum model and human match the conventional model ''' global compData global compResults count = 0 for i in compData: if i[3] == i[0]: # this is for the C v. G compResults[count][1] = 1 if i[3] == i[1]: # this is for the Q v. G compResults[count][0] = 1 if i[3] == i[2]: # this is for the H v. G compResults[count][2] = 1 count += 1 def showCompResults(): ''' The entirety of this function is to display to the user which problem they or the quantum computer got correct in a visually pleasing way ''' global compResults global compData data = [ [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0] ] dataColors = [ ["#a2cffe",0,0,0], ["#a2cffe",0,0,0], ["#a2cffe",0,0,0], ["#a2cffe",0,0,0], ["#a2cffe",0,0,0] ] ''' This next for loop checks the compResults array and sets the values of data and dataColors accordingly ''' count = 0 # print(compResults) for i in compResults: if i[0] == 1: # Q v. G data[count][3] = compData[count][1] dataColors[count][3] = "palegreen" else: dataColors[count][3] = "#cf6275" if i[2] == 1: # Human v. G data[count][1] = compData[count][2] dataColors[count][1] = "palegreen" else: dataColors[count][1] = "#cf6275" if i[1] == 1: # C v. G data[count][2] = compData[count][0] dataColors[count][2] = "palegreen" else: dataColors[count][2] = "#cf6275" data[count][0] = compData[count][3] count += 1 print(data) for i in range(0,5): data[i] = ["Red" if x==1 else "Blue" for x in data[i]] print(data) ''' This section below sums the amount of correct answers from both the human and quantum computer ''' Sum = [sum(x) for x in zip(*compResults)] winner = ". . . wait what?!?!?! it was a tie! Well, I guess no one" if (Sum[0] < Sum[1]) and (Sum[0] < Sum[2]): winner = "Human" elif (Sum[1] < Sum[0]) and (Sum[1] < Sum[2]): winner = "Quantum Computer" elif (Sum[2] < Sum[1]) and (Sum[2] < Sum[0]): winner = "Classical Computer" ''' This section below displays the data formated above and who the winner of the game is ''' fig, ax = plt.subplots(1,1) column_labels=["Truth", "Human v. Truth", "Classical v. Truth", "Quantum v. Truth"] plt.title("Who won, a quantum computer or a human? Turns out the " + winner + " is better!") ax.axis('tight') ax.axis('off') ax.table(cellText=data, colLabels = column_labels, cellColours = dataColors, loc = "center", cellLoc='center') plt.show() def showProblem(array): ''' This function is used to display the game board for the user to evaluate ''' global compData N = 8 # board dimensions: N x N board = array board = board.reshape(N,N) plt.axis('off') plt.title("Who has more?") plt.imshow(board,cmap='bwr') plt.show() def playersMove(roundNum): ''' This function is used to initialize the user to input an answer for the game board ''' global compData while True: print("Is red or blue more? (b/r): ") playerChoice = input("").lower() if playerChoice == "r": playerChoice = 1 break elif playerChoice == "b": playerChoice = 0 break compData[roundNum][2] = playerChoice clear_output(wait=True) newGame = True while newGame: # Generate 5 boards for the player to play player_data_5, player_images_5, __, __ =generate_data(D=5,N=8,train_split=1) cCompData = player_prediction_classical(best_model=best_nCen,player_data=player_data_5) # qCompData = player_prediction_quantum(best_model=best_quantum,player_data=player_data_5) qCompData=[0,0,0,0,0] generateCompData(cCompData, qCompData, player_data_5) clear_output(wait=True) # Start the game! for i in range(0, 5): showProblem(player_images_5[i]) playersMove(i) clear_output(wait=True) finalizeCompResults() showCompResults() while True: print("Would you like to play again? (y/n): ") playerChoice = input("").lower() if playerChoice == "y": clear_output(wait=True) break elif playerChoice == "n": clear_output(wait=True) newGame = False break
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_qsphere(state)
https://github.com/nmoran/qiskit-qdrift-quid19
nmoran
import pylab import time import numpy as np import multiprocessing as mp from qiskit import BasicAer from qiskit.aqua import QuantumInstance, AquaError from qiskit.aqua.operators import Z2Symmetries from qiskit.aqua.operators.op_converter import to_weighted_pauli_operator from qiskit.aqua.algorithms.single_sample import IQPE from qiskit.aqua.algorithms.single_sample import QPE from qiskit.aqua.components.iqfts import Standard from qiskit.aqua.algorithms.classical import ExactEigensolver from qiskit.chemistry import FermionicOperator from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock from qiskit.chemistry.drivers import PySCFDriver, UnitsType def compute_energy(i, distance, algorithm): try: driver = PySCFDriver( atom='H .0 .0 .0; H .0 .0 {}'.format(distance), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g' ) except: raise AquaError('PYSCF driver does not appear to be installed') molecule = driver.run() qubit_mapping = 'parity' fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubit_op = Z2Symmetries.two_qubit_reduction(to_weighted_pauli_operator(fer_op.mapping(map_type=qubit_mapping, threshold=1e-10)), 2) if algorithm.lower() == 'exacteigensolver': exact_eigensolver = ExactEigensolver(qubit_op, k=1) result = exact_eigensolver.run() reference_energy = result['energy'] elif algorithm.lower() == 'iqpe': num_particles = molecule.num_alpha + molecule.num_beta two_qubit_reduction = True num_orbitals = qubit_op.num_qubits + (2 if two_qubit_reduction else 0) num_time_slices = 2 num_iterations = 10 state_in = HartreeFock(qubit_op.num_qubits, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction) iqpe = IQPE(qubit_op, state_in, num_time_slices, num_iterations, expansion_mode='trotter', expansion_order=1, shallow_circuit_concat=True) # backend = BasicAer.get_backend('statevector_simulator') backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend) result = iqpe.run(quantum_instance) elif algorithm.lower() == 'qpe': num_particles = molecule.num_alpha + molecule.num_beta two_qubit_reduction = True num_orbitals = qubit_op.num_qubits + (2 if two_qubit_reduction else 0) num_time_slices = 10 iqft = Standard(qubit_op.num_qubits) state_in = HartreeFock(qubit_op.num_qubits, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction) qpe = QPE(qubit_op, state_in, iqft, num_time_slices, num_ancillae=4, expansion_mode='trotter', expansion_order=1, shallow_circuit_concat=True) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) result = qpe.run(quantum_instance) else: raise AquaError('Unrecognized algorithm.') return i, distance, result['energy'] + molecule.nuclear_repulsion_energy, molecule.hf_energy import concurrent.futures import multiprocessing as mp algorithms = ['iqpe', 'exacteigensolver', 'qpe'] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 1 # Number of steps to increase by energies = np.empty([len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) start_time = time.time() for j in range(len(algorithms)): algorithm = algorithms[j] print(f'On algorithm {algorithm}') for i in range(steps+1): d = start + i*by/steps result = compute_energy( i, d, algorithm ) i, d, energy, hf_energy = result energies[j][i] = energy hf_energies[i] = hf_energy distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print("--- %s seconds ---" % (time.time() - start_time)) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy') pylab.legend(loc='upper right') pylab.show() pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[0], energies[1]), label='IQPE') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper right') pylab.show() import concurrent.futures import multiprocessing as mp algorithms = ['qpe'] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 1 # Number of steps to increase by reps=5 energies = np.empty([len(algorithms), steps+1, reps]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) start_time = time.time() for j in range(len(algorithms)): for k in range(reps): algorithm = algorithms[j] print(f'On algorithm {algorithm}') for i in range(steps+1): d = start + i*by/steps result = compute_energy( i, d, algorithm ) i, d, energy, hf_energy = result energies[j][i][k] = energy hf_energies[i] = hf_energy distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print("--- %s seconds ---" % (time.time() - start_time)) from qiskit.chemistry import set_qiskit_chemistry_logging import logging set_qiskit_chemistry_logging(logging.INFO) import concurrent.futures import multiprocessing as mp algorithms = ['iqpe', 'exacteigensolver', 'qpe'] start = 0.5 # Start distance by = 0.5 # How much to increase distance by steps = 1 # Number of steps to increase by energies = np.empty([len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) start_time = time.time() for j in range(len(algorithms)): algorithm = algorithms[j] print(f'On algorithm {algorithm}') for i in range(steps+1): d = start + i*by/steps result = compute_energy( i, d, algorithm ) i, d, energy, hf_energy = result energies[j][i] = energy hf_energies[i] = hf_energy distances[i] = d print(' --- complete') print('Distances: ', distances) print('Energies:', energies) print('Hartree-Fock energies:', hf_energies) print("--- %s seconds ---" % (time.time() - start_time)) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]) pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('H2 Ground State Energy') pylab.legend(loc='upper right') pylab.show() BasicAer.backends()
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram n = 8 n_q = 8 n_b = 8 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,0) 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(output='mpl') counts = execute(qc_ha,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import ( ElectronicStructureDriverType, ElectronicStructureMoleculeDriver, PySCFDriver, ) from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer from qiskit_nature.settings import settings settings.dict_aux_operators = True molecule = Molecule( geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1 ) driver = ElectronicStructureMoleculeDriver( molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF ) # or equivalently: driver = PySCFDriver.from_molecule(molecule, basis="sto3g") transformer = FreezeCoreTransformer() problem = ElectronicStructureProblem(driver, transformers=[transformer]) # Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so: second_q_ops = problem.second_q_ops() hamiltonian = second_q_ops["ElectronicEnergy"] print(hamiltonian) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo from qiskit_nature.second_q.transformers import FreezeCoreTransformer molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1) driver = PySCFDriver.from_molecule(molecule, basis="sto3g") # this is now done explicitly problem = driver.run() transformer = FreezeCoreTransformer() # and you also apply transformers explicitly problem = transformer.transform(problem) hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver molecule = Molecule( geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1 ) driver = PySCFDriver.from_molecule(molecule) result = driver.run() print(type(result)) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1) driver = PySCFDriver.from_molecule(molecule, basis="sto3g") result = driver.run() print(type(result)) from qiskit_nature.drivers.second_quantization import FCIDumpDriver path_to_fcidump = "aux_files/h2.fcidump" driver = FCIDumpDriver(path_to_fcidump) result = driver.run() print(type(result)) from qiskit_nature.second_q.formats.fcidump import FCIDump path_to_fcidump = "aux_files/h2.fcidump" fcidump = FCIDump.from_file(path_to_fcidump) print(type(fcidump)) from qiskit_nature.second_q.formats.fcidump_translator import fcidump_to_problem problem = fcidump_to_problem(fcidump) print(type(problem)) from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer transformer = FreezeCoreTransformer() driver = PySCFDriver() transformed_result = transformer.transform(driver.run()) print(type(transformed_result)) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.transformers import FreezeCoreTransformer transformer = FreezeCoreTransformer() driver = PySCFDriver() transformed_result = transformer.transform(driver.run()) print(type(transformed_result)) from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer driver = PySCFDriver() transformer = FreezeCoreTransformer() problem = ElectronicStructureProblem(driver, transformers=[transformer]) # we trigger driver.run() implicitly like so: second_q_ops = problem.second_q_ops() hamiltonian_op = second_q_ops.pop("ElectronicEnergy") aux_ops = second_q_ops from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.transformers import FreezeCoreTransformer driver = PySCFDriver() problem = driver.run() transformer = FreezeCoreTransformer() problem = transformer.transform(problem) hamiltonian_op, aux_ops = problem.second_q_ops() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/InvictusWingsSRL/QiskitTutorials
InvictusWingsSRL
#%matplotlib widgets import tkinter import matplotlib import matplotlib.pyplot as plt import ipympl import IPython #matplotlib.use('TkAgg') #matplotlib.use('WebAgg') from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, transpile, qasm2, qasm3 from qiskit_aer import Aer from qiskit.primitives import BackendSampler from qiskit.providers.basic_provider import BasicProvider # instead of BasicAer import Our_Qiskit_Functions as oq import numpy as np import math as m import scipy as sci import random import time from itertools import permutations S_simulator = Aer.backends(name='statevector_simulator')[0] %matplotlib ipympl #%matplotlib notebook #plt.rcParams['animation.html'] = 'jshtml' Data = [ [1,1],[4,2],[5,5],[3,6] ] D_min = [1000,0,0] D2_min = [1000,0,0] #----------------------------------------- Searches for centroids within 3 < x < 4 and 3 < y < 4 for j1 in np.arange(1000): X = 3.0 + j1/1000.0 for j2 in np.arange(1000): Y = 3.0 + j2/1000.0 D = 0 D2 = 0 for k in np.arange( len(Data) ): D = D + m.sqrt( (X-Data[k][0])**2 + (Y-Data[k][1])**2 ) D2 = D2 + (X-Data[k][0])**2 + (Y-Data[k][1])**2 if( D < D_min[0] ): D_min = [ D, X, Y ] if( D2 < D2_min[0] ): D2_min = [ D2, X, Y ] #----------------------------------------- print('Minimum Distance: ',round(D_min[0],2),' coordinates: (',D_min[1],D_min[2],')') print('Minimum Distance Squared: ',round(D2_min[0],2),' coordinates: (',D2_min[1],D2_min[2],')') xs = 0 ys = 0 for x, y in Data: xs += x ys += y xs /= len(Data) ys /= len(Data) print('Xc = ', xs, ' Yc = ', ys) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.axis([-0.2,8.2,-0.2,8.2]) #fig.show() colors = ['red','limegreen','deepskyblue','gold'] colors2 = ['darkred','darkgreen','darkblue','darkorange'] #-------------------------------------------------------- N = 240 k = 4 #-------------------------------------------------------- Data = oq.k_Data(k,N) for d in np.arange(len( Data )): ax.scatter( Data[d][0], Data[d][1], color='black', s=10 ) fig.canvas.draw() time.sleep(2) #-------------------------------------------------------- Centroids = oq.Initial_Centroids( k, Data ) Clusters = [] Clusters,old_Clusters = oq.Update_Clusters( Data, Centroids, Clusters ) for c1 in np.arange(len(Clusters)): for c2 in np.arange( len( Clusters[c1] ) ): ax.scatter( Clusters[c1][c2][0],Clusters[c1][c2][1], color=colors[c1],s=10 ) ax.scatter( Centroids[c1][0],Centroids[c1][1], color=colors2[c1], marker='x',s=50 ) fig.canvas.draw() time.sleep(1) time.sleep(2) #-------------------------------------------------------- terminate = False iters = 0 while( (terminate==False) and (iters<50) ): Centroids,old_Centroids = oq.Update_Centroids(Centroids, Clusters) Clusters,old_Clusters = oq.Update_Clusters( Data, Centroids, Clusters ) oq.Draw_Data( Clusters, Centroids, old_Centroids, fig, ax, colors, colors2 ) terminate = oq.Check_Termination( Clusters, old_Clusters ) iters = iters + 1 print( 'Clustering Complete: ',iters,' Iterations' ) #fig.show() a = QuantumRegister(1,name='a') q = QuantumRegister(2,name='q') qc= QuantumCircuit(a,q) qc.h( a[0] ) qc.x( q[1] ) print('____ Before CSWAP ____') oq.Wavefunction(qc, systems=[1,2]) qc.cswap( a[0], q[0], q[1] ) print('\n____ After CSWAP ____') oq.Wavefunction(qc, systems=[1,2]); q = QuantumRegister(3,name='q') c = ClassicalRegister(1,name='c') qc= QuantumCircuit(q,c,name='qc') qc.h( q[1] ) qc.x( q[2] ) qc.barrier() #------------------------------ The SWAP Test qc.h( q[0] ) qc.cswap( q[0], q[1], q[2] ) qc.h( q[0] ) qc.measure( q[0], c[0] ) #------------------------------- oq.Measurement( qc,shots=10000, ) print(' ') print(qc) a = QuantumRegister( 1, name='a' ) q1 = QuantumRegister( 2, name='q1' ) q2 = QuantumRegister( 2, name='q2' ) c = ClassicalRegister( 1, name='c' ) qc = QuantumCircuit( a, q1, q2, c ) #========================================= qc.h( q1[0] ) qc.h( q1[1] ) qc.x( q2[1] ) oq.Wavefunction( qc, systems=[1,2,2], show_systems=[False,True,True] ) qc.barrier() #-------------------------------- 2-Qubit SWAP Test qc.h( a[0] ) qc.cswap( a[0], q1[0], q2[0] ) qc.cswap( a[0], q1[1], q2[1] ) qc.h( a[0] ) qc.measure(a,c) #-------------------------------- print('\n___ Measurement Probabilities on the Control Qubit ___') oq.Measurement( qc, shots=8000 ) print(' ') print(qc) q = QuantumRegister(1) qc= QuantumCircuit(q) A = [ 3/5, 4/5 ] qc.initialize( A, [q[0]] ) oq.Wavefunction( qc ); print( qc.decompose().decompose().decompose() ) A = [1,0,-2,0] B = [6,-4,0,0] trials = 50000 #============================== A_norm = 0 B_norm = 0 D = 0 for i in np.arange(len(A)): A_norm = A_norm + A[i]**2 B_norm = B_norm + B[i]**2 D = D + (A[i]-B[i])**2 D = m.sqrt(D) A_norm = m.sqrt(A_norm) B_norm = m.sqrt(B_norm) Z = round( A_norm**2 + B_norm**2 ) #------------------------------ phi_vec = [A_norm/m.sqrt(Z),-B_norm/m.sqrt(Z)] psi_vec = [] for i in np.arange(len(A)): psi_vec.append( (A[i]/A_norm) /m.sqrt(2) ) psi_vec.append( (B[i]/B_norm) /m.sqrt(2) ) #============================== a = QuantumRegister(1,name='a') q = QuantumRegister(4,name='q') c = ClassicalRegister(1,name='c') qc= QuantumCircuit(a,q,c) qc.initialize( phi_vec, q[0] ) qc.initialize( psi_vec, q[1:4] ) #------------------------------ The SWAP Test qc.h( a[0] ) qc.cswap( a[0], q[0], q[1] ) qc.h( a[0] ) qc.measure(a,c) #------------------------------ M = oq.Measurement(qc,shots=trials,return_M=True,print_M=False) print('Euclidean Distance: ',round(D,4)) print('\n DistCalc Distance: ',round( m.sqrt((((M['0']/trials - 0.5)/0.5)*2*Z)),4) ); Shots = 10000 Points = [ [-1,1], [3,4], [7,7], [6,8] ] Norm_Points = [] for p in np.arange( len(Points) ): Norm_Points.append( Points[p]/np.linalg.norm(Points[p]) ) #================================================== for p2 in np.arange( len(Norm_Points)-1 ): q = QuantumRegister(3) c = ClassicalRegister(1) qc= QuantumCircuit(q,c) qc.initialize( Norm_Points[int(p2)], [q[1]] ) qc.initialize( Norm_Points[-1], [q[2]] ) #-------------------------------------------------- IP = oq.SWAP_Test( qc, q[0], q[1], q[2], c[0], Shots ) print('\nComparing Points: ',Points[p2],' & ',Points[-1],'\n',IP,'|0> ',Shots-IP,'|1>') Shots = 10000 Points = [ [2,3], [4,6], [8,12], [12,18] ] Norm_Points = [] for p in np.arange( len(Points) ): Norm_Points.append( Points[p]/np.linalg.norm(Points[p]) ) #================================================== for p2 in np.arange( len(Norm_Points)-1 ): q = QuantumRegister(3) c = ClassicalRegister(1) qc= QuantumCircuit(q,c) qc.initialize( Norm_Points[int(p2)], [q[1]] ) qc.initialize( Norm_Points[-1], [q[2]] ) #-------------------------------------------------- IP = oq.SWAP_Test( qc, q[0], q[1], q[2], c[0], Shots ) print('\nComparing Points: ',Points[p2],' & ',Points[-1],'\n',IP,'|0> ',Shots-IP,'|1>') Point = [ 0.12, -0.15 ] Centroids = [ [-0.38,0.61] , [-0.09,-0.34] , [0.52,0.29] ] #----------------------- fig = plt.figure(figsize=(4,4)) ax = fig.add_subplot(1,1,1) ax.axis([-1,1,-1,1]) #fig.show() #----------------------- plt.plot(Point[0], Point[1], 'ro') markers = ['gx','bx','kx'] for c in np.arange( len(Centroids) ): plt.plot(Centroids[c][0], Centroids[c][1], markers[c]) fig.canvas.draw() Shots = 10000 Point = [ 0.12, -0.15 ] Centroids = [ [-0.38,0.61] , [-0.09,-0.34] , [0.52,0.29] ] Bloch_Point = [ (Point[0]+1)*m.pi/2, (Point[1]+1)*m.pi/2 ] Bloch_Cents = [] for c in np.arange( len(Centroids) ): Bloch_Cents.append( [ (Centroids[c][0]+1)*m.pi/2, (Centroids[c][1]+1)*m.pi/2 ] ) #==================================== colors = ['Green','Blue','Black'] for c2 in np.arange( len(Bloch_Cents) ): q = QuantumRegister(3) c = ClassicalRegister(1) qc= QuantumCircuit(q,c) qc.u( Bloch_Point[0], Bloch_Point[1], 0, [q[1]] ) qc.u( Bloch_Cents[c2][0], Bloch_Cents[c2][1], 0, [q[2]] ) #-------------------------------------------------- IP = oq.SWAP_Test( qc, q[0], q[1], q[2], c[0], Shots ) print('\n\nComparing Points: ',Centroids[c2],' & ',Point,' (',colors[c2],' Centroid )\n\n',IP,'|0> ',Shots-IP,'|1>' ) size = 100 Shots = 10000 Data_Space = [-1,1,-1,1] Point = [0.12,-0.15] # Example Point #Point = [-0.6,0.] #Point = [0,-0.6] #Point = [-0.9,0.] #Point = [0,-0.9] t = (Point[0]+1)*m.pi/2 p = (Point[1]+1)*m.pi/2 OL_grid = np.zeros(shape=(size,size)) #======================================================== for x in np.arange(size): t2 = (( (-1 + 2*(x/size)) + 1) * m.pi / 2) for y in np.arange(size): p2 = (( (-1 + 2*(y/size)) + 1) * m.pi / 2) #--------------------------------- q = QuantumRegister( 3, name='q' ) c = ClassicalRegister( 1, name='c' ) qc= QuantumCircuit( q,c, name='qc' ) qc.u( t, p, 0, q[1] ) qc.u( t2, p2, 0, q[2] ) #--------------------------------- IP = oq.SWAP_Test( qc, q[0], q[1], q[2], c[0], Shots ) if( IP < 5000 ): IP = 5000 OL_grid[int(size-y-1),int(x)] = m.sqrt((1.0*IP/Shots-0.5)*2) #======================================================== fig, ax = plt.subplots() show_ticks = False show_text = False oq.Heatmap(OL_grid, show_text, show_ticks, ax, "viridis", "Inner Product") plt.plot((Point[0]+1)*size/2, size-(((Point[1]+1))*size/2), 'ro') Centroids = [ [-0.38,0.61] , [-0.09,-0.34] , [0.52,0.29] ] colors = ['green','blue','black'] for c in np.arange(len(Centroids)): plt.scatter((Centroids[c][0]+1)*size/2, size-((Centroids[c][1]+1)*size/2), color='white', marker='s', s=50) plt.scatter((Centroids[c][0]+1)*size/2, size-((Centroids[c][1]+1)*size/2), color=colors[c], marker='x', s=50) fig.tight_layout() #plt.show() Shots = 10000 Point = [2*random.random()-1,2*random.random()-1] t = (Point[0]+1)*m.pi/2 p = (Point[1]+1)*m.pi/2 #======================================================== q = QuantumRegister( 3, name='q' ) c = ClassicalRegister( 1, name='c' ) qc= QuantumCircuit( q,c, name='qc' ) qc.u( t, p, 0, q[1] ) qc.u( m.pi-t, p+m.pi, 0, q[2] ) #--------------------------------- IP = oq.SWAP_Test( qc, q[0], q[1], q[2], c[0], Shots ) print('Inner Product Result Bewteen: [',round(t,3),' ,',round(p,3),'] & [',round(m.pi-t,3),' ,',round(p+m.pi,3),'] (θ,Φ) & (π-θ,π+Φ)') print('\n',IP,' |0>') size = 100 #------------------------------------------------------- Data_Space = [-1,1,-1,1] Point = [0.12,-0.15] # Example Point t,p = oq.Bloch_State( Point, Data_Space ) #------------------------------------------------------- OL_grid = np.zeros(shape=(size,size)) #======================================================== for x in np.arange(size): Xp = Data_Space[0] + (x/size)*(Data_Space[1]-Data_Space[0]) for y in np.arange(size): Yp = Data_Space[2] + (y/size)*(Data_Space[3]-Data_Space[2]) t2,p2 = oq.Bloch_State( [Xp,Yp], Data_Space ) #----------------------------- q = QuantumRegister( 3, name='q' ) c = ClassicalRegister( 1, name='c' ) qc= QuantumCircuit( q,c, name='qc' ) qc.u( t, p, 0, q[1] ) qc.u( t2, p2, 0, q[2] ) #------------- IP = oq.SWAP_Test( qc, q[0], q[1], q[2], c[0], Shots ) if( IP < 5000 ): IP = 5000 OL_grid[int(size-y-1),int(x)] = m.sqrt((1.0*IP/Shots-0.5)*2) #======================================================== fig, ax = plt.subplots() show_ticks = False show_text = False oq.Heatmap(OL_grid, show_text, show_ticks, ax, "viridis", "Inner Product") plt.plot((Point[0]-Data_Space[0])*size/(Data_Space[1]-Data_Space[0]), (Data_Space[3]-Point[1])*size/(Data_Space[3]-Data_Space[2]), 'ro') Centroids = [ [-0.38,0.61] , [-0.09,-0.34] , [0.52,0.29] ] colors = ['green','blue','black'] for c in np.arange(len(Centroids)): plt.scatter((Centroids[c][0]+1)*size/2, size-((Centroids[c][1]+1)*size/2), color='white', marker='s', s=50) plt.scatter((Centroids[c][0]+1)*size/2, size-((Centroids[c][1]+1)*size/2), color=colors[c], marker='x', s=50) fig.tight_layout() plt.show() fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.axis([-0.2,8.2,-0.2,8.2]) #fig.show() colors = ['red','limegreen','deepskyblue','gold'] colors2 = ['darkred','darkgreen','darkblue','darkorange'] #-------------------------------------------------------- n = 140 k = 4 shots = 500 Data_Space = [0,8,0,8] #-------------------------------------------------------- Data = oq.k_Data(k,n) for d in np.arange(len( Data )): ax.scatter( Data[d][0], Data[d][1], color='black', s=10 ) fig.canvas.draw() time.sleep(2) #-------------------------------------------------------- Centroids = oq.Initial_Centroids( k, Data ) Clusters = [] Clusters,old_Clusters = oq.Q_Update_Clusters( Data, Centroids, Clusters, Data_Space, shots ) for c1 in np.arange(len(Clusters)): for c2 in np.arange( len( Clusters[c1] ) ): ax.scatter( Clusters[c1][c2][0],Clusters[c1][c2][1], color=colors[c1],s=10 ) ax.scatter( Centroids[c1][0],Centroids[c1][1], color=colors2[c1], marker='x',s=50 ) fig.canvas.draw() time.sleep(1) time.sleep(2) #-------------------------------------------------------- terminate = False iters = 0 while( (terminate==False) and (iters<50) ): Centroids,old_Centroids = oq.Update_Centroids(Centroids, Clusters) Clusters,old_Clusters = oq.Q_Update_Clusters( Data, Centroids, Clusters, Data_Space, shots ) oq.Draw_Data( Clusters, Centroids, old_Centroids, fig, ax, colors, colors2 ) terminate = oq.Check_Termination( Clusters, old_Clusters ) iters = iters + 1 print( 'Clustering Complete: ',iters,' Iterations' )
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
import numpy as np import math from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QiskitError from qiskit.compiler import assemble from qiskit.providers.aer import QasmSimulator from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.synthesis import two_qubit_cnot_decompose class QuantumFourierTransformFusionSuite: def __init__(self): self.timeout = 60 * 20 self.backend = QasmSimulator() num_qubits = [5, 10, 15, 20, 25] self.circuit = {} for num_qubit in num_qubits: for use_cu1 in [True, False]: circuit = self.qft_circuit(num_qubit, use_cu1) self.circuit[(num_qubit, use_cu1)] = assemble(circuit, self.backend, shots=1) self.param_names = ["Quantum Fourier Transform", "Fusion Activated", "Use cu1 gate"] self.params = (num_qubits, [True, False], [True, False]) @staticmethod def qft_circuit(num_qubit, use_cu1): qreg = QuantumRegister(num_qubit,"q") creg = ClassicalRegister(num_qubit, "c") circuit = QuantumCircuit(qreg, creg) for i in range(num_qubit): circuit.h(qreg[i]) for i in range(num_qubit): for j in range(i): l = math.pi/float(2**(i-j)) if use_cu1: circuit.cu1(l, qreg[i], qreg[j]) else: circuit.u1(l/2, qreg[i]) circuit.cx(qreg[i], qreg[j]) circuit.u1(-l/2, qreg[j]) circuit.cx(qreg[i], qreg[j]) circuit.u1(l/2, qreg[j]) circuit.h(qreg[i]) circuit.barrier() for i in range(num_qubit): circuit.measure(qreg[i], creg[i]) return circuit def time_quantum_fourier_transform(self, num_qubit, fusion_enable, use_cu1): """ Benchmark QFT """ result = self.backend.run(self.circuit[(num_qubit, use_cu1)], fusion_enable=fusion_enable).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status) class RandomFusionSuite: def __init__(self): self.timeout = 60 * 20 self.backend = QasmSimulator() self.param_names = ["Number of Qubits", "Fusion Activated"] self.params = ([5, 10, 15, 20, 25], [True, False]) @staticmethod def build_model_circuit_kak(width, depth, seed=None): """Create quantum volume model circuit on quantum register qreg of given depth (default depth is equal to width) and random seed. The model circuits consist of layers of Haar random elements of U(4) applied between corresponding pairs of qubits in a random bipartition. """ qreg = QuantumRegister(width) depth = depth or width np.random.seed(seed) circuit = QuantumCircuit(qreg, name="Qvolume: %s by %s, seed: %s" % (width, depth, seed)) for _ in range(depth): # Generate uniformly random permutation Pj of [0...n-1] perm = np.random.permutation(width) # For each pair p in Pj, generate Haar random U(4) # Decompose each U(4) into CNOT + SU(2) for k in range(width // 2): U = random_unitary(4, seed).data for gate in two_qubit_cnot_decompose(U): qs = [qreg[int(perm[2 * k + i.index])] for i in gate[1]] pars = gate[0].params name = gate[0].name if name == "cx": circuit.cx(qs[0], qs[1]) elif name == "u1": circuit.u1(pars[0], qs[0]) elif name == "u2": circuit.u2(*pars[:2], qs[0]) elif name == "u3": circuit.u3(*pars[:3], qs[0]) elif name == "id": pass # do nothing else: raise Exception("Unexpected gate name: %s" % name) return circuit def time_random_transform(self, num_qubits, fusion_enable): circ = self.build_model_circuit_kak(num_qubits, num_qubits, 1) qobj = assemble(circ) result = self.backend.run(qobj, fusion_enable=fusion_enable).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Width pass testing""" import unittest from qiskit import QuantumCircuit, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import Width from qiskit.test import QiskitTestCase class TestWidthPass(QiskitTestCase): """Tests for Depth analysis methods.""" def test_empty_dag(self): """Empty DAG has 0 depth""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = Width() _ = pass_.run(dag) self.assertEqual(pass_.property_set["width"], 0) def test_just_qubits(self): """A dag with 8 operations and no classic bits""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = Width() _ = pass_.run(dag) self.assertEqual(pass_.property_set["width"], 2) if __name__ == "__main__": unittest.main()
https://github.com/apozas/qaoa-color
apozas
import qiskit qiskit.__version__ from functools import reduce from itertools import product from qiskit import BasicAer, QuantumRegister from qiskit_aqua import QuantumInstance from qiskit_aqua import Operator, run_algorithm from qiskit.quantum_info import Pauli from qiskit_aqua.components.optimizers import COBYLA from qiskit_aqua.components.initial_states import Custom from constrainedqaoa import constrainedQAOA import numpy as np import qutip as qt edges = [(0, 1), (1, 2), (2, 3)] vertices = 4 colors = 2 n_qubits = vertices * colors zr = np.zeros(n_qubits) ws = np.eye(n_qubits) up = qt.basis(2, 0) dn = qt.basis(2, 1) reduce( lambda x, y: x + y, [list(edge) for edge in edges]) def W(size, copies): initial_list = [dn] + [up] * (size - 1) cycles = [[initial_list[i - j] for i in range(size)] for j in range(size)] W_1copy = sum([qt.tensor(states) for states in cycles]) return qt.tensor([W_1copy] * copies) amplitudes = W(colors, vertices).full().T.tolist()[0] init_state = Custom(n_qubits, state_vector=amplitudes) W(colors, vertices) cost_operator = reduce( lambda x, y: x + y, [ Operator([[1, (Pauli(ws[colors*v1 + j, :], zr) *Pauli(ws[colors*v2 + j, :], zr))]]) for (v1, v2), j in product(edges, range(colors)) ] ) mixer_operator = reduce( lambda x, y: x + y, [ Operator([[1, (Pauli(zr, ws[colors*i + j, :]) *Pauli(zr, ws[colors*i + (j+1) % colors, :]))]]) + Operator([[1, (Pauli(ws[colors*i + j % colors, :], ws[colors*i + j % colors, :]) *Pauli(ws[colors*i + (j+1) % colors, :], ws[colors*i + (j+1) % colors, :]))]]) for i, j in product(range(vertices), range(colors)) ] ) # Fix redundancies if colors == 2: mixer_operator.scaling_coeff(1/2) cobyla = COBYLA() cobyla.set_options(maxiter=250) p = 2 # steps of QAOA constrained = constrainedQAOA(cost_operator, cobyla, mixer_operator, p, init_state) from qiskit import BasicAer backend = BasicAer.get_backend('statevector_simulator') seed = 50 constrained.random_seed = seed quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_mapper=seed) result = constrained.run(quantum_instance) result['eigvals'] np.round(result['eigvecs'], 4) result['eval_count']
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np # useful math functions from math import pi, cos, acos, sqrt import random # importing the QISKit from qiskit import QuantumProgram import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram Q_program = QuantumProgram() Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url N = 4 # Creating registers qr = Q_program.create_quantum_register("qr", N) # for recording the measurement on qr cr = Q_program.create_classical_register("cr", N) circuitName = "sharedEntangled" sharedEntangled = Q_program.create_circuit(circuitName, [qr], [cr]) #Create uniform superposition of all strings of length 2 for i in range(2): sharedEntangled.h(qr[i]) #The amplitude is minus if there are odd number of 1s for i in range(2): sharedEntangled.z(qr[i]) #Copy the content of the fist two qubits to the last two qubits for i in range(2): sharedEntangled.cx(qr[i], qr[i+2]) #Flip the last two qubits for i in range(2,4): sharedEntangled.x(qr[i]) #we first define controlled-u gates required to assign phases from math import pi def ch(qProg, a, b): """ Controlled-Hadamard gate """ qProg.h(b) qProg.sdg(b) qProg.cx(a, b) qProg.h(b) qProg.t(b) qProg.cx(a, b) qProg.t(b) qProg.h(b) qProg.s(b) qProg.x(b) qProg.s(a) return qProg def cu1pi2(qProg, c, t): """ Controlled-u1(phi/2) gate """ qProg.u1(pi/4.0, c) qProg.cx(c, t) qProg.u1(-pi/4.0, t) qProg.cx(c, t) qProg.u1(pi/4.0, t) return qProg def cu3pi2(qProg, c, t): """ Controlled-u3(pi/2, -pi/2, pi/2) gate """ qProg.u1(pi/2.0, t) qProg.cx(c, t) qProg.u3(-pi/4.0, 0, 0, t) qProg.cx(c, t) qProg.u3(pi/4.0, -pi/2.0, 0, t) return qProg # dictionary for Alice's operations/circuits aliceCircuits = {} # Quantum circuits for Alice when receiving idx in 1, 2, 3 for idx in range(1, 4): circuitName = "Alice"+str(idx) aliceCircuits[circuitName] = Q_program.create_circuit(circuitName, [qr], [cr]) theCircuit = aliceCircuits[circuitName] if idx == 1: #the circuit of A_1 theCircuit.x(qr[1]) theCircuit.cx(qr[1], qr[0]) theCircuit = cu1pi2(theCircuit, qr[1], qr[0]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit = cu1pi2(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit = cu1pi2(theCircuit, qr[0], qr[1]) theCircuit = cu3pi2(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit = ch(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit.cx(qr[1], qr[0]) theCircuit.x(qr[1]) elif idx == 2: theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit = cu1pi2(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit = cu1pi2(theCircuit, qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit.h(qr[0]) theCircuit.h(qr[1]) elif idx == 3: theCircuit.cz(qr[0], qr[1]) theCircuit.swap(qr[0], qr[1]) theCircuit.h(qr[0]) theCircuit.h(qr[1]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) theCircuit.cz(qr[0], qr[1]) theCircuit.x(qr[0]) theCircuit.x(qr[1]) #measure the first two qubits in the computational basis theCircuit.measure(qr[0], cr[0]) theCircuit.measure(qr[1], cr[1]) # dictionary for Bob's operations/circuits bobCircuits = {} # Quantum circuits for Bob when receiving idx in 1, 2, 3 for idx in range(1,4): circuitName = "Bob"+str(idx) bobCircuits[circuitName] = Q_program.create_circuit(circuitName, [qr], [cr]) theCircuit = bobCircuits[circuitName] if idx == 1: theCircuit.x(qr[2]) theCircuit.x(qr[3]) theCircuit.cz(qr[2], qr[3]) theCircuit.x(qr[3]) theCircuit.u1(pi/2.0, qr[2]) theCircuit.x(qr[2]) theCircuit.z(qr[2]) theCircuit.cx(qr[2], qr[3]) theCircuit.cx(qr[3], qr[2]) theCircuit.h(qr[2]) theCircuit.h(qr[3]) theCircuit.x(qr[3]) theCircuit = cu1pi2(theCircuit, qr[2], qr[3]) theCircuit.x(qr[2]) theCircuit.cz(qr[2], qr[3]) theCircuit.x(qr[2]) theCircuit.x(qr[3]) elif idx == 2: theCircuit.x(qr[2]) theCircuit.x(qr[3]) theCircuit.cz(qr[2], qr[3]) theCircuit.x(qr[3]) theCircuit.u1(pi/2.0, qr[3]) theCircuit.cx(qr[2], qr[3]) theCircuit.h(qr[2]) theCircuit.h(qr[3]) elif idx == 3: theCircuit.cx(qr[3], qr[2]) theCircuit.x(qr[3]) theCircuit.h(qr[3]) #measure the third and fourth qubits in the computational basis theCircuit.measure(qr[2], cr[2]) theCircuit.measure(qr[3], cr[3]) a, b = random.randint(1,3), random.randint(1,3) #generate random integers print("The values of a and b are, resp.,", a,b) aliceCircuit = aliceCircuits["Alice"+str(a)] bobCircuit = bobCircuits["Bob"+str(b)] circuitName = "Alice"+str(a)+"Bob"+str(b) Q_program.add_circuit(circuitName, sharedEntangled+aliceCircuit+bobCircuit) backend = "local_qasm_simulator" ##backend = "ibmqx2" shots = 1 # We perform a one-shot experiment results = Q_program.execute([circuitName], backend=backend, shots=shots) answer = results.get_counts(circuitName) print(answer) for key in answer.keys(): aliceAnswer = [int(key[-1]), int(key[-2])] bobAnswer = [int(key[-3]), int(key[-4])] if sum(aliceAnswer) % 2 == 0:#the sume of Alice answer must be even aliceAnswer.append(0) else: aliceAnswer.append(1) if sum(bobAnswer) % 2 == 1:#the sum of Bob answer must be odd bobAnswer.append(0) else: bobAnswer.append(1) break print("Alice answer for a = ", a, "is", aliceAnswer) print("Bob answer for b = ", b, "is", bobAnswer) if(aliceAnswer[b-1] != bobAnswer[a-1]): #check if the intersection of their answers is the same print("Alice and Bob lost") else: print("Alice and Bob won") backend = "local_qasm_simulator" #backend = "ibmqx2" shots = 10 # We perform 10 shots of experiments for each round nWins = 0 nLost = 0 for a in range(1,4): for b in range(1,4): print("Asking Alice and Bob with a and b are, resp.,", a,b) rWins = 0 rLost = 0 aliceCircuit = aliceCircuits["Alice"+str(a)] bobCircuit = bobCircuits["Bob"+str(b)] circuitName = "Alice"+str(a)+"Bob"+str(b) Q_program.add_circuit(circuitName, sharedEntangled+aliceCircuit+bobCircuit) if backend == "ibmqx2": ibmqx2_backend = Q_program.get_backend_configuration('ibmqx2') ibmqx2_coupling = ibmqx2_backend['coupling_map'] results = Q_program.execute([circuitName], backend=backend, shots=shots, coupling_map=ibmqx2_coupling, max_credits=3, wait=10, timeout=240) else: results = Q_program.execute([circuitName], backend=backend, shots=shots) answer = results.get_counts(circuitName) for key in answer.keys(): kfreq = answer[key] #frequencies of keys obtained from measurements aliceAnswer = [int(key[-1]), int(key[-2])] bobAnswer = [int(key[-3]), int(key[-4])] if sum(aliceAnswer) % 2 == 0: aliceAnswer.append(0) else: aliceAnswer.append(1) if sum(bobAnswer) % 2 == 1: bobAnswer.append(0) else: bobAnswer.append(1) #print("Alice answer for a = ", a, "is", aliceAnswer) #print("Bob answer for b = ", b, "is", bobAnswer) if(aliceAnswer[b-1] != bobAnswer[a-1]): #print(a, b, "Alice and Bob lost") nLost += kfreq rLost += kfreq else: #print(a, b, "Alice and Bob won") nWins += kfreq rWins += kfreq print("\t#wins = ", rWins, "out of ", shots, "shots") print("Number of Games = ", nWins+nLost) print("Number of Wins = ", nWins) print("Winning probabilities = ", (nWins*100.0)/(nWins+nLost))
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ from qiskit import QuantumCircuit, Aer, execute from IPython.core.display import display from qiskit.tools.visualization import plot_histogram print("Ch 9: Grover with ancilla qubits") print("--------------------------------") # Create 3 qubit circuit with two classical bits qc=QuantumCircuit(3,2) qc.h([0,1]) qc.x(2) # Code for the oracle qc.barrier([0,1,2]) qc.x(0) qc.barrier([0,1,2]) # Phase kickback using the ancilla qubit qc.h(2) qc.ccx(0,1,2) qc.h(2) # End code for the oracle qc.barrier([0,1,2]) qc.x(0) qc.barrier([0,1,2]) # Amplifier qc.h([0,1]) qc.x([0,1]) qc.h(1) qc.cx(0,1) qc.h(1) qc.barrier([0,1,2]) qc.x([0,1]) qc.h([0,1]) # Measure two qubits qc.measure([0,1],[0,1]) # Display circuit and execute on simulator display(qc.draw('mpl')) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1) result = job.result() counts = result.get_counts(qc) display(plot_histogram(counts))
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. """Test the SabreLayout pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes import SabreLayout from qiskit.transpiler.exceptions import TranspilerError from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.compiler.transpiler import transpile from qiskit.providers.fake_provider import FakeAlmaden, FakeAlmadenV2 from qiskit.providers.fake_provider import FakeKolkata from qiskit.providers.fake_provider import FakeMontreal class TestSabreLayout(QiskitTestCase): """Tests the SabreLayout pass""" def setUp(self): super().setUp() self.cmap20 = FakeAlmaden().configuration().coupling_map def test_5q_circuit_20q_coupling(self): """Test finds layout for 5q circuit on 20q device.""" # ┌───┐ # q_0: ──■───────┤ X ├─────────────── # │ └─┬─┘┌───┐ # q_1: ──┼────■────┼──┤ X ├───────■── # ┌─┴─┐ │ │ ├───┤┌───┐┌─┴─┐ # q_2: ┤ X ├──┼────┼──┤ X ├┤ X ├┤ X ├ # └───┘┌─┴─┐ │ └───┘└─┬─┘└───┘ # q_3: ─────┤ X ├──■─────────┼─────── # └───┘ │ # q_4: ──────────────────────■─────── qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[2]) circuit.cx(qr[1], qr[3]) circuit.cx(qr[3], qr[0]) circuit.x(qr[2]) circuit.cx(qr[4], qr[2]) circuit.x(qr[1]) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) pass_ = SabreLayout(CouplingMap(self.cmap20), seed=0, swap_trials=32, layout_trials=32) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual([layout[q] for q in circuit.qubits], [18, 11, 13, 12, 14]) def test_6q_circuit_20q_coupling(self): """Test finds layout for 6q circuit on 20q device.""" # ┌───┐┌───┐┌───┐┌───┐┌───┐ # q0_0: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├ # └─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘ # q0_1: ──┼────■────┼────┼────┼── # │ ┌───┐ │ │ │ # q0_2: ──┼──┤ X ├──┼────■────┼── # │ └───┘ │ │ # q1_0: ──■─────────┼─────────┼── # ┌───┐ │ │ # q1_1: ─────┤ X ├──┼─────────■── # └───┘ │ # q1_2: ────────────■──────────── qr0 = QuantumRegister(3, "q0") qr1 = QuantumRegister(3, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr1[0], qr0[0]) circuit.cx(qr0[1], qr0[0]) circuit.cx(qr1[2], qr0[0]) circuit.x(qr0[2]) circuit.cx(qr0[2], qr0[0]) circuit.x(qr1[1]) circuit.cx(qr1[1], qr0[0]) dag = circuit_to_dag(circuit) pass_ = SabreLayout(CouplingMap(self.cmap20), seed=0, swap_trials=32, layout_trials=32) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual([layout[q] for q in circuit.qubits], [7, 8, 12, 6, 11, 13]) def test_6q_circuit_20q_coupling_with_target(self): """Test finds layout for 6q circuit on 20q device.""" # ┌───┐┌───┐┌───┐┌───┐┌───┐ # q0_0: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├ # └─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘ # q0_1: ──┼────■────┼────┼────┼── # │ ┌───┐ │ │ │ # q0_2: ──┼──┤ X ├──┼────■────┼── # │ └───┘ │ │ # q1_0: ──■─────────┼─────────┼── # ┌───┐ │ │ # q1_1: ─────┤ X ├──┼─────────■── # └───┘ │ # q1_2: ────────────■──────────── qr0 = QuantumRegister(3, "q0") qr1 = QuantumRegister(3, "q1") circuit = QuantumCircuit(qr0, qr1) circuit.cx(qr1[0], qr0[0]) circuit.cx(qr0[1], qr0[0]) circuit.cx(qr1[2], qr0[0]) circuit.x(qr0[2]) circuit.cx(qr0[2], qr0[0]) circuit.x(qr1[1]) circuit.cx(qr1[1], qr0[0]) dag = circuit_to_dag(circuit) target = FakeAlmadenV2().target pass_ = SabreLayout(target, seed=0, swap_trials=32, layout_trials=32) pass_.run(dag) layout = pass_.property_set["layout"] self.assertEqual([layout[q] for q in circuit.qubits], [7, 8, 12, 6, 11, 13]) def test_layout_with_classical_bits(self): """Test sabre layout with classical bits recreate from issue #8635.""" qc = QuantumCircuit.from_qasm_str( """ OPENQASM 2.0; include "qelib1.inc"; qreg q4833[1]; qreg q4834[6]; qreg q4835[7]; creg c982[2]; creg c983[2]; creg c984[2]; rzz(0) q4833[0],q4834[4]; cu(0,-6.1035156e-05,0,1e-05) q4834[1],q4835[2]; swap q4834[0],q4834[2]; cu(-1.1920929e-07,0,-0.33333333,0) q4833[0],q4834[2]; ccx q4835[2],q4834[5],q4835[4]; measure q4835[4] -> c984[0]; ccx q4835[2],q4835[5],q4833[0]; measure q4835[5] -> c984[1]; measure q4834[0] -> c982[1]; u(10*pi,0,1.9) q4834[5]; measure q4834[3] -> c984[1]; measure q4835[0] -> c982[0]; rz(0) q4835[1]; """ ) res = transpile(qc, FakeKolkata(), layout_method="sabre", seed_transpiler=1234) self.assertIsInstance(res, QuantumCircuit) layout = res._layout.initial_layout self.assertEqual( [layout[q] for q in qc.qubits], [13, 10, 11, 12, 17, 14, 22, 26, 5, 16, 25, 19, 7, 8] ) # pylint: disable=line-too-long def test_layout_many_search_trials(self): """Test recreate failure from randomized testing that overflowed.""" qc = QuantumCircuit.from_qasm_str( """ OPENQASM 2.0; include "qelib1.inc"; qreg q18585[14]; creg c1423[5]; creg c1424[4]; creg c1425[3]; barrier q18585[4],q18585[5],q18585[12],q18585[1]; cz q18585[11],q18585[3]; cswap q18585[8],q18585[10],q18585[6]; u(-2.00001,6.1035156e-05,-1.9) q18585[2]; barrier q18585[3],q18585[6],q18585[5],q18585[8],q18585[10],q18585[9],q18585[11],q18585[2],q18585[12],q18585[7],q18585[13],q18585[4],q18585[0],q18585[1]; cp(0) q18585[2],q18585[4]; cu(-0.99999,0,0,0) q18585[7],q18585[1]; cu(0,0,0,2.1507119) q18585[6],q18585[3]; barrier q18585[13],q18585[0],q18585[12],q18585[3],q18585[2],q18585[10]; ry(-1.1044662) q18585[13]; barrier q18585[13]; id q18585[12]; barrier q18585[12],q18585[6]; cu(-1.9,1.9,-1.5,0) q18585[10],q18585[0]; barrier q18585[13]; id q18585[8]; barrier q18585[12]; barrier q18585[12],q18585[1],q18585[9]; sdg q18585[2]; rz(-10*pi) q18585[6]; u(0,27.566433,1.9) q18585[1]; barrier q18585[12],q18585[11],q18585[9],q18585[4],q18585[7],q18585[0],q18585[13],q18585[3]; cu(-0.99999,-5.9604645e-08,-0.5,2.00001) q18585[3],q18585[13]; rx(-5.9604645e-08) q18585[7]; p(1.1) q18585[13]; barrier q18585[12],q18585[13],q18585[10],q18585[9],q18585[7],q18585[4]; z q18585[10]; measure q18585[7] -> c1423[2]; barrier q18585[0],q18585[3],q18585[7],q18585[4],q18585[1],q18585[8],q18585[6],q18585[11],q18585[5]; barrier q18585[5],q18585[2],q18585[8],q18585[3],q18585[6]; """ ) res = transpile( qc, FakeMontreal(), layout_method="sabre", routing_method="stochastic", seed_transpiler=12345, ) self.assertIsInstance(res, QuantumCircuit) layout = res._layout.initial_layout self.assertEqual( [layout[q] for q in qc.qubits], [7, 19, 14, 18, 10, 6, 12, 16, 13, 20, 15, 21, 1, 17] ) class TestDisjointDeviceSabreLayout(QiskitTestCase): """Test SabreLayout with a disjoint coupling map.""" def setUp(self): super().setUp() self.dual_grid_cmap = CouplingMap( [[0, 1], [0, 2], [1, 3], [2, 3], [4, 5], [4, 6], [5, 7], [5, 8]] ) def test_dual_ghz(self): """Test a basic example with 2 circuit components and 2 cmap components.""" qc = QuantumCircuit(8, name="double dhz") qc.h(0) qc.cz(0, 1) qc.cz(0, 2) qc.h(3) qc.cx(3, 4) qc.cx(3, 5) qc.cx(3, 6) qc.cx(3, 7) layout_routing_pass = SabreLayout( self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1 ) layout_routing_pass(qc) layout = layout_routing_pass.property_set["layout"] self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8]) def test_dual_ghz_with_wide_barrier(self): """Test a basic example with 2 circuit components and 2 cmap components.""" qc = QuantumCircuit(8, name="double dhz") qc.h(0) qc.cz(0, 1) qc.cz(0, 2) qc.h(3) qc.cx(3, 4) qc.cx(3, 5) qc.cx(3, 6) qc.cx(3, 7) qc.measure_all() layout_routing_pass = SabreLayout( self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1 ) layout_routing_pass(qc) layout = layout_routing_pass.property_set["layout"] self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8]) def test_dual_ghz_with_intermediate_barriers(self): """Test dual ghz circuit with intermediate barriers local to each componennt.""" qc = QuantumCircuit(8, name="double dhz") qc.h(0) qc.cz(0, 1) qc.cz(0, 2) qc.barrier(0, 1, 2) qc.h(3) qc.cx(3, 4) qc.cx(3, 5) qc.barrier(4, 5, 6) qc.cx(3, 6) qc.cx(3, 7) qc.measure_all() layout_routing_pass = SabreLayout( self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1 ) layout_routing_pass(qc) layout = layout_routing_pass.property_set["layout"] self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8]) def test_dual_ghz_with_intermediate_spanning_barriers(self): """Test dual ghz circuit with barrier in the middle across components.""" qc = QuantumCircuit(8, name="double dhz") qc.h(0) qc.cz(0, 1) qc.cz(0, 2) qc.barrier(0, 1, 2, 4, 5) qc.h(3) qc.cx(3, 4) qc.cx(3, 5) qc.cx(3, 6) qc.cx(3, 7) qc.measure_all() layout_routing_pass = SabreLayout( self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1 ) layout_routing_pass(qc) layout = layout_routing_pass.property_set["layout"] self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8]) def test_too_large_components(self): """Assert trying to run a circuit with too large a connected component raises.""" qc = QuantumCircuit(8) qc.h(0) for i in range(1, 6): qc.cx(0, i) qc.h(7) qc.cx(7, 6) layout_routing_pass = SabreLayout( self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1 ) with self.assertRaises(TranspilerError): layout_routing_pass(qc) if __name__ == "__main__": unittest.main()
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/magn5452/QiskitQaoa
magn5452
from qiskit import Aer from qiskit import QuantumCircuit from VehicleRouting.standard.CostCalculator import CostCalculator def maxcut_obj(x, G): """ Given a bitstring as a solution, this function returns the number of edges shared between the two partitions of the graph. Args: x: str solution bitstring G: networkx graph Returns: obj: float Objective """ obj = 0 for i, j in G.couplings(): if x[i] != x[j]: obj -= 1 return obj def compute_expectation(counts, G): """ Computes expectation value based on measurement results Args: counts: dict key as bitstring, val as count G: networkx graph Returns: avg: float expectation value """ avg = 0 sum_count = 0 for bitstring, count in counts.items(): obj = maxcut_obj(bitstring, G) avg += obj * count sum_count += count return avg / sum_count # We will also bring the different circuit components that # build the qaoa circuit under a single function def create_qaoa_circuit(graph, theta): """ Creates a parametrized qaoa circuit Args: graph: networkx graph theta: list unitary parameters Returns: qc: qiskit circuit """ nqubits = len(graph.nodes()) p = len(theta) // 2 # number of alternating unitaries qc = QuantumCircuit(nqubits) beta = theta[:p] gamma = theta[p:] # initial_state for i in range(0, nqubits): qc.h(i) for irep in range(0, p): # problem unitary for pair in list(graph.couplings()): qc.rzz(2 * gamma[irep], pair[0], pair[1]) qc.barrier() # mixer unitary for i in range(0, nqubits): qc.rx(2 * beta[irep], i) qc.measure_all() return qc # Finally we write a function that executes the circuit on the chosen backend def get_expectation(graph, p, shots=512): """ Runs parametrized circuit Args: graph: networkx graph p: int, Number of repetitions of unitaries """ backend = Aer.get_backend('qasm_simulator') backend.shots = shots def execute_circ(theta): qc = create_qaoa_circuit(graph, theta) counts = backend.run(qc, seed_simulator=10, nshots=512).result().get_counts() return compute_expectation(counts, graph) return execute_circ # Finally we write a function that executes the circuit on the chosen backend def get_execute_circuit(graph, shots=512): """ Runs parametrized circuit Args: G: networkx graph p: int, Number of repetitions of unitaries """ backend = Aer.get_backend('qasm_simulator') backend.shots = shots def execute_circ(theta): qc = create_qaoa_circuit(graph, theta) counts = backend.run(qc, seed_simulator=10, nshots=512).result().get_counts() return compute_expectation(counts, graph) return execute_circ
https://github.com/apcarrik/qiskit-dev
apcarrik
import matplotlib as plt import numpy as np from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram from math import gcd from numpy.random import randint import pandas as pd from fractions import Fraction print("Imports Successful") ### Problem: Period Finding # Builds circuit for operator U such that U|y> = |ay mod 15> def c_amod15(a, power): """Controlled multiplication by a mod 15""" if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11, or 13") U = QuantumCircuit(4) for iteration in range(power): if a in [2,13]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [7,8]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a == 11: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for q in range(4): U.x(q) U = U.to_gate() U.name = "%i^%i mod 15" % (a, power) c_U = U.control() return c_U # Specify variables n_count = 8 # number of counting qubits a = 7 # Import QFT circuit def qft_dagger(n): """n-qubit QFTdagger the first n qubits in circuit""" qc = QuantumCircuit(n) # Don't forget the swaps! 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 = "QFTdagger" return qc # Create QuantumCircuit with n_count counting qubits plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 4, n_count) # Initialize counting qubits in state |+> for q in range(n_count): qc.h(q) # Add auxiliary register in state |1> qc.x(3+n_count) # Do controlled-U operations for q in range(n_count): qc.append(c_amod15(a, 2**q), [q] + [i+n_count for i in range(4)]) # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(output='mpl', fold=-1).show() # -1 means do not fold # Show histogram results aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts).show() # Show text results rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # convert (base 2) string to decimal phase = decimal/(2**n_count) # find corresponding eigenvalue measured_phases.append(phase) rows.append( [f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"] )# add these valeus to the rows in our table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) # Find s and r using continuded fractions algorithm rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) headers = ["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns= headers) print(df) ### Modular Exponentiation # Use repeated squaring to calcualte exponential a^(2^j) mod N def a2jmodN(a, j, N): """Compute a^(2^j) (mod N) by repeated squaring""" for i in range(j): a = np.mod(a**2, N) return a print(a2jmodN(7,2049, 53)) ### Factoring and Period Finding # Assume N is the product of two primes N = 15 np.random.seed(1) a = randint(2,15) print("a=",a) # Check a isn't already a non-trivial factor of N from math import gcd assert gcd(a,N) == 1 # Apply Shor's order finding algorithm for N=15 def qpe_amod15(a): n_count = 8 qc = QuantumCircuit(4+n_count, n_count) for q in range(n_count): qc.h(q) # initialize counting qubits in state |+> qc.x(3+n_count) # set auxiliary register in state |1> for q in range(n_count): # do controlled-U operations qc.append(c_amod15(a, 2**q), [q] + [i+n_count for i in range(4)]) qc.append(qft_dagger(n_count), range(n_count)) # Do inverse-QFT qc.measure(range(n_count), range(n_count)) # Simulate results aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) obj = assemble(t_qc, shots=1) result = aer_sim.run(qobj, memory=True).result() # setting memory=True allows us to see list of each sequential reading readings = result.get_memory() print("Register Reading: ", readings[0]) phase = int(readings[0],2)/(2**n_count) print("Corresponding Phase: %f" % phase) return phase # Find guess for r given phase phase = qpe_amod15(a) # Phase = s/r Fraction(phase).limit_denominator(15) # Denominator should tell us r # Get fraction frac = Fraction(phase).limit_denominator(15) s, r = frac.numerator, frac.denominator print(r) # use r to guess factors of N guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] print("guesses:", guesses) # repeat guess algorithm until at least one factor of 15 is found a = 7 factor_found = False attempt = 0 while not factor_found: attempt += 1 print("\nAttempt %i:" % attempt) phase = qpe_amod15(a) # Phase = s/r frac = Fraction(phase).limit_denominator(N) # Denominator should tell us r r = frac.denominator print("Result: r = %i" % r) if phase != 0: # Guesses for factors are gcd(x^(r/2) +/- 1 , 15) guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] print("Guessed Factors: %i and %i" % (guesses[0], guesses[1])) for guess in guesses: if guess not in [1,N] and (N % guess) == 0: # check to see if guess is factor print("*** Non-trivial factor found: %i ***" % guess) factor_found = True
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### added y gate ### qc.y(0) qc.h(1) return qc
https://github.com/qiskit-community/qopt-best-practices
qiskit-community
import matplotlib.pyplot import networkx as nx from qiskit_ibm_runtime.fake_provider import FakeVigoV2 from qiskit import qpy from qiskit_aer import Aer from qiskit_optimization.applications import Maxcut print("Your installation works 🎉!") from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() print("Your available backends are: ", service.backends()) 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="<MY_IBM_QUANTUM_TOKEN>", overwrite=True, set_as_default=True) # Load saved credentials service = QiskitRuntimeService()
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
from collections import Counter import io, pydot from PIL import Image import networkx as nx import retworkx as rx from qiskit.test.mock import FakeMumbai, FakeManhattan from qiskit.providers.aer.noise import NoiseModel mumbai = FakeMumbai() conf = mumbai.configuration() props = mumbai.properties() noise_model = NoiseModel.from_backend(mumbai) graph = rx.PyGraph(multigraph=False) coupling_map = [tuple(edge) for edge in conf.coupling_map] graph.add_nodes_from([i for i in range(27)]) graph.add_edges_from_no_data(coupling_map) circle_nodes = [12, 13, 14, 16, 19, 22, 25, 24, 23, 21, 18, 15] neighbor_nodes = [10, 11, 20, 26, 17] def node_attr(node): kwargs = dict(style='filled', shape="circle", label="", fixedsize="true", width="0.3", height="0.3") if node in circle_nodes: kwargs.update(fillcolor='green') elif node in neighbor_nodes: kwargs.update(fillcolor='lightblue') else: kwargs.update(fillcolor='darkblue') return kwargs graph_attr = {"center": "true", "mode": "KK", "ratio": "0.5"} dot_str = graph.to_dot(node_attr=node_attr, graph_attr=graph_attr) dot = pydot.graph_from_dot_data(dot_str)[0] png = dot.create_png(prog='neato') Image.open(io.BytesIO(png)) print(f"Mumbai has the following gate set: {set(noise_model.basis_gates) - set(['reset'])}") # reset not physically implemented yet num_qubits = conf.n_qubits def calc_mean(T: callable) -> float: """ return mean of T1 or T2 time in microseconds""" s = sum(T(qubit) for qubit in range(num_qubits)) return s / num_qubits * 10**6 T1, T2 = map(calc_mean, (props.t1, props.t2)) print(f"Averages over all {num_qubits} qubits in µs: {T1=:.2f} {T2=:.2f}") mean_readout = sum(props.readout_error(q) for q in range(num_qubits)) / num_qubits * 100 print(f"Average readout error is {mean_readout:.2f} %") manhattan = FakeManhattan() conf = manhattan.configuration() G = nx.Graph() G.add_nodes_from(range(0,conf.n_qubits)) G.add_edges_from(conf.coupling_map) print(f"Manhattan Graph: Nodes {G.number_of_nodes()} Connections {G.number_of_edges()}") degree_ct = Counter() for node, degree in dict(G.degree()).items(): degree_ct[degree] += 1 print("Degree to number of nodes: ", degree_ct)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import json import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit import ParameterVector from qiskit.circuit.library import ZFeatureMap from qiskit.quantum_info import SparsePauliOp from qiskit.utils import algorithm_globals from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier from qiskit_machine_learning.neural_networks import EstimatorQNN from sklearn.model_selection import train_test_split algorithm_globals.random_seed = 12345 # We now define a two qubit unitary as defined in [3] def conv_circuit(params): target = QuantumCircuit(2) target.rz(-np.pi / 2, 1) target.cx(1, 0) target.rz(params[0], 0) target.ry(params[1], 1) target.cx(0, 1) target.ry(params[2], 1) target.cx(1, 0) target.rz(np.pi / 2, 0) return target # Let's draw this circuit and see what it looks like params = ParameterVector("θ", length=3) circuit = conv_circuit(params) circuit.draw("mpl") def conv_layer(num_qubits, param_prefix): qc = QuantumCircuit(num_qubits, name="Convolutional Layer") qubits = list(range(num_qubits)) param_index = 0 params = ParameterVector(param_prefix, length=num_qubits * 3) for q1, q2 in zip(qubits[0::2], qubits[1::2]): qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2]) qc.barrier() param_index += 3 for q1, q2 in zip(qubits[1::2], qubits[2::2] + [0]): qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2]) qc.barrier() param_index += 3 qc_inst = qc.to_instruction() qc = QuantumCircuit(num_qubits) qc.append(qc_inst, qubits) return qc circuit = conv_layer(4, "θ") circuit.decompose().draw("mpl") def pool_circuit(params): target = QuantumCircuit(2) target.rz(-np.pi / 2, 1) target.cx(1, 0) target.rz(params[0], 0) target.ry(params[1], 1) target.cx(0, 1) target.ry(params[2], 1) return target params = ParameterVector("θ", length=3) circuit = pool_circuit(params) circuit.draw("mpl") def pool_layer(sources, sinks, param_prefix): num_qubits = len(sources) + len(sinks) qc = QuantumCircuit(num_qubits, name="Pooling Layer") param_index = 0 params = ParameterVector(param_prefix, length=num_qubits // 2 * 3) for source, sink in zip(sources, sinks): qc = qc.compose(pool_circuit(params[param_index : (param_index + 3)]), [source, sink]) qc.barrier() param_index += 3 qc_inst = qc.to_instruction() qc = QuantumCircuit(num_qubits) qc.append(qc_inst, range(num_qubits)) return qc sources = [0, 1] sinks = [2, 3] circuit = pool_layer(sources, sinks, "θ") circuit.decompose().draw("mpl") def generate_dataset(num_images): images = [] labels = [] hor_array = np.zeros((6, 8)) ver_array = np.zeros((4, 8)) j = 0 for i in range(0, 7): if i != 3: hor_array[j][i] = np.pi / 2 hor_array[j][i + 1] = np.pi / 2 j += 1 j = 0 for i in range(0, 4): ver_array[j][i] = np.pi / 2 ver_array[j][i + 4] = np.pi / 2 j += 1 for n in range(num_images): rng = algorithm_globals.random.integers(0, 2) if rng == 0: labels.append(-1) random_image = algorithm_globals.random.integers(0, 6) images.append(np.array(hor_array[random_image])) elif rng == 1: labels.append(1) random_image = algorithm_globals.random.integers(0, 4) images.append(np.array(ver_array[random_image])) # Create noise for i in range(8): if images[-1][i] == 0: images[-1][i] = algorithm_globals.random.uniform(0, np.pi / 4) return images, labels images, labels = generate_dataset(50) train_images, test_images, train_labels, test_labels = train_test_split( images, labels, test_size=0.3 ) fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(4): ax[i // 2, i % 2].imshow( train_images[i].reshape(2, 4), # Change back to 2 by 4 aspect="equal", ) plt.subplots_adjust(wspace=0.1, hspace=0.025) feature_map = ZFeatureMap(8) feature_map.decompose().draw("mpl") feature_map = ZFeatureMap(8) ansatz = QuantumCircuit(8, name="Ansatz") # First Convolutional Layer ansatz.compose(conv_layer(8, "с1"), list(range(8)), inplace=True) # First Pooling Layer ansatz.compose(pool_layer([0, 1, 2, 3], [4, 5, 6, 7], "p1"), list(range(8)), inplace=True) # Second Convolutional Layer ansatz.compose(conv_layer(4, "c2"), list(range(4, 8)), inplace=True) # Second Pooling Layer ansatz.compose(pool_layer([0, 1], [2, 3], "p2"), list(range(4, 8)), inplace=True) # Third Convolutional Layer ansatz.compose(conv_layer(2, "c3"), list(range(6, 8)), inplace=True) # Third Pooling Layer ansatz.compose(pool_layer([0], [1], "p3"), list(range(6, 8)), inplace=True) # Combining the feature map and ansatz circuit = QuantumCircuit(8) circuit.compose(feature_map, range(8), inplace=True) circuit.compose(ansatz, range(8), inplace=True) observable = SparsePauliOp.from_list([("Z" + "I" * 7, 1)]) # we decompose the circuit for the QNN to avoid additional data copying qnn = EstimatorQNN( circuit=circuit.decompose(), observables=observable, input_params=feature_map.parameters, weight_params=ansatz.parameters, ) circuit.draw("mpl") def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() with open("11_qcnn_initial_point.json", "r") as f: initial_point = json.load(f) classifier = NeuralNetworkClassifier( qnn, optimizer=COBYLA(maxiter=200), # Set max iterations here callback=callback_graph, initial_point=initial_point, ) x = np.asarray(train_images) y = np.asarray(train_labels) objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) classifier.fit(x, y) # score classifier print(f"Accuracy from the train data : {np.round(100 * classifier.score(x, y), 2)}%") y_predict = classifier.predict(test_images) x = np.asarray(test_images) y = np.asarray(test_labels) print(f"Accuracy from the test data : {np.round(100 * classifier.score(x, y), 2)}%") # Let's see some examples in our dataset fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(0, 4): ax[i // 2, i % 2].imshow(test_images[i].reshape(2, 4), aspect="equal") if y_predict[i] == -1: ax[i // 2, i % 2].set_title("The QCNN predicts this is a Horizontal Line") if y_predict[i] == +1: ax[i // 2, i % 2].set_title("The QCNN predicts this is a Vertical Line") plt.subplots_adjust(wspace=0.1, hspace=0.5) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from sklearn.datasets import load_iris iris_data = load_iris() print(iris_data.DESCR) features = iris_data.data labels = iris_data.target from sklearn.preprocessing import MinMaxScaler features = MinMaxScaler().fit_transform(features) import pandas as pd import seaborn as sns df = pd.DataFrame(iris_data.data, columns=iris_data.feature_names) df["class"] = pd.Series(iris_data.target) sns.pairplot(df, hue="class", palette="tab10") from sklearn.model_selection import train_test_split from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=0.8, random_state=algorithm_globals.random_seed ) from sklearn.svm import SVC svc = SVC() _ = svc.fit(train_features, train_labels) # suppress printing the return value train_score_c4 = svc.score(train_features, train_labels) test_score_c4 = svc.score(test_features, test_labels) print(f"Classical SVC on the training dataset: {train_score_c4:.2f}") print(f"Classical SVC on the test dataset: {test_score_c4:.2f}") from qiskit.circuit.library import ZZFeatureMap num_features = features.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) feature_map.decompose().draw(output="mpl", fold=20) from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=num_features, reps=3) ansatz.decompose().draw(output="mpl", fold=20) from qiskit.algorithms.optimizers import COBYLA optimizer = COBYLA(maxiter=100) from qiskit.primitives import Sampler sampler = Sampler() from matplotlib import pyplot as plt from IPython.display import clear_output objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() import time from qiskit_machine_learning.algorithms.classifiers import VQC vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q4 = vqc.score(train_features, train_labels) test_score_q4 = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}") print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}") from sklearn.decomposition import PCA features = PCA(n_components=2).fit_transform(features) plt.rcParams["figure.figsize"] = (6, 6) sns.scatterplot(x=features[:, 0], y=features[:, 1], hue=labels, palette="tab10") train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=0.8, random_state=algorithm_globals.random_seed ) svc.fit(train_features, train_labels) train_score_c2 = svc.score(train_features, train_labels) test_score_c2 = svc.score(test_features, test_labels) print(f"Classical SVC on the training dataset: {train_score_c2:.2f}") print(f"Classical SVC on the test dataset: {test_score_c2:.2f}") num_features = features.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) ansatz = RealAmplitudes(num_qubits=num_features, reps=3) optimizer = COBYLA(maxiter=40) vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] # make the objective function plot look nicer. plt.rcParams["figure.figsize"] = (12, 6) start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q2_ra = vqc.score(train_features, train_labels) test_score_q2_ra = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset using RealAmplitudes: {train_score_q2_ra:.2f}") print(f"Quantum VQC on the test dataset using RealAmplitudes: {test_score_q2_ra:.2f}") from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=num_features, reps=3) optimizer = COBYLA(maxiter=40) vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q2_eff = vqc.score(train_features, train_labels) test_score_q2_eff = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset using EfficientSU2: {train_score_q2_eff:.2f}") print(f"Quantum VQC on the test dataset using EfficientSU2: {test_score_q2_eff:.2f}") print(f"Model | Test Score | Train Score") print(f"SVC, 4 features | {train_score_c4:10.2f} | {test_score_c4:10.2f}") print(f"VQC, 4 features, RealAmplitudes | {train_score_q4:10.2f} | {test_score_q4:10.2f}") print(f"----------------------------------------------------------") print(f"SVC, 2 features | {train_score_c2:10.2f} | {test_score_c2:10.2f}") print(f"VQC, 2 features, RealAmplitudes | {train_score_q2_ra:10.2f} | {test_score_q2_ra:10.2f}") print(f"VQC, 2 features, EfficientSU2 | {train_score_q2_eff:10.2f} | {test_score_q2_eff:10.2f}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/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/jeevesh2002/QuantumKatasQiskit
jeevesh2002
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector # Create a quantum circuit with one qubit qc = QuantumCircuit(1) # Put the qubit into an uneven superposition # ry(theta) is a rotation around the y-axis by angle theta qc.ry(1.0, 0) # Print the statevector |𝜓❭ print(f"The Qubit is in State |𝜓❭ = {Statevector.from_instruction(qc).data}") # Let's apply the X gate; notice how it swaps the amplitudes of the |0❭ and |1❭ basis states qc.x(0) # Print the statevector X|𝜓❭ print(f"The Qubit is in State X|𝜓❭ = {Statevector.from_instruction(qc).data}") # Applying the Z gate adds -1 relative phase to the |1❭ basis states qc.z(0) # Print the statevector ZX|𝜓❭ print(f"The Qubit is in State ZX|𝜓❭ = {Statevector.from_instruction(qc).data}") # Finally, applying the Y gate returns the qubit to its original state |𝜓❭, with an extra global phase of i qc.y(0) # Print the statevector YZX|𝜓❭ print(f"The Qubit is in State YZX|𝜓❭ = {Statevector.from_instruction(qc).data}")
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0, 4.0, 5.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/daimurat/qiskit-implementation
daimurat
import numpy as np import matplotlib.pyplot as plt from qiskit import Aer, QuantumCircuit from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit.opflow import StateFn, PauliSumOp, AerPauliExpectation, Gradient from qiskit.utils import QuantumInstance from qiskit.algorithms.optimizers import COBYLA from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier expval = AerPauliExpectation() gradient = Gradient() qi_sv = QuantumInstance(Aer.get_backend('statevector_simulator')) qi_qasm = QuantumInstance(Aer.get_backend('qasm_simulator'), shots=1000) from qiskit_machine_learning.neural_networks import CircuitQNN num_qubits = 3 qc = RealAmplitudes(num_qubits, entanglement='linear', reps=1) qc.draw(output='mpl') # specify circuit QNN qnn = CircuitQNN(qc, [], qc.parameters, sparse=True, sampling=False, quantum_instance=qi_qasm) # define (random) input and weights input = np.random.rand(qnn.num_inputs) weights = np.random.rand(qnn.num_weights) # QNN forward pass # sampling=True: sample # sampling=False: probability qnn.forward(input, weights).todense() # returned as ab sparse matrix meas = QuantumCircuit(num_qubits) meas.measure_all() qc.assign_parameters(weights, inplace=True) qc_sampling = meas.compose(qc, front=True) # frontをTrueにしないと測定が先に来てしまう qi_qasm.execute(qc_sampling).get_counts() # QNN backward pass, returns a tuple of sparse matrices # sampling=True: None # sampling=False: probability gradient result = qnn.backward(input, weights) result[1].todense() # specify circuit QNN parity = lambda x: '{:b}'.format(x).count('1') % 2 # バイナリ表現で1の数/2 output_shape = 2 # this is required in case of a callable with dense output qnn6 = CircuitQNN(qc, [], qc.parameters, sparse=False, interpret=parity, output_shape=output_shape, quantum_instance=qi_qasm) # define (random) input and weights input6 = np.random.rand(qnn6.num_inputs) weights6 = np.random.rand(qnn6.num_weights) # QNN forward pass qnn6.forward(input6, weights6) # QNN backward pass qnn6.backward(input6, weights6) num_inputs = 2 num_samples = 20 X = 2*np.random.rand(num_samples, num_inputs) - 1 # num_sample x num_inpuutsの配列 y01 = 1*(np.sum(X, axis=1) >= 0) # in { 0, 1} y = 2*y01-1 # in {-1, +1} y_one_hot = np.zeros((num_samples, 2)) for i in range(num_samples): y_one_hot[i, y01[i]] = 1 for x, y_target in zip(X, y): if y_target == 1: plt.plot(x[0], x[1], 'bo') else: plt.plot(x[0], x[1], 'go') plt.plot([-1, 1], [1, -1], '--', color='black') plt.show() # 量子回路の準備 num_inputs = 2 feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) qc = QuantumCircuit(num_inputs) qc.append(feature_map, range(num_inputs)) qc.append(ansatz, range(num_inputs)) qc.decompose().draw(output='mpl') # parity maps bitstrings to 0 or 1 def parity(x): return '{:b}'.format(x).count('1') % 2 output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping. # construct QNN circuit_qnn = CircuitQNN(circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, quantum_instance=qi_qasm) # construct classifier circuit_classifier = NeuralNetworkClassifier(neural_network=circuit_qnn, optimizer=COBYLA()) circuit_classifier.fit(X, y01) circuit_classifier.score(X, y01) # 評価用のデータを生成 num_samples_test = 100 X_test = 2*np.random.rand(num_samples_test, num_inputs) - 1 # num_sample x num_inpuutsの配列 y01_test = 1*(np.sum(X_test, axis=1) >= 0) # in { 0, 1} y_test = 2*y01_test-1 # in {-1, +1} # evaluate data points y_predict = circuit_classifier.predict(X_test) # plot results for x, y_target, y_p in zip(X_test, y01_test, y_predict): if y_p == 1: plt.plot(x[0], x[1], 'bo') else: plt.plot(x[0], x[1], 'go') if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2) plt.plot([-1, 1], [1, -1], '--', color='black') plt.show() import qiskit.tools.jupyter %qiskit_version_table
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/Qiskit/feedback
Qiskit
#pylint: disable=import-error, wrong-import-position # Python imports import os import sys # External imports from pylab import cm from sklearn import metrics import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Qiskit imports from qiskit import BasicAer from qiskit.visualization import circuit_drawer from qiskit.algorithms.optimizers import SPSA from qiskit_machine_learning.kernels import QuantumKernel from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer from qiskit_machine_learning.algorithms import QSVC # Put this repository on the Python path and import qkt pkgs module_path = os.path.abspath(os.path.join('../..')) sys.path.append(module_path) from qkt.feature_maps import CovariantFeatureMap from qkt.utils import train_test_split, QKTCallback # Load the dataset and split into train and test sets DATA_FILEPATH = '../../data/dataset_graph7.csv' X_train, y_train, X_test, y_test = train_test_split(DATA_FILEPATH) num_features = np.shape(X_train)[1] entangler_map = [[0,2],[3,4],[2,5],[1,4],[2,3],[4,6]] # Note that [[0,1],[2,3],[4,5],[6,7],[8,9],[1,2],[3,4],[5,6],[7,8]] # is a suitable input for the 10-qubit dataset fm = CovariantFeatureMap( feature_dimension=num_features, entanglement=entangler_map, single_training_parameter=True ) circuit_drawer(fm) print(fm.user_parameters) # Use the qasm simulator backend backend = BasicAer.get_backend('statevector_simulator') # Instantiate quantum kernel quant_kernel = QuantumKernel(fm, user_parameters=fm.user_parameters, quantum_instance=backend) # Set up the optimizer cb_qkt = QKTCallback() spsa_opt = SPSA(maxiter=5, callback=cb_qkt.callback, learning_rate=0.1, perturbation=0.1 ) # Instantiate a quantum kernel trainer. qkt = QuantumKernelTrainer( quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[0.1]*len(fm.user_parameters) ) # Train the kernel using QKT directly qka_results = qkt.fit(X_train, y_train) optimized_kernel = qka_results.quantum_kernel # Use QSVC for classification qsvc = QSVC(quantum_kernel=optimized_kernel) # Fit the QSVC qsvc.fit(X_train, y_train) # Predict the labels labels_test = qsvc.predict(X_test) # Evalaute the test accuracy accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test) print(f"accuracy test: {accuracy_test}") plot_data = cb_qkt.get_callback_data() # callback data K=optimized_kernel.evaluate(X_train) # kernel matrix evaluated on the training samples plt.rcParams['font.size'] = 20 fig, ax = plt.subplots(1,2, figsize=(14,5)) ax[0].plot([i+1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c='k', marker='o' ) ax[0].set_xlabel('Iterations') ax[0].set_ylabel('Loss') ax[1].imshow(K, cmap=cm.get_cmap('bwr', 20)) ax[1].axis('off') fig.tight_layout() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/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/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
from qiskit import IBMQ from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.test.mock import FakeMumbai from qiskit.utils import QuantumInstance from qiskit.providers.aer.noise import NoiseModel from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer def job_callback(job_id, job_status, queue_position, job): # BUG ? print(job_id) print(job_status) print(queue_position) print(job) problem = QuadraticProgram() x = problem.continuous_var(name="x") y = problem.continuous_var(name="y") problem.maximize(linear=[2, 0], quadratic=[[-1, 2], [0, -2]]) # init IBM Q Experience Simulator IBMQ.load_account() backend = IBMQ.get_provider(hub="ibm-q").get_backend("simulator_statevector") quantum_instance_kwargs = {"shots": 512, "job_callback": job_callback} quantum_instance = QuantumInstance(backend, **quantum_instance_kwargs) print("only quantum instance") print(f"{quantum_instance._job_callback=}") qaoa_mes = QAOA(quantum_instance=quantum_instance, optimizer=COBYLA(maxiter=2)) qaoa_ibmq_sim = MinimumEigenOptimizer(qaoa_mes) print("QAOA meo no noise model") print(f"{qaoa_ibmq_sim.min_eigen_solver.quantum_instance._job_callback=}") device = FakeMumbai() noise_model = NoiseModel.from_backend(device) conf = device.configuration() quantum_instance_kwargs_noise = { "shots": 512, "noise_model": noise_model, "job_callback": job_callback, "coupling_map": conf.coupling_map, "basis_gates": conf.basis_gates, } quantum_instance_noise = QuantumInstance(backend, **quantum_instance_kwargs) qaoa_mes_noise = QAOA(quantum_instance=quantum_instance_noise, optimizer=COBYLA(maxiter=2)) qaoa_ibmq_noise = MinimumEigenOptimizer(qaoa_mes_noise) print("QAOA meo with noise model") print(f"{qaoa_ibmq_noise.min_eigen_solver.quantum_instance._job_callback=}")
https://github.com/ka-us-tubh/quantum-computing-qiskit-
ka-us-tubh
import numpy as np # Importing standard Qiskit libraries from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator from qiskit.extensions import Initialize from qiskit_textbook.tools import random_state # Loading your IBM Quantum account(s) provider = IBMQ.load_account() qr =QuantumRegister(3,name='q') crz=ClassicalRegister(1,name='crz') crx =ClassicalRegister(1,name='crx') qc=QuantumCircuit(qr,crz,crx) def create_bell_pair(qc,a,b): qc.h(a) qc.cx(a,b) def alice_gates(qc,psi,a): qc.cx(psi,a) qc.h(psi) def measure_and_send(qr,a,b): qc.barrier() qc.measure(a,0) qc.measure(b,1) def bob_gates(qc,qubit,crz,crx): qc.x(qubit).c_if(crx,1) qc.z(qubit).c_if(crz,1) psi =random_state(1) display(array_to_latex(psi,prefix="|\\psi\\rangle=")) plot_bloch_multivector(psi) init_gate=Initialize(psi) init_gate.label='init' qc.append(init_gate,[0]) qc.barrier() create_bell_pair(qc,1,2) qc.barrier() alice_gates(qc,0,1) measure_and_send(qc,0,1) bob_gates(qc,2,crz,crx) qc.draw() sim=Aer.get_backend('aer_simulator') qc.save_statevector() out_vector=sim.run(qc).result().get_statevector() plot_bloch_multivector(out_vector) #usinng qasm sim inverse_init_gate=init_gate.gates_to_uncompute() qc.append(init_gate,[0]) qc.barrier() create_bell_pair(qc,1,2) qc.barrier() alice_gates(qc,0,1) measure_and_send(qc,0,1) bob_gates(qc,2,crz,crx) qc.append(inverse_init_gate,[2]) cr_result=ClassicalRegister(1) qc.add_register(cr_result) qc.measure(2,2) qc.draw() t_qc=transpile(qc,sim) t_qc.save_statevector() counts =sim.run(t_qc).result().get_counts() plot_histogram(counts) def new_bob_gates(qc,a,b,c): qc.cx(b,c) qc.cz(a,c) qc=QuantumCircuit(3,1) qc.append(init_gate,[0]) qc.barrier() create_bell_pair(qc,1,2) qc.barrier() alice_gates(qc,0,1) qc.barrier() #measure_and_send(qc,0,1) new_bob_gates(qc,0,1,2) qc.append(inverse_init_gate,[2]) #cr_result=ClassicalRegister(1) #qc.add_register(cr_result) qc.measure(2,0) qc.draw() IBMQ.load_account() provider=IBMQ.get_provider(hub="ibm-q") from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor backend=least_busy(provider.backends(filters=lambda b:b.configuration().n_qubits>=3 and not b.configuration().simulator and b.status().operational==True)) t_qc =transpile(qc,backend,optimization_level=3) job=backend.run(t_qc) job_monitor(job) exp_result=job.result() exp_counts =exp_result.get_counts(qc) print(exp_counts) plot_histogram(exp_counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw()
https://github.com/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. """ Constructs a multiplexor gate. """ from math import log2 from typing import List, Union, Type import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library import RZGate, RYGate, CXGate, CZGate def ucr( r_gate: Union[Type[RZGate], Type[RYGate]], angles: List[float], c_gate: Union[Type[CXGate], Type[CZGate]] = CXGate, last_control=True, ) -> QuantumCircuit: """ Constructs a multiplexor rotation gate. Synthesis of Quantum Logic Circuits https://arxiv.org/abs/quant-ph/0406176 """ size = len(angles) n_qubits = int(log2(size)) + 1 reg = QuantumRegister(n_qubits) circuit = QuantumCircuit(reg) target = reg[0] control = reg[n_qubits - 1] if n_qubits == 1: if abs(angles[0]) > 10**-8: circuit.append(r_gate(angles[0]), [target]) return circuit angle_multiplexor = np.kron( [[0.5, 0.5], [0.5, -0.5]], np.identity(2 ** (n_qubits - 2)) ) multiplexed_angles = angle_multiplexor.dot(angles) # Figure 2 from Synthesis of Quantum Logic Circuits: # The recursive decomposition of a multiplexed Rz gate. # The boxed CNOT gates may be canceled. # This is why "last_cnot=False" in both calls of "rotation_multiplexor()" and # also why the multiplexer in the second "circuit.append()" is reversed. mult = ucr(r_gate, multiplexed_angles[: size // 2], c_gate, False) circuit.append(mult.to_instruction(), reg[0:-1]) circuit.append(c_gate(), [control, target]) mult = ucr(r_gate, multiplexed_angles[size // 2 :], c_gate, False) circuit.append(mult.reverse_ops().to_instruction(), reg[0:-1]) # The following condition allows saving CNOTs when two multiplexors are used # in sequence. Any multiplexor can have its operation reversed. Therefore, if # the second multiplexor is reverted, its last CNOT will be cancelled by the # last CNOT of the first multiplexer. In this condition, both last CNOTs are # unnecessary. if last_control: circuit.append(c_gate(), [control, target]) return circuit
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, assemble, Aer from qiskit.tools.visualization import plot_histogram from math import pi import matplotlib.pyplot as plt q = QuantumRegister(1,'q') c = ClassicalRegister(1,'c') qc = QuantumCircuit(q, c) qc.h(0) qc.measure(0,0) qc.x(0).c_if(c, 0) qc.draw(output='mpl') q = QuantumRegister(3,'q') c = ClassicalRegister(3,'c') qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.barrier() qc.measure(q,c) qc.draw('mpl') print(bin(3)) print(bin(7)) q = QuantumRegister(3,'q') c = ClassicalRegister(3,'c') qc = QuantumCircuit(q, c) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.measure(q,c) qc.x(2).c_if(c, 3) # for the 011 case qc.x(2).c_if(c, 7) # for the 111 case qc.draw(output='mpl') nq = 2 m = 2 q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc_S = QuantumCircuit(q,c) qc_S.h(0) qc_S.x(1) qc_S.draw('mpl') cu_circ = QuantumCircuit(2) cu_circ.cp(pi/2,0,1) cu_circ.draw('mpl') for _ in range(2**(m-1)): qc_S.cp(pi/2,0,1) qc_S.draw('mpl') def x_measurement(qc, qubit, cbit): """Measure 'qubit' in the X-basis, and store the result in 'cbit'""" qc.h(qubit) qc.measure(qubit, cbit) x_measurement(qc_S, q[0], c[0]) qc_S.draw('mpl') qc_S.reset(0) qc_S.h(0) qc_S.draw('mpl') qc_S.p(-pi/2,0).c_if(c,1) qc_S.draw('mpl') ## 2^t c-U operations (with t=m-2) for _ in range(2**(m-2)): qc_S.cp(pi/2,0,1) x_measurement(qc_S, q[0], c[1]) qc_S.draw('mpl') sim = Aer.get_backend('qasm_simulator') count0 = execute(qc_S, sim).result().get_counts() key_new = [str(int(key,2)/2**m) for key in list(count0.keys())] count1 = dict(zip(key_new, count0.values())) fig, ax = plt.subplots(1,2) plot_histogram(count0, ax=ax[0]) plot_histogram(count1, ax=ax[1]) plt.tight_layout() nq = 3 # number of qubits m = 3 # number of classical bits q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc = QuantumCircuit(q,c) qc.h(0) qc.x([1,2]) qc.draw('mpl') cu_circ = QuantumCircuit(nq) cu_circ.mcp(pi/4,[0,1],2) cu_circ.draw('mpl') for _ in range(2**(m-1)): qc.mcp(pi/4,[0,1],2) qc.draw('mpl') x_measurement(qc, q[0], c[0]) qc.draw('mpl') qc.reset(0) qc.h(0) qc.draw('mpl') qc.p(-pi/2,0).c_if(c,1) qc.draw('mpl') for _ in range(2**(m-2)): qc.mcp(pi/4,[0,1],2) x_measurement(qc, q[0], c[1]) qc.draw('mpl') # initialization of qubit q0 qc.reset(0) qc.h(0) # phase correction qc.p(-pi/4,0).c_if(c,1) qc.p(-pi/2,0).c_if(c,2) qc.p(-3*pi/4,0).c_if(c,3) # c-U operations for _ in range(2**(m-3)): qc.mcp(pi/4,[0,1],2) # X measurement qc.h(0) qc.measure(0,2) qc.draw('mpl') count0 = execute(qc, sim).result().get_counts() key_new = [str(int(key,2)/2**m) for key in list(count0.keys())] count1 = dict(zip(key_new, count0.values())) fig, ax = plt.subplots(1,2) plot_histogram(count0, ax=ax[0]) plot_histogram(count1, ax=ax[1]) fig.tight_layout() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/nahumsa/volta
nahumsa
import qiskit import numpy as np from qiskit.aqua.operators import PauliExpectation, CircuitSampler, ExpectationFactory from qiskit.aqua.operators import CircuitStateFn, StateFn, ListOp import sys sys.path.append('../../') from typing import Union import qiskit import numpy as np from qiskit import Aer, execute from qiskit.aqua.utils.backend_utils import is_aer_provider from qiskit.aqua.operators import (PauliExpectation, CircuitSampler, ExpectationFactory, CircuitStateFn, StateFn, ListOp) import sys sys.path.append('../') def sample_hamiltonian(hamiltonian: qiskit.aqua.operators.OperatorBase, backend: Union[qiskit.providers.BaseBackend, qiskit.aqua.QuantumInstance], ansatz: qiskit.QuantumCircuit): if qiskit.aqua.quantum_instance.QuantumInstance == type(backend): sampler = CircuitSampler(backend, param_qobj=is_aer_provider(backend.backend)) else: sampler = CircuitSampler(backend) expectation = ExpectationFactory.build(operator=hamiltonian,backend=backend) observable_meas = expectation.convert(StateFn(hamiltonian, is_measurement=True)) ansatz_circuit_op = CircuitStateFn(ansatz) expect_op = observable_meas.compose(ansatz_circuit_op).reduce() sampled_expect_op = sampler.convert(expect_op) return np.real(sampled_expect_op.eval()) from VOLTA.Ansatz import get_num_parameters, get_var_form from qiskit.aqua.operators import I, X, Y, Z from qiskit.aqua import QuantumInstance n_qubits = 2 n_params = get_num_parameters(n_qubits) params = [0.]*n_params wavefunction = get_var_form(params, n_qubits) hamiltonian = 1/2*((Z^Z) + (Z^I) + (X^X)) hamiltonian = X^X backend = QuantumInstance(backend=qiskit.BasicAer.get_backend('qasm_simulator'), shots=10000) sample_hamiltonian(hamiltonian, backend, wavefunction) # Variational Form backend = qiskit.BasicAer.get_backend('qasm_simulator') sampler = CircuitSampler(backend=backend) expectation = ExpectationFactory.build(operator=hamiltonian,backend=backend) observable_meas = expectation.convert(StateFn(hamiltonian, is_measurement=True)) print(observable_meas) ansatz_circuit_op = CircuitStateFn(wavefunction) expect_op = observable_meas.compose(ansatz_circuit_op).reduce() sampled_expect_op = sampler.convert(expect_op) means = np.real(sampled_expect_op.eval()) means
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute from qiskit.quantum_info import Statevector # the state vector of the required qubits is generated from qiskit.visualization import plot_bloch_multivector, plot_histogram, plot_state_qsphere # plot the qubits in a qsphere import numpy as np from numpy import pi import math from math import sqrt import matplotlib as mpl %matplotlib inline import qiskit qiskit.__version__ qiskit.__qiskit_version__ qc = QuantumCircuit(3) qc.z(0) qc.s(1) qc.s(1) qc.t(2) qc.t(2) qc.t(2) qc.t(2) qc.draw() simulator = Aer.get_backend('statevector_simulator') sv = Statevector.from_label('0') plot_state_qsphere(sv.data) plot_bloch_multivector(sv) #job = execute(qc, simulator) #result = job.result() #outputstate = result.get_statevector(qc) #plot_bloch_multivector(outputstate)
https://github.com/jaykomarraju/Quantum-Optimization-for-Solar-Farm
jaykomarraju
import numpy as np import networkx as nx from qiskit import Aer from qiskit.algorithms import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer num_time_slots = 24 # Define the QUBO problem qubo = QuadraticProgram() # Add binary variables for charging (c) and discharging (d) states for t in range(num_time_slots): qubo.binary_var(f'c_{t}') qubo.binary_var(f'd_{t}') # Define the objective function # (In practice, you need to calculate Jij and hi based on the solar farm data) Jij = np.random.rand(num_time_slots, num_time_slots) * 0.5 hi_c = -1 + np.random.rand(num_time_slots) hi_d = 1 - np.random.rand(num_time_slots) # Set linear and quadratic terms of the objective function linear_terms = {} quadratic_terms = {} for t in range(num_time_slots): linear_terms[f'c_{t}'] = hi_c[t] linear_terms[f'd_{t}'] = hi_d[t] for s in range(num_time_slots): if t != s: quadratic_terms[(f'c_{t}', f'c_{s}')] = Jij[t, s] quadratic_terms[(f'd_{t}', f'd_{s}')] = Jij[t, s] qubo.minimize(linear=linear_terms, quadratic=quadratic_terms) # Set up the quantum instance backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, seed_simulator=42, seed_transpiler=42, shots=10000) # Set up the QAOA algorithm and optimizer optimizer = COBYLA(maxiter=500) qaoa = QAOA(optimizer=optimizer, reps=5, quantum_instance=quantum_instance) # Set up the minimum eigen optimizer min_eig_optimizer = MinimumEigenOptimizer(qaoa) # Solve the problem result = min_eig_optimizer.solve(qubo) print("QAOA result:", result) # Solve the problem using a classical solver (NumPyMinimumEigensolver) exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver()) exact_result = exact_solver.solve(qubo) print("Classical result:", exact_result)
https://github.com/amitcrypto/ARIA-Blocks-Qiskit
amitcrypto
# Copyright (c) Amit Kumar Chauhan, IIT Ropar, India. # Licensed under the GNU General Public License. # Importing standard Qiskit libraries and configuring account import qiskit from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) provider = IBMQ.load_account() # Creating qubits q = qiskit.QuantumRegister(128) circuit = qiskit.QuantumCircuit(q) # Applying Toffoli gate on the register of qubits circuit.ccx(q[7], q[9], q[16]) circuit.ccx(q[6], q[10], q[16]) circuit.ccx(q[5], q[11], q[16]) circuit.ccx(q[4], q[12], q[16]) circuit.ccx(q[3], q[13], q[16]) circuit.ccx(q[2], q[14], q[16]) circuit.ccx(q[1], q[15], q[16]) circuit.ccx(q[7], q[10], q[17]) circuit.ccx(q[6], q[11], q[17]) circuit.ccx(q[5], q[12], q[17]) circuit.ccx(q[4], q[13], q[17]) circuit.ccx(q[3], q[14], q[17]) circuit.ccx(q[2], q[15], q[17]) circuit.ccx(q[7], q[11], q[18]) circuit.ccx(q[6], q[12], q[18]) circuit.ccx(q[5], q[13], q[18]) circuit.ccx(q[4], q[14], q[18]) circuit.ccx(q[3], q[15], q[18]) circuit.ccx(q[7], q[12], q[19]) circuit.ccx(q[6], q[13], q[19]) circuit.ccx(q[5], q[14], q[19]) circuit.ccx(q[4], q[15], q[19]) circuit.ccx(q[7], q[13], q[20]) circuit.ccx(q[6], q[14], q[20]) circuit.ccx(q[5], q[15], q[20]) circuit.ccx(q[7], q[14], q[21]) circuit.ccx(q[6], q[15], q[21]) circuit.ccx(q[7], q[15], q[22]) # Applying CNOT gate on the register of qubits circuit.cx(q[22], q[23]) circuit.cx(q[20], q[23]) circuit.cx(q[19], q[23]) circuit.cx(q[21], q[22]) circuit.cx(q[19], q[22]) circuit.cx(q[18], q[22]) circuit.cx(q[20], q[21]) circuit.cx(q[18], q[21]) circuit.cx(q[17], q[21]) circuit.cx(q[19], q[20]) circuit.cx(q[17], q[20]) circuit.cx(q[16], q[20]) circuit.cx(q[18], q[19]) circuit.cx(q[16], q[19]) circuit.cx(q[18], q[22]) circuit.cx(q[17], q[18]) circuit.cx(q[17], q[22]) circuit.cx(q[17], q[21]) circuit.cx(q[16], q[17]) circuit.cx(q[16], q[21]) circuit.cx(q[16], q[20]) # Applying Toffoli gate on the register of qubits circuit.ccx(q[7], q[8], q[23]) circuit.ccx(q[6], q[9], q[23]) circuit.ccx(q[5], q[10], q[23]) circuit.ccx(q[4], q[11], q[23]) circuit.ccx(q[3], q[12], q[23]) circuit.ccx(q[2], q[13], q[23]) circuit.ccx(q[1], q[14], q[23]) circuit.ccx(q[0], q[15], q[23]) circuit.ccx(q[6], q[8], q[22]) circuit.ccx(q[5], q[9], q[22]) circuit.ccx(q[4], q[10], q[22]) circuit.ccx(q[3], q[11], q[22]) circuit.ccx(q[2], q[12], q[22]) circuit.ccx(q[1], q[13], q[22]) circuit.ccx(q[0], q[14], q[22]) circuit.ccx(q[5], q[8], q[21]) circuit.ccx(q[4], q[9], q[21]) circuit.ccx(q[3], q[10], q[21]) circuit.ccx(q[2], q[11], q[21]) circuit.ccx(q[1], q[12], q[21]) circuit.ccx(q[0], q[13], q[21]) circuit.ccx(q[4], q[8], q[20]) circuit.ccx(q[3], q[9], q[20]) circuit.ccx(q[2], q[10], q[20]) circuit.ccx(q[1], q[11], q[20]) circuit.ccx(q[0], q[12], q[20]) circuit.ccx(q[3], q[8], q[19]) circuit.ccx(q[2], q[9], q[19]) circuit.ccx(q[1], q[10], q[19]) circuit.ccx(q[0], q[11], q[19]) circuit.ccx(q[2], q[8], q[18]) circuit.ccx(q[1], q[9], q[18]) circuit.ccx(q[0], q[10], q[18]) circuit.ccx(q[1], q[8], q[17]) circuit.ccx(q[0], q[9], q[17]) circuit.ccx(q[0], q[8], q[16]) # Printing the circuit qc = circuit.draw() print(qc) # Estimating the circuit depth d = QuantumCircuit.depth(circuit) print('The Circuit Depth :=', d)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) 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 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. """Testing legacy instruction alignment pass.""" from qiskit import QuantumCircuit, pulse from qiskit.test import QiskitTestCase from qiskit.transpiler import InstructionDurations from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import ( AlignMeasures, ValidatePulseGates, ALAPSchedule, TimeUnitConversion, ) class TestAlignMeasures(QiskitTestCase): """A test for measurement alignment pass.""" def setUp(self): super().setUp() instruction_durations = InstructionDurations() instruction_durations.update( [ ("rz", (0,), 0), ("rz", (1,), 0), ("x", (0,), 160), ("x", (1,), 160), ("sx", (0,), 160), ("sx", (1,), 160), ("cx", (0, 1), 800), ("cx", (1, 0), 800), ("measure", None, 1600), ] ) self.time_conversion_pass = TimeUnitConversion(inst_durations=instruction_durations) # reproduce old behavior of 0.20.0 before #7655 # currently default write latency is 0 self.scheduling_pass = ALAPSchedule( durations=instruction_durations, clbit_write_latency=1600, conditional_latency=0, ) self.align_measure_pass = AlignMeasures(alignment=16) def test_t1_experiment_type(self): """Test T1 experiment type circuit. (input) ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├ └───┘└────────────────┘└╥┘ c: 1/════════════════════════╩═ 0 (aligned) ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├ └───┘└────────────────┘└╥┘ c: 1/════════════════════════╩═ 0 This type of experiment slightly changes delay duration of interest. However the quantization error should be less than alignment * dt. """ circuit = QuantumCircuit(1, 1) circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.measure(0, 0) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) ref_circuit = QuantumCircuit(1, 1) ref_circuit.x(0) ref_circuit.delay(112, 0, unit="dt") ref_circuit.measure(0, 0) self.assertEqual(aligned_circuit, ref_circuit) def test_hanh_echo_experiment_type(self): """Test Hahn echo experiment type circuit. (input) ┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌─┐ q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤M├ └────┘└────────────────┘└───┘└────────────────┘└────┘└╥┘ c: 1/══════════════════════════════════════════════════════╩═ 0 (output) ┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌──────────────┐┌─┐ q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤ Delay(8[dt]) ├┤M├ └────┘└────────────────┘└───┘└────────────────┘└────┘└──────────────┘└╥┘ c: 1/══════════════════════════════════════════════════════════════════════╩═ 0 This type of experiment doesn't change duration of interest (two in the middle). However induces slight delay less than alignment * dt before measurement. This might induce extra amplitude damping error. """ circuit = QuantumCircuit(1, 1) circuit.sx(0) circuit.delay(100, 0, unit="dt") circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.sx(0) circuit.measure(0, 0) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) ref_circuit = QuantumCircuit(1, 1) ref_circuit.sx(0) ref_circuit.delay(100, 0, unit="dt") ref_circuit.x(0) ref_circuit.delay(100, 0, unit="dt") ref_circuit.sx(0) ref_circuit.delay(8, 0, unit="dt") ref_circuit.measure(0, 0) self.assertEqual(aligned_circuit, ref_circuit) def test_mid_circuit_measure(self): """Test circuit with mid circuit measurement. (input) ┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(120[dt]) ├┤M├ └───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘ c: 2/════════════════════════╩══════════════════════════════════════════╩═ 0 1 (output) ┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(134[dt]) ├┤M├ └───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘ c: 2/════════════════════════╩══════════════════════════════════════════╩═ 0 1 Extra delay is always added to the existing delay right before the measurement. Delay after measurement is unchanged. """ circuit = QuantumCircuit(1, 2) circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.measure(0, 0) circuit.delay(10, 0, unit="dt") circuit.x(0) circuit.delay(120, 0, unit="dt") circuit.measure(0, 1) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) ref_circuit = QuantumCircuit(1, 2) ref_circuit.x(0) ref_circuit.delay(112, 0, unit="dt") ref_circuit.measure(0, 0) ref_circuit.delay(10, 0, unit="dt") ref_circuit.x(0) ref_circuit.delay(134, 0, unit="dt") ref_circuit.measure(0, 1) self.assertEqual(aligned_circuit, ref_circuit) def test_mid_circuit_multiq_gates(self): """Test circuit with mid circuit measurement and multi qubit gates. (input) ┌───┐┌────────────────┐┌─┐ ┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├──■───────■──┤M├ └───┘└────────────────┘└╥┘┌─┴─┐┌─┐┌─┴─┐└╥┘ q_1: ────────────────────────╫─┤ X ├┤M├┤ X ├─╫─ ║ └───┘└╥┘└───┘ ║ c: 2/════════════════════════╩═══════╩═══════╩═ 0 1 0 (output) ┌───┐ ┌────────────────┐┌─┐ ┌─────────────────┐ ┌─┐» q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├──■──┤ Delay(1600[dt]) ├──■──┤M├» ┌──────┴───┴──────┐└────────────────┘└╥┘┌─┴─┐└───────┬─┬───────┘┌─┴─┐└╥┘» q_1: ┤ Delay(1872[dt]) ├───────────────────╫─┤ X ├────────┤M├────────┤ X ├─╫─» └─────────────────┘ ║ └───┘ └╥┘ └───┘ ║ » c: 2/══════════════════════════════════════╩═══════════════╩═══════════════╩═» 0 1 0 » « «q_0: ─────────────────── « ┌─────────────────┐ «q_1: ┤ Delay(1600[dt]) ├ « └─────────────────┘ «c: 2/═══════════════════ « Delay for the other channel paired by multi-qubit instruction is also scheduled. Delay (1872dt) = X (160dt) + Delay (100dt + extra 12dt) + Measure (1600dt). """ circuit = QuantumCircuit(2, 2) circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.measure(0, 0) circuit.cx(0, 1) circuit.measure(1, 1) circuit.cx(0, 1) circuit.measure(0, 0) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) ref_circuit = QuantumCircuit(2, 2) ref_circuit.x(0) ref_circuit.delay(112, 0, unit="dt") ref_circuit.measure(0, 0) ref_circuit.delay(160 + 112 + 1600, 1, unit="dt") ref_circuit.cx(0, 1) ref_circuit.delay(1600, 0, unit="dt") ref_circuit.measure(1, 1) ref_circuit.cx(0, 1) ref_circuit.delay(1600, 1, unit="dt") ref_circuit.measure(0, 0) self.assertEqual(aligned_circuit, ref_circuit) def test_alignment_is_not_processed(self): """Test avoid pass processing if delay is aligned.""" circuit = QuantumCircuit(2, 2) circuit.x(0) circuit.delay(160, 0, unit="dt") circuit.measure(0, 0) circuit.cx(0, 1) circuit.measure(1, 1) circuit.cx(0, 1) circuit.measure(0, 0) # pre scheduling is not necessary because alignment is skipped # this is to minimize breaking changes to existing code. transpiled = self.align_measure_pass(circuit, property_set={"time_unit": "dt"}) self.assertEqual(transpiled, circuit) def test_circuit_using_clbit(self): """Test a circuit with instructions using a common clbit. (input) ┌───┐┌────────────────┐┌─┐ q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├────────────── └───┘└────────────────┘└╥┘ ┌───┐ q_1: ────────────────────────╫────┤ X ├────── ║ └─╥─┘ ┌─┐ q_2: ────────────────────────╫──────╫─────┤M├ ║ ┌────╨────┐└╥┘ c: 1/════════════════════════╩═╡ c_0 = T ╞═╩═ 0 └─────────┘ 0 (aligned) ┌───┐ ┌────────────────┐┌─┐┌────────────────┐ q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├┤ Delay(160[dt]) ├─── ┌──────┴───┴──────┐└────────────────┘└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1872[dt]) ├───────────────────╫───────┤ X ├────────── └┬────────────────┤ ║ └─╥─┘ ┌─┐ q_2: ─┤ Delay(432[dt]) ├───────────────────╫─────────╫─────────┤M├ └────────────────┘ ║ ┌────╨────┐ └╥┘ c: 1/══════════════════════════════════════╩════╡ c_0 = T ╞═════╩═ 0 └─────────┘ 0 Looking at the q_0, the total schedule length T becomes 160 (x) + 112 (aligned delay) + 1600 (measure) + 160 (delay) = 2032. The last delay comes from ALAP scheduling called before the AlignMeasure pass, which aligns stop times as late as possible, so the start time of x(1).c_if(0) and the stop time of measure(0, 0) become T - 160. """ circuit = QuantumCircuit(3, 1) circuit.x(0) circuit.delay(100, 0, unit="dt") circuit.measure(0, 0) circuit.x(1).c_if(0, 1) circuit.measure(2, 0) timed_circuit = self.time_conversion_pass(circuit) scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"}) aligned_circuit = self.align_measure_pass( scheduled_circuit, property_set={"time_unit": "dt"} ) self.assertEqual(aligned_circuit.duration, 2032) ref_circuit = QuantumCircuit(3, 1) ref_circuit.x(0) ref_circuit.delay(112, 0, unit="dt") ref_circuit.delay(1872, 1, unit="dt") # 2032 - 160 ref_circuit.delay(432, 2, unit="dt") # 2032 - 1600 ref_circuit.measure(0, 0) ref_circuit.x(1).c_if(0, 1) ref_circuit.delay(160, 0, unit="dt") ref_circuit.measure(2, 0) self.assertEqual(aligned_circuit, ref_circuit) class TestPulseGateValidation(QiskitTestCase): """A test for pulse gate validation pass.""" def setUp(self): super().setUp() self.pulse_gate_validation_pass = ValidatePulseGates(granularity=16, min_length=64) def test_invalid_pulse_duration(self): """Kill pass manager if invalid pulse gate is found.""" # this is invalid duration pulse # this will cause backend error since this doesn't fit with waveform memory chunk. custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)), inplace=True ) circuit = QuantumCircuit(1) circuit.x(0) circuit.add_calibration("x", qubits=(0,), schedule=custom_gate) with self.assertRaises(TranspilerError): self.pulse_gate_validation_pass(circuit) def test_short_pulse_duration(self): """Kill pass manager if invalid pulse gate is found.""" # this is invalid duration pulse # this will cause backend error since this doesn't fit with waveform memory chunk. custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True ) circuit = QuantumCircuit(1) circuit.x(0) circuit.add_calibration("x", qubits=(0,), schedule=custom_gate) with self.assertRaises(TranspilerError): self.pulse_gate_validation_pass(circuit) def test_short_pulse_duration_multiple_pulse(self): """Kill pass manager if invalid pulse gate is found.""" # this is invalid duration pulse # however total gate schedule length is 64, which accidentally satisfies the constraints # this should fail in the validation custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True ) custom_gate.insert( 32, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True ) circuit = QuantumCircuit(1) circuit.x(0) circuit.add_calibration("x", qubits=(0,), schedule=custom_gate) with self.assertRaises(TranspilerError): self.pulse_gate_validation_pass(circuit) def test_valid_pulse_duration(self): """No error raises if valid calibration is provided.""" # this is valid duration pulse custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(160, 0.1), pulse.DriveChannel(0)), inplace=True ) circuit = QuantumCircuit(1) circuit.x(0) circuit.add_calibration("x", qubits=(0,), schedule=custom_gate) # just not raise an error self.pulse_gate_validation_pass(circuit) def test_no_calibration(self): """No error raises if no calibration is addedd.""" circuit = QuantumCircuit(1) circuit.x(0) # just not raise an error self.pulse_gate_validation_pass(circuit)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct circuit for uncertainty model uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) # plot probability distribution x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 1.438 strike_price_2 = 2.584 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, strike_price_2 - strike_price_1] f_min = 0 f_max = strike_price_2 - strike_price_1 bull_spread_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective bull_spread = bull_spread_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) exact_delta = sum( uncertainty_model.probabilities[np.logical_and(x >= strike_price_1, x <= strike_price_2)] ) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread, objective_qubits=[num_uncertainty_qubits], post_processing=bull_spread_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 0, 0] offsets = [0, 1, 0] f_min = 0 f_max = 1 bull_spread_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # no approximation necessary, hence no rescaling factor # construct the A operator by stacking the uncertainty model and payoff function together bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval) print("Exact delta: \t%.4f" % exact_delta) print("Estimated value:\t%.4f" % result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
from qiskit.optimization import QuadraticProgram from qiskit.optimization.algorithms import MinimumEigenOptimizer from dwave.plugins.qiskit import DWaveMinimumEigensolver from dwave.system import DWaveCliqueSampler, LeapHybridSampler import numpy as np A = np.array([[0,1,2,3,4,1], [2,1,4,1,0,2], [1,5,2,3,1,1], [0,0,1,2,2,0]]) m, n = A.shape c = np.array([-1,2,-2,2,1,1]) b = np.array([6,8,5,2]) solution = np.array([2,0,0,0,1,2]) print(all(A.dot(solution) == b)) model = QuadraticProgram("Integer Test") lowerbound = 0 upperbound = 7 # add variables x = [model.integer_var(lowerbound = lowerbound, upperbound = upperbound, name = 'x'+str(j)) for j in range(n)] # add linear constraints for i in range(m): model.linear_constraint(linear=A[i], sense='==', rhs=b[i], name='A'+str(i)+'eq'+'b'+str(i)) # add linear objective function model.minimize(linear = c) print(model.export_as_lp_string()) # Use D-Wave QPU as a minimum eigen solver # See https://github.com/dwavesystems/dwave-qiskit-plugin num_reads = 1000 cliqueSampler = DWaveCliqueSampler() dwave_solver_clique = DWaveMinimumEigensolver(sampler = cliqueSampler, num_reads = num_reads) optimizer = MinimumEigenOptimizer(dwave_solver_clique) result = optimizer.solve(model) # Problem ID : f684f451-2f9d-4ebd-ad84-983ac989838b print(result) result.min_eigen_solver_result.sampleset.to_pandas_dataframe() dwave_solver_hybrid = DWaveMinimumEigensolver(sampler = LeapHybridSampler()) optimizer = MinimumEigenOptimizer(dwave_solver_hybrid) result = optimizer.solve(model) # Problem ID : cef4cc6d-8686-4491-8eb7-3fdbba3b7ec2 print(result) result.min_eigen_solver_result.sampleset.to_pandas_dataframe()
https://github.com/ichen17/Learning-Qiskit
ichen17
from qiskit import * import numpy as np from random import random from qiskit.extensions import Initialize from qiskit.visualization import plot_histogram, plot_bloch_multivector ## SETUP # Protocol uses 3 qubits and 1 classical bit in a register qr = QuantumRegister(3, name="q") # Protocol uses 4 qubits cr1 = ClassicalRegister(1, name="cr1") # and 2 classical bit #cr2 = ClassicalRegister(1, name="cr2") bit_flip_circuit = QuantumCircuit(qr,cr1) def encoding(qc, q0, q1, q2): """Creates encoding process using qubits q0 & q1 & q2""" qc.cx(q0,q1) # CNOT with q1 as control and q0 as target qc.cx(q0,q2) # CNOT with q2 as control and q0 as target # initialization instruction to create # |ψ⟩ from the state |0⟩: p = 0.25 # p stands for the probability of fliping the state of the qubit psi = [np.sqrt(p), np.sqrt(1-p)] init_gate = Initialize(psi) # initialize the superposition state init_gate.label = "init" def measure(qc, q0, cr): """Measures qubit q0 """ qc.barrier() qc.measure(q0,cr) def decoding(qc, q0, q1, q2): """Creates decoding process using qubits q0 & q1 & q2""" qc.cx(q0,q1) # CNOT with q1 as control and q0 as target qc.cx(q0,q2) # CNOT with q2 as control and q0 as target qc.ccx(q2,q1,q0) # Apply a Toffoli gate |011> <-> |111> encoding(bit_flip_circuit, 0, 1, 2) # step 2. error simulation #bit_flip_circuit.append(Er,[0,1,2,3]) #error_simulation(bit_flip_circuit, 0, 1, 2, p) bit_flip_circuit.barrier() bit_flip_circuit.ry(np.pi/3,0)# Here rotate the spin around x axis by pi/3 so that the state will become 1/2|0>+sqrt(3)/2|1> bit_flip_circuit.ry(np.pi/3,1)# Here rotate the spin around x axis by pi/3 so that the state will become 1/2|0>+sqrt(3)/2|1> bit_flip_circuit.ry(np.pi/3,2)# Here rotate the spin around x axis by pi/3 so that the state will become 1/2|0>+sqrt(3)/2|1> bit_flip_circuit.barrier() # step 3. decoding decoding(bit_flip_circuit, 0, 1, 2) # step 4. measurement measure(bit_flip_circuit, 0, 0) # View the circuit: %matplotlib inline bit_flip_circuit.draw(output='mpl') backend = BasicAer.get_backend('qasm_simulator') counts = execute(bit_flip_circuit, backend, shots=1024).result().get_counts() # No. of measurement shots = 1024 plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import datetime import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt plt.rcParams.update({"text.usetex": True}) plt.rcParams["figure.figsize"] = (6,4) mpl.rcParams["figure.dpi"] = 200 from qiskit_ibm_runtime import Estimator, Session, QiskitRuntimeService, Options from qiskit.quantum_info import SparsePauliOp from qiskit import QuantumCircuit service = QiskitRuntimeService() backend_simulator = "backend_simulator" backend = "ibmq_montreal" qubits = 4 trotter_layer = QuantumCircuit(qubits) trotter_layer.rx(0.1, range(qubits)) trotter_layer.cx(0, 1) trotter_layer.cx(2, 3) trotter_layer.rz(-0.2, [1, 3]) trotter_layer.cx(0, 1) trotter_layer.cx(2, 3) trotter_layer.cx(1, 2) trotter_layer.rz(-0.2, 2) trotter_layer.cx(1, 2) num_steps = 6 trotter_circuit_list = [] for i in range(1, num_steps): trotter_circuit = QuantumCircuit(qubits) for _ in range(i): trotter_circuit = trotter_circuit.compose(trotter_layer) trotter_circuit_list.append(trotter_circuit) print(f'Trotter circuit with {i} Trotter steps`) display(trotter_circuit.draw(fold=-1)) obs = SparsePauliOp("Z"*qubits) obs_list = [obs]*len(trotter_circuit_list) options = Options() options.execution.shots = 1000 options.optimization_level = 0 # No optimization options.resilience_level = 0 # No mitigation with Session(service=service, backend=backend_simulator) as session: estimator_sim = Estimator(session=session, options=options) job_sim = estimator_sim.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_sim.job_id) print(job_sim.result()) expvals_ideal = job_sim.result().values expvals_ideal_variance = [metadata['variance']/metadata['shots'] for metadata in job_sim.result().metadata] std_error_ideal = np.sqrt(expvals_ideal_variance) options = Options() options.execution.shots = 1000 options.optimization_level = 0 # No optimization options.resilience_level = 0 # No error mitigation with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job.job_id) print(job.result()) expvals_unmit = job.result().values expvals_unmit_variance = [metadata['variance']/metadata['shots'] for metadata in job.result().metadata] std_error_unmit = np.sqrt(expvals_unmit_variance) options = Options() options.execution.shots = 1000 options.optimization_level = 3 # Dynamical decoupling options.resilience_level = 0 # No error mitigation with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job_dd = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_dd.job_id) print(job_dd.result()) expvals_unmit_dd = job_dd.result().values expvals_unmit_dd_variance = [metadata['variance']/metadata['shots'] for metadata in job_dd.result().metadata] std_error_dd = np.sqrt(expvals_unmit_dd_variance) plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_dd, std_error_dd, fmt = 'o', linestyle = '-', capsize=4, c='blue', label='Dynamical decoupling') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() options = Options() options.resilience_level = 1 # T-REx options.optimization_level = 0 # No optimization options.execution.shots = 1000 with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job_trex = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_trex.job_id) print(job_trex.result()) expvals_unmit_trex = job_trex.result().values expvals_unmit_trex_variance = [metadata['variance']/metadata['shots'] for metadata in job_trex.result().metadata] std_error_trex = np.sqrt(expvals_unmit_trex_variance) plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() options = Options() options.execution.shots = 1000 options.optimization_level = 0 # No optimization options.resilience_level = 2 # ZNE with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) job_zne = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_zne.job_id) print(job_zne.result()) expvals_unmit_zne = job_zne.result().values # Standard error: coming soon! plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE') plt.xlabel('No. Trotter Steps') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() def interim_results_callback(job_id, result): now = datetime.datetime.now() print(now, "*** Callback ***", result, "\n") options = Options() options.optimization_level = 0 # No optimization options.execution.shots = 100 options.resilience_level = 3 # PEC options.environment.callback = interim_results_callback with Session(service=service, backend=backend) as session: estimator_pec = Estimator(session=session, options=options) job_pec = estimator_pec.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_pec.job_id) expvals_pec = job_pec.result().values std_error_pec = [metadata['standard_error'] for metadata in job_pec.result().metadata] plt.title('Trotter circuits expectation value') plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() print(job_pec.result()) pec_metadata = job_pec.result().metadata fig, ax = plt.subplots() fig.subplots_adjust(right=0.75) twin1 = ax.twinx() twin2 = ax.twinx() twin3 = ax.twinx() twin2.spines.right.set_position(("axes", 1.2)) twin3.spines.right.set_position(("axes", 1.4)) p1, = ax.plot(range(1, num_steps), [m["total_mitigated_layers"] for m in pec_metadata] , "b-", label="Total mitigated layers") p2, = twin1.plot(range(1, num_steps), [m["sampling_overhead"] for m in pec_metadata], "r-", label="Sampling overhead") p3, = twin2.plot(range(1, num_steps), [m["samples"] for m in pec_metadata], "g-", label="Samples") p4, = twin3.plot(range(1, num_steps), [m["shots"] for m in pec_metadata], "c-", label="Shots") ax.set_ylim(0, 20) twin1.set_ylim(0, 2.8) twin2.set_ylim(0, 300) twin3.set_ylim(0, 35000) ax.set_xlabel("No. Trotter Steps") ax.set_ylabel("Total mitigated layers") twin1.set_ylabel("Sampling overhead") twin2.set_ylabel("Samples") twin3.set_ylabel("Shots") ax.yaxis.label.set_color(p1.get_color()) twin1.yaxis.label.set_color(p2.get_color()) twin2.yaxis.label.set_color(p3.get_color()) twin3.yaxis.label.set_color(p4.get_color()) tkw = dict(size=4, width=1.5) ax.tick_params(axis='y', colors=p1.get_color(), **tkw) twin1.tick_params(axis='y', colors=p2.get_color(), **tkw) twin2.tick_params(axis='y', colors=p3.get_color(), **tkw) twin3.tick_params(axis='y', colors=p4.get_color(), **tkw) plt.xticks([1, 2, 3, 4, 5]) ax.legend(handles=[p1, p2, p3, p4]) plt.title('PEC metadata') plt.show() from matplotlib.pyplot import figure plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal') plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation') plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx') plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE') plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC') plt.title('Trotter circuits expectation value') plt.ylabel(f"$\langle ZZZZ \\rangle$") plt.xlabel('No. Trotter Steps') plt.xticks([1, 2, 3, 4, 5]) plt.legend() plt.show() options = Options() options.execution.shots = 1000 options.optimization_level = 0 # no optimization options.resilience_level = 2 # ZNE options.resilience.noise_factors = [1, 2, 3, 4] options.resilience.noise_amplifier = "LocalFoldingAmplifier" options.resilience.extrapolator = "QuadraticExtrapolator" with Session(service=service, backend='ibmq_montreal') as session: estimator = Estimator(session=session, options=options) job_zne_options = estimator.run(circuits=trotter_circuit_list, observables=obs_list) print('job id:', job_zne_options.job_id) print(job_zne_options.result()) from qiskit.tools import jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Depth pass testing""" import unittest from qiskit import QuantumCircuit, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import CountOps from qiskit.test import QiskitTestCase class TestCountOpsPass(QiskitTestCase): """Tests for CountOps analysis methods.""" def test_empty_dag(self): """Empty DAG has empty counts.""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = CountOps() _ = pass_.run(dag) self.assertDictEqual(pass_.property_set["count_ops"], {}) def test_just_qubits(self): """A dag with 8 operations (6 CXs and 2 Hs)""" # ┌───┐ ┌───┐┌───┐ # q0_0: ┤ H ├──■────■────■────■──┤ X ├┤ X ├ # ├───┤┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐└─┬─┘└─┬─┘ # q0_1: ┤ H ├┤ X ├┤ X ├┤ X ├┤ X ├──■────■── # └───┘└───┘└───┘└───┘└───┘ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = CountOps() _ = pass_.run(dag) self.assertDictEqual(pass_.property_set["count_ops"], {"cx": 6, "h": 2}) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example showing how to draw a quantum circuit using Qiskit. """ from qiskit import QuantumCircuit def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) return qc # Create the circuit bell_circuit = build_bell_circuit() # Use the internal .draw() to print the circuit print(bell_circuit)
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/vindem/quantumMD
vindem
from qiskit import IBMQ, Aer from qiskit.aqua import QuantumInstance from qiskit.providers.aer.noise import NoiseModel from qiskit.ignis.mitigation.measurement import CompleteMeasFitter #Loading data about our backend quantum architecture IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend_sim = Aer.get_backend("qasm_simulator") backend_real = provider.get_backend("ibmq_lima") coupling_map = backend_real.configuration().coupling_map # Extracting noise model for error mitigation noise_model = NoiseModel.from_backend(backend_real) # Initializing quantum instance with error mitigation based on noise model of backend_real quantum_instance = QuantumInstance(backend=backend_sim, shots=20000, noise_model=noise_model, coupling_map=coupling_map, measurement_error_mitigation_cls=CompleteMeasFitter, cals_matrix_refresh_period=30) from qiskit.aqua.components.optimizers import COBYLA optimizer = COBYLA(maxiter=5000, tol=0.0001) from qiskit.aqua.operators import MatrixOperator, op_converter import numpy as np #Initialization of a 2x2 matrix in the same shape as MD program dimensions = 2 rdist = np.random.rand(dimensions,dimensions) rdist[0][0] = 1.0 rdist[0][1] = 2.0 rdist[1][0] = 1.0 rdist[1][1] = 3.0 rdistt = np.transpose(rdist) z1 = np.zeros((dimensions,dimensions)) z2 = np.zeros((dimensions,dimensions)) in_matrix = np.block([[z1,rdist],[rdistt,z2]]) #Converting matrix into operator hamiltonian = MatrixOperator(in_matrix) hamiltonian_qubit_op = op_converter.to_weighted_pauli_operator(hamiltonian) from qiskit.circuit.library import RealAmplitudes best_ansatz_ever = RealAmplitudes(2,reps=2) best_ansatz_ever.draw(output='text') from qiskit.aqua.algorithms import VQE vqe = VQE(operator=hamiltonian_qubit_op,var_form=best_ansatz_ever,quantum_instance=quantum_instance, optimizer=optimizer) vqe_result = np.real(vqe.run(backend_sim)['eigenvalue']) print(vqe_result) import math import scipy.linalg as lin_alg #storing values of, respectively, classic and quantum eigenvalues classic = [] quantum = [] for i in range(1,100): #Initializing random matrix rdist = np.random.rand(dimensions,dimensions) rdistt = np.transpose(rdist) z1 = np.zeros((dimensions,dimensions)) z2 = np.zeros((dimensions,dimensions)) in_matrix = np.block([[z1,rdist],[rdistt,z2]]) #Conversion of matrix into operator hamiltonian = MatrixOperator(in_matrix) hamiltonian_qubit_op = op_converter.to_weighted_pauli_operator(hamiltonian) #Calculation of Quantum eigenvalue vqe = VQE(operator=hamiltonian_qubit_op,var_form=best_ansatz_ever,quantum_instance=quantum_instance, optimizer=optimizer) vqe_result = np.real(vqe.run(backend_sim)['eigenvalue']) #Calculation of Classic eigenvalue classic_result = lin_alg.eigvalsh(in_matrix)[0] #Storing eigenvalues of current matrix classic.append(classic_result) quantum.append(vqe_result) #Calculating mean square error, root mean square error, root mean square error MSE = np.square(np.subtract(classic,quantum)).mean() RMSE = math.sqrt(MSE) print("RMSE: "+str(RMSE)) format_rmse = "{:.4f}".format((RMSE/(max(classic)-min(classic)))*100.0) print("NRMSE: "+format_rmse+ "%")
https://github.com/ritamsarmah/cs239
ritamsarmah
#!/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/qiskit-community/prototype-zne
qiskit-community
# for loading execution context parameters from the environment import os from dotenv import load_dotenv # for (de)serializing results import json # for processing data import numpy as np # for extrapolation from scipy.optimize import curve_fit # for plotting results import matplotlib as mpl import matplotlib.pyplot as plt # for defining the circuits and observables constituting our expectation value problems from qiskit.circuit import QuantumCircuit, Parameter from qiskit.quantum_info import SparsePauliOp from qiskit.circuit.library import TwoLocal # for using real quantum hardware from qiskit import IBMQ, transpile from qiskit.primitives import Estimator from qiskit_ibm_runtime import QiskitRuntimeService from zne import ZNEStrategy from zne import Estimator as ZneEstimator from zne.noise_amplification import LocalFoldingAmplifier load_dotenv() TOKEN = os.environ["TOKEN"] HUB = os.environ["HUB"] GROUP = os.environ["GROUP"] PROJECT = os.environ["PROJECT"] BACKEND = os.environ["BACKEND"] service = QiskitRuntimeService(channel="ibm_quantum", instance=f"{HUB}/{GROUP}/{PROJECT}", token=TOKEN) IBMQ.enable_account(TOKEN) provider = IBMQ.get_provider(hub=HUB, group=GROUP, project=PROJECT) backend = provider.get_backend(BACKEND) mpl.rcParams['figure.dpi'] = 500 plt.rcParams.update({ "text.usetex": True, "font.family": "Computer Modern Roman" }) def plot_results( measured_data, exact_ev, experiment_repr, observable_repr, regime=None, regression_model=None, regression_guess=None, exact_color="#000000", measured_color="#dc267f", regression_color="#785ef0" ): if not regime: regime = len(measured_data["noise_factors"]) noise_factors = np.array(measured_data["noise_factors"][:regime]) measured_evs = np.array(measured_data["values"][:regime]) measured_errors = np.sqrt(np.array(measured_data["variances"][:regime]) / np.array(measured_data["num_shots"][:regime])) plt.plot([0, noise_factors[regime-1]], [exact_ev, exact_ev], "--", label=f"Exact", color=exact_color) unmitigated_ev = measured_evs[0] unmitigated_error = np.abs(exact_ev - unmitigated_ev) plt.errorbar([1], measured_evs[0], yerr=measured_errors[0], label=f"Unmitigated ($\Delta\left\langle H \\right\\rangle = {unmitigated_error:.3f}$)", fmt="s", color=measured_color) plt.plot(noise_factors, measured_evs, label=f"Measured", color=measured_color) plt.fill_between( noise_factors, measured_evs - measured_errors, measured_evs + measured_errors, alpha=0.5, color=measured_color, linewidth=0 ) if regression_model: popt, pcov = curve_fit(regression_model, measured_data['noise_factors'][:regime], measured_data['values'][:regime], p0=regression_guess) goodness_of_fit = np.linalg.norm(np.diag(pcov)) regression_domain = np.linspace(0, noise_factors[regime-1], 100) plt.plot(regression_domain, regression_model(regression_domain, *popt), label=f"Regression", color=regression_color) zne_ev = regression_model(0, *popt) zne_error = np.abs(exact_ev - zne_ev) plt.scatter([0], [zne_ev], label=f"Extrapolated ($\Delta\left\langle H \\right\\rangle = {zne_error:.3f}$)", marker="x", color=regression_color) plt.title(experiment_repr) plt.xlabel("Noise Factor ($n$)") plt.ylabel(f"Expectation Value ($\langle {observable_repr} \\rangle$)") plt.legend() plt.show() H2_GNDSTATE_WAVEFN = QuantumCircuit(2).compose( TwoLocal( rotation_blocks=["ry", "rz"], entanglement_blocks="cz", num_qubits=2 ).assign_parameters( [ 4.104009273873245, -6.046872443309065, 5.277223342332378, 1.5319564597237907, 4.893000083985066, -3.0921586512224257, -0.34939132286472496, 5.584790805066014, -4.161687737508674, -3.2391548739165845, 1.7436977108208878, 0.17441513089260774, 2.623695306064223, 0.03678956439381653, 2.410055788777767, -2.3250358101154913, ] ) ) H2_HAMILTONIAN = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) H2_GNDSTATE_ENERGY = -1.85727503 NOISE_FACTORS = tuple(range(1, 199 + 2, 2)) len(NOISE_FACTORS) with Estimator([H2_GNDSTATE_WAVEFN], [H2_HAMILTONIAN]) as estimator: simulated_energy = estimator([0], [0]).values[0] simulated_energy np.isclose(simulated_energy, H2_GNDSTATE_ENERGY) # with ZneEstimator( # circuits=[H2_GNDSTATE_WAVEFN], # observables=[H2_HAMILTONIAN], # service=service, # options={"backend": backend.name()}, # zne_strategy=ZNEStrategy(noise_factors=NOISE_FACTORS, noise_amplifier=LocalFoldingAmplifier()), # ) as estimator: # results = estimator( # circuits=[0], # observables=[0], # ) # data = { # "noise_factors": list(results.metadata[0]["zne"]["noise_factors"]), # "values": list(results.metadata[0]["zne"]["values"]), # "variances": list(results.metadata[0]["zne"]["variances"]), # "num_shots": [ result["shots"] for result in results.metadata[0]['zne']['remaining_metadata'] ] # } # with open('data.json', 'w') as f: # json.dump(data, f) with open('data.json', 'r') as f: data = json.load(f) plot_results(data, H2_GNDSTATE_ENERGY, "$H_2$ Ground State Simulation", "H") def linear(noise_factor, noiseless_ev, decay_rate): return noiseless_ev + decay_rate * noise_factor for regime in [3, 5, 20]: plot_results(data, H2_GNDSTATE_ENERGY, "$H_2$ Ground State Simulation (Linear ZNE)", "H", regime=regime, regression_model=linear) def damped_sinusoid(noise_factor, noiseless_ev, amplitude, frequency, decay_rate): return noiseless_ev + amplitude * ( 1 - np.cos(frequency * noise_factor) * np.exp(-decay_rate * noise_factor) ) plot_results(data, H2_GNDSTATE_ENERGY, "$H_2$ Ground State Simulation (Damped Sinusoid ZNE)", "H", regression_model=damped_sinusoid, regression_guess=[data["values"][0], 1, (2*np.pi)/(60*4), 0.01])
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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=missing-function-docstring, missing-module-docstring import unittest from inspect import signature from math import pi import numpy as np from scipy.linalg import expm from ddt import data, ddt, unpack from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute from qiskit.exceptions import QiskitError from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase from qiskit.circuit import Gate, ControlledGate from qiskit.circuit.library import ( U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, XXMinusYYGate, XXPlusYYGate, RZGate, XGate, YGate, GlobalPhaseGate, ) from qiskit import BasicAer from qiskit.quantum_info import Pauli from qiskit.quantum_info.operators.predicates import matrix_equal, is_unitary_matrix from qiskit.utils.optionals import HAS_TWEEDLEDUM from qiskit.quantum_info import Operator from qiskit import transpile class TestStandard1Q(QiskitTestCase): """Standard Extension Test. Gates with a single Qubit""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr) def test_barrier(self): self.circuit.barrier(self.qr[1]) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_barrier_wires(self): self.circuit.barrier(1) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_barrier_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.barrier, self.cr[0]) self.assertRaises(CircuitError, qc.barrier, self.cr) self.assertRaises(CircuitError, qc.barrier, (self.qr, "a")) self.assertRaises(CircuitError, qc.barrier, 0.0) def test_conditional_barrier_invalid(self): qc = self.circuit barrier = qc.barrier(self.qr) self.assertRaises(QiskitError, barrier.c_if, self.cr, 0) def test_barrier_reg(self): self.circuit.barrier(self.qr) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_barrier_none(self): self.circuit.barrier() self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual( self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2], self.qr2[0], self.qr2[1], self.qr2[2]), ) def test_ccx(self): self.circuit.ccx(self.qr[0], self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "ccx") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_ccx_wires(self): self.circuit.ccx(0, 1, 2) self.assertEqual(self.circuit[0].operation.name, "ccx") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_ccx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ccx, self.cr[0], self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.ccx, self.qr[0], self.qr[0], self.qr[2]) self.assertRaises(CircuitError, qc.ccx, 0.0, self.qr[0], self.qr[2]) self.assertRaises(CircuitError, qc.ccx, self.cr, self.qr, self.qr) self.assertRaises(CircuitError, qc.ccx, "a", self.qr[1], self.qr[2]) def test_ch(self): self.circuit.ch(self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ch") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_ch_wires(self): self.circuit.ch(0, 1) self.assertEqual(self.circuit[0].operation.name, "ch") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_ch_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ch, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.ch, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.ch, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.ch, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.ch, self.cr, self.qr) self.assertRaises(CircuitError, qc.ch, "a", self.qr[1]) def test_cif_reg(self): self.circuit.h(self.qr[0]).c_if(self.cr, 7) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[0],)) self.assertEqual(self.circuit[0].operation.condition, (self.cr, 7)) def test_cif_single_bit(self): self.circuit.h(self.qr[0]).c_if(self.cr[0], True) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[0],)) self.assertEqual(self.circuit[0].operation.condition, (self.cr[0], True)) def test_crz(self): self.circuit.crz(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "crz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_cry(self): self.circuit.cry(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "cry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crx(self): self.circuit.crx(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "crx") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crz_wires(self): self.circuit.crz(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "crz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_cry_wires(self): self.circuit.cry(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "cry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crx_wires(self): self.circuit.crx(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "crx") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.crz, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.crz, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.crz, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.crz, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.crz, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.crz, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.crz, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.crz, 'a', self.qr[1], self.qr[2]) def test_cry_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cry, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.cry, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cry, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cry, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.cry, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cry, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.cry, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.cry, 'a', self.qr[1], self.qr[2]) def test_crx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.crx, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.crx, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.crx, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.crx, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.crx, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.crx, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.crx, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.crx, 'a', self.qr[1], self.qr[2]) def test_cswap(self): self.circuit.cswap(self.qr[0], self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cswap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_cswap_wires(self): self.circuit.cswap(0, 1, 2) self.assertEqual(self.circuit[0].operation.name, "cswap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_cswap_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cswap, self.qr[1], self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.qr[1], 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.qr[0], self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, 0.0, self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, (self.qr, 3), self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, self.cr, self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, "a", self.qr[1], self.qr[2]) def test_cu1(self): self.circuit.append(CU1Gate(1), [self.qr[1], self.qr[2]]) self.assertEqual(self.circuit[0].operation.name, "cu1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu1_wires(self): self.circuit.append(CU1Gate(1), [1, 2]) self.assertEqual(self.circuit[0].operation.name, "cu1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu3(self): self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr[2]]) self.assertEqual(self.circuit[0].operation.name, "cu3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu3_wires(self): self.circuit.append(CU3Gate(1, 2, 3), [1, 2]) self.assertEqual(self.circuit[0].operation.name, "cu3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx(self): self.circuit.cx(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cx") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx_wires(self): self.circuit.cx(1, 2) self.assertEqual(self.circuit[0].operation.name, "cx") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cx, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cx, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cx, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cx, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cx, self.cr, self.qr) self.assertRaises(CircuitError, qc.cx, "a", self.qr[1]) def test_cy(self): self.circuit.cy(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cy") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cy_wires(self): self.circuit.cy(1, 2) self.assertEqual(self.circuit[0].operation.name, "cy") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cy_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cy, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cy, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cy, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cy, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cy, self.cr, self.qr) self.assertRaises(CircuitError, qc.cy, "a", self.qr[1]) def test_cz(self): self.circuit.cz(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cz") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cz_wires(self): self.circuit.cz(1, 2) self.assertEqual(self.circuit[0].operation.name, "cz") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cz, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cz, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cz, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cz, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cz, self.cr, self.qr) self.assertRaises(CircuitError, qc.cz, "a", self.qr[1]) def test_h(self): self.circuit.h(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_h_wires(self): self.circuit.h(1) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_h_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.h, self.cr[0]) self.assertRaises(CircuitError, qc.h, self.cr) self.assertRaises(CircuitError, qc.h, (self.qr, 3)) self.assertRaises(CircuitError, qc.h, (self.qr, "a")) self.assertRaises(CircuitError, qc.h, 0.0) def test_h_reg(self): instruction_set = self.circuit.h(self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "h") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_h_reg_inv(self): instruction_set = self.circuit.h(self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "h") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_iden(self): self.circuit.i(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "id") self.assertEqual(self.circuit[0].operation.params, []) def test_iden_wires(self): self.circuit.i(1) self.assertEqual(self.circuit[0].operation.name, "id") self.assertEqual(self.circuit[0].operation.params, []) def test_iden_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.i, self.cr[0]) self.assertRaises(CircuitError, qc.i, self.cr) self.assertRaises(CircuitError, qc.i, (self.qr, 3)) self.assertRaises(CircuitError, qc.i, (self.qr, "a")) self.assertRaises(CircuitError, qc.i, 0.0) def test_iden_reg(self): instruction_set = self.circuit.i(self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "id") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_iden_reg_inv(self): instruction_set = self.circuit.i(self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "id") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_rx(self): self.circuit.rx(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [1]) def test_rx_wires(self): self.circuit.rx(1, 1) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [1]) def test_rx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rx, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.rx, self.qr[1], 0) self.assertRaises(CircuitError, qc.rx, 0, self.cr[0]) self.assertRaises(CircuitError, qc.rx, 0, 0.0) self.assertRaises(CircuitError, qc.rx, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.rx, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.rx, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.rx, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.rx, 0, "a") def test_rx_reg(self): instruction_set = self.circuit.rx(1, self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "rx") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_rx_reg_inv(self): instruction_set = self.circuit.rx(1, self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "rx") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_rx_pi(self): qc = self.circuit qc.rx(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry(self): self.circuit.ry(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry_wires(self): self.circuit.ry(1, 1) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ry, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.ry, self.qr[1], 0) self.assertRaises(CircuitError, qc.ry, 0, self.cr[0]) self.assertRaises(CircuitError, qc.ry, 0, 0.0) self.assertRaises(CircuitError, qc.ry, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.ry, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.ry, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.ry, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.ry, 0, "a") def test_ry_reg(self): instruction_set = self.circuit.ry(1, self.qr) self.assertEqual(instruction_set[0].operation.name, "ry") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_ry_reg_inv(self): instruction_set = self.circuit.ry(1, self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "ry") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_ry_pi(self): qc = self.circuit qc.ry(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) def test_rz(self): self.circuit.rz(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rz_wires(self): self.circuit.rz(1, 1) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rz, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.rz, self.qr[1], 0) self.assertRaises(CircuitError, qc.rz, 0, self.cr[0]) self.assertRaises(CircuitError, qc.rz, 0, 0.0) self.assertRaises(CircuitError, qc.rz, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.rz, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.rz, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.rz, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.rz, 0, "a") def test_rz_reg(self): instruction_set = self.circuit.rz(1, self.qr) self.assertEqual(instruction_set[0].operation.name, "rz") self.assertEqual(instruction_set[2].operation.params, [1]) def test_rz_reg_inv(self): instruction_set = self.circuit.rz(1, self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "rz") self.assertEqual(instruction_set[2].operation.params, [-1]) def test_rz_pi(self): self.circuit.rz(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rzz(self): self.circuit.rzz(1, self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "rzz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_rzz_wires(self): self.circuit.rzz(1, 1, 2) self.assertEqual(self.circuit[0].operation.name, "rzz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_rzz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rzz, 1, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.rzz, 1, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, self.cr, self.qr) self.assertRaises(CircuitError, qc.rzz, 1, "a", self.qr[1]) self.assertRaises(CircuitError, qc.rzz, 0.1, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.rzz, 0.1, self.qr[0], self.qr[0]) def test_s(self): self.circuit.s(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "s") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_s_wires(self): self.circuit.s(1) self.assertEqual(self.circuit[0].operation.name, "s") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_s_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.s, self.cr[0]) self.assertRaises(CircuitError, qc.s, self.cr) self.assertRaises(CircuitError, qc.s, (self.qr, 3)) self.assertRaises(CircuitError, qc.s, (self.qr, "a")) self.assertRaises(CircuitError, qc.s, 0.0) def test_s_reg(self): instruction_set = self.circuit.s(self.qr) self.assertEqual(instruction_set[0].operation.name, "s") self.assertEqual(instruction_set[2].operation.params, []) def test_s_reg_inv(self): instruction_set = self.circuit.s(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "sdg") self.assertEqual(instruction_set[2].operation.params, []) def test_sdg(self): self.circuit.sdg(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "sdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_sdg_wires(self): self.circuit.sdg(1) self.assertEqual(self.circuit[0].operation.name, "sdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_sdg_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.sdg, self.cr[0]) self.assertRaises(CircuitError, qc.sdg, self.cr) self.assertRaises(CircuitError, qc.sdg, (self.qr, 3)) self.assertRaises(CircuitError, qc.sdg, (self.qr, "a")) self.assertRaises(CircuitError, qc.sdg, 0.0) def test_sdg_reg(self): instruction_set = self.circuit.sdg(self.qr) self.assertEqual(instruction_set[0].operation.name, "sdg") self.assertEqual(instruction_set[2].operation.params, []) def test_sdg_reg_inv(self): instruction_set = self.circuit.sdg(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "s") self.assertEqual(instruction_set[2].operation.params, []) def test_swap(self): self.circuit.swap(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "swap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_swap_wires(self): self.circuit.swap(1, 2) self.assertEqual(self.circuit[0].operation.name, "swap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_swap_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.swap, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.swap, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.swap, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.swap, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.swap, self.cr, self.qr) self.assertRaises(CircuitError, qc.swap, "a", self.qr[1]) self.assertRaises(CircuitError, qc.swap, self.qr, self.qr2[[1, 2]]) self.assertRaises(CircuitError, qc.swap, self.qr[:2], self.qr2) def test_t(self): self.circuit.t(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "t") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_t_wire(self): self.circuit.t(1) self.assertEqual(self.circuit[0].operation.name, "t") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_t_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.t, self.cr[0]) self.assertRaises(CircuitError, qc.t, self.cr) self.assertRaises(CircuitError, qc.t, (self.qr, 3)) self.assertRaises(CircuitError, qc.t, (self.qr, "a")) self.assertRaises(CircuitError, qc.t, 0.0) def test_t_reg(self): instruction_set = self.circuit.t(self.qr) self.assertEqual(instruction_set[0].operation.name, "t") self.assertEqual(instruction_set[2].operation.params, []) def test_t_reg_inv(self): instruction_set = self.circuit.t(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "tdg") self.assertEqual(instruction_set[2].operation.params, []) def test_tdg(self): self.circuit.tdg(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "tdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_tdg_wires(self): self.circuit.tdg(1) self.assertEqual(self.circuit[0].operation.name, "tdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_tdg_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.tdg, self.cr[0]) self.assertRaises(CircuitError, qc.tdg, self.cr) self.assertRaises(CircuitError, qc.tdg, (self.qr, 3)) self.assertRaises(CircuitError, qc.tdg, (self.qr, "a")) self.assertRaises(CircuitError, qc.tdg, 0.0) def test_tdg_reg(self): instruction_set = self.circuit.tdg(self.qr) self.assertEqual(instruction_set[0].operation.name, "tdg") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_tdg_reg_inv(self): instruction_set = self.circuit.tdg(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "t") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_u1(self): self.circuit.append(U1Gate(1), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u1_wires(self): self.circuit.append(U1Gate(1), [1]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u1_reg(self): instruction_set = self.circuit.append(U1Gate(1), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u1") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_u1_reg_inv(self): instruction_set = self.circuit.append(U1Gate(1), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u1") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_u1_pi(self): qc = self.circuit qc.append(U1Gate(pi / 2), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2(self): self.circuit.append(U2Gate(1, 2), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [1, 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2_wires(self): self.circuit.append(U2Gate(1, 2), [1]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [1, 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2_reg(self): instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u2") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1, 2]) def test_u2_reg_inv(self): instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u2") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-pi - 2, -1 + pi]) def test_u2_pi(self): self.circuit.append(U2Gate(pi / 2, 0.3 * pi), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [pi / 2, 0.3 * pi]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3(self): self.circuit.append(U3Gate(1, 2, 3), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3_wires(self): self.circuit.append(U3Gate(1, 2, 3), [1]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3_reg(self): instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u3") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_u3_reg_inv(self): instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u3") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_u3_pi(self): self.circuit.append(U3Gate(pi, pi / 2, 0.3 * pi), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [pi, pi / 2, 0.3 * pi]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x(self): self.circuit.x(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "x") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x_wires(self): self.circuit.x(1) self.assertEqual(self.circuit[0].operation.name, "x") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.x, self.cr[0]) self.assertRaises(CircuitError, qc.x, self.cr) self.assertRaises(CircuitError, qc.x, (self.qr, "a")) self.assertRaises(CircuitError, qc.x, 0.0) def test_x_reg(self): instruction_set = self.circuit.x(self.qr) self.assertEqual(instruction_set[0].operation.name, "x") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_x_reg_inv(self): instruction_set = self.circuit.x(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "x") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_y(self): self.circuit.y(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "y") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_y_wires(self): self.circuit.y(1) self.assertEqual(self.circuit[0].operation.name, "y") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_y_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.y, self.cr[0]) self.assertRaises(CircuitError, qc.y, self.cr) self.assertRaises(CircuitError, qc.y, (self.qr, "a")) self.assertRaises(CircuitError, qc.y, 0.0) def test_y_reg(self): instruction_set = self.circuit.y(self.qr) self.assertEqual(instruction_set[0].operation.name, "y") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_y_reg_inv(self): instruction_set = self.circuit.y(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "y") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_z(self): self.circuit.z(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "z") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_z_wires(self): self.circuit.z(1) self.assertEqual(self.circuit[0].operation.name, "z") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_z_reg(self): instruction_set = self.circuit.z(self.qr) self.assertEqual(instruction_set[0].operation.name, "z") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_z_reg_inv(self): instruction_set = self.circuit.z(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "z") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_global_phase(self): qc = self.circuit qc.append(GlobalPhaseGate(0.1), []) self.assertEqual(self.circuit[0].operation.name, "global_phase") self.assertEqual(self.circuit[0].operation.params, [0.1]) self.assertEqual(self.circuit[0].qubits, ()) def test_global_phase_inv(self): instruction_set = self.circuit.append(GlobalPhaseGate(0.1), []).inverse() self.assertEqual(len(instruction_set), 1) self.assertEqual(instruction_set[0].operation.params, [-0.1]) def test_global_phase_matrix(self): """Test global_phase matrix.""" theta = 0.1 np.testing.assert_allclose( np.array(GlobalPhaseGate(theta)), np.array([[np.exp(1j * theta)]], dtype=complex), atol=1e-7, ) def test_global_phase_consistency(self): """Tests compatibility of GlobalPhaseGate with QuantumCircuit.global_phase""" theta = 0.1 qc1 = QuantumCircuit(0, global_phase=theta) qc2 = QuantumCircuit(0) qc2.append(GlobalPhaseGate(theta), []) np.testing.assert_allclose( Operator(qc1), Operator(qc2), atol=1e-7, ) def test_transpile_global_phase_consistency(self): """Tests compatibility of transpiled GlobalPhaseGate with QuantumCircuit.global_phase""" qc1 = QuantumCircuit(0, global_phase=0.3) qc2 = QuantumCircuit(0, global_phase=0.2) qc2.append(GlobalPhaseGate(0.1), []) np.testing.assert_allclose( Operator(transpile(qc1, basis_gates=["u"])), Operator(transpile(qc2, basis_gates=["u"])), atol=1e-7, ) @ddt class TestStandard2Q(QiskitTestCase): """Standard Extension Test. Gates with two Qubits""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr) def test_barrier_reg_bit(self): self.circuit.barrier(self.qr, self.qr2[0]) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2], self.qr2[0])) def test_ch_reg_reg(self): instruction_set = self.circuit.ch(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_reg_inv(self): instruction_set = self.circuit.ch(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_bit(self): instruction_set = self.circuit.ch(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual( instruction_set[1].qubits, ( self.qr[1], self.qr2[1], ), ) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_bit_inv(self): instruction_set = self.circuit.ch(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual( instruction_set[1].qubits, ( self.qr[1], self.qr2[1], ), ) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_bit_reg(self): instruction_set = self.circuit.ch(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_crz_reg_reg(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_reg_reg_inv(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crz_reg_bit(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_reg_bit_inv(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crz_bit_reg(self): instruction_set = self.circuit.crz(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_bit_reg_inv(self): instruction_set = self.circuit.crz(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_reg_reg(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_reg_reg_inv(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_reg_bit(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_reg_bit_inv(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_bit_reg(self): instruction_set = self.circuit.cry(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_bit_reg_inv(self): instruction_set = self.circuit.cry(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_reg_reg(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_reg_reg_inv(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_reg_bit(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_reg_bit_inv(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_bit_reg(self): instruction_set = self.circuit.crx(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_bit_reg_inv(self): instruction_set = self.circuit.crx(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_reg_reg(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_reg_reg_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_reg_bit(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_reg_bit_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_bit_reg(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_bit_reg_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu3_reg_reg(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_reg_reg_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cu3_reg_bit(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_reg_bit_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cu3_bit_reg(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_bit_reg_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cx_reg_reg(self): instruction_set = self.circuit.cx(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_reg_inv(self): instruction_set = self.circuit.cx(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_bit(self): instruction_set = self.circuit.cx(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_bit_inv(self): instruction_set = self.circuit.cx(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_bit_reg(self): instruction_set = self.circuit.cx(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_bit_reg_inv(self): instruction_set = self.circuit.cx(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_reg(self): instruction_set = self.circuit.cy(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_reg_inv(self): instruction_set = self.circuit.cy(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_bit(self): instruction_set = self.circuit.cy(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_bit_inv(self): instruction_set = self.circuit.cy(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_bit_reg(self): instruction_set = self.circuit.cy(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_bit_reg_inv(self): instruction_set = self.circuit.cy(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_reg(self): instruction_set = self.circuit.cz(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_reg_inv(self): instruction_set = self.circuit.cz(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_bit(self): instruction_set = self.circuit.cz(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_bit_inv(self): instruction_set = self.circuit.cz(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_bit_reg(self): instruction_set = self.circuit.cz(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_bit_reg_inv(self): instruction_set = self.circuit.cz(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_swap_reg_reg(self): instruction_set = self.circuit.swap(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "swap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_swap_reg_reg_inv(self): instruction_set = self.circuit.swap(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "swap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) @unpack @data( (0, 0, np.eye(4)), ( np.pi / 2, np.pi / 2, np.array( [ [np.sqrt(2) / 2, 0, 0, -np.sqrt(2) / 2], [0, 1, 0, 0], [0, 0, 1, 0], [np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2], ] ), ), ( np.pi, np.pi / 2, np.array([[0, 0, 0, -1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]), ), ( 2 * np.pi, np.pi / 2, np.array([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]), ), ( np.pi / 2, np.pi, np.array( [ [np.sqrt(2) / 2, 0, 0, 1j * np.sqrt(2) / 2], [0, 1, 0, 0], [0, 0, 1, 0], [1j * np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2], ] ), ), (4 * np.pi, 0, np.eye(4)), ) def test_xx_minus_yy_matrix(self, theta: float, beta: float, expected: np.ndarray): """Test XX-YY matrix.""" gate = XXMinusYYGate(theta, beta) np.testing.assert_allclose(np.array(gate), expected, atol=1e-7) def test_xx_minus_yy_exponential_formula(self): """Test XX-YY exponential formula.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXMinusYYGate(theta, beta) x = np.array(XGate()) y = np.array(YGate()) xx = np.kron(x, x) yy = np.kron(y, y) rz1 = np.kron(np.array(RZGate(beta)), np.eye(2)) np.testing.assert_allclose( np.array(gate), rz1 @ expm(-0.25j * theta * (xx - yy)) @ rz1.T.conj(), atol=1e-7, ) def test_xx_plus_yy_exponential_formula(self): """Test XX+YY exponential formula.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXPlusYYGate(theta, beta) x = np.array(XGate()) y = np.array(YGate()) xx = np.kron(x, x) yy = np.kron(y, y) rz0 = np.kron(np.eye(2), np.array(RZGate(beta))) np.testing.assert_allclose( np.array(gate), rz0.T.conj() @ expm(-0.25j * theta * (xx + yy)) @ rz0, atol=1e-7, ) class TestStandard3Q(QiskitTestCase): """Standard Extension Test. Gates with three Qubits""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.qr3 = QuantumRegister(3, "s") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.qr3, self.cr) def test_ccx_reg_reg_reg(self): instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3) self.assertEqual(instruction_set[0].operation.name, "ccx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ccx_reg_reg_inv(self): instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3).inverse() self.assertEqual(instruction_set[0].operation.name, "ccx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cswap_reg_reg_reg(self): instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3) self.assertEqual(instruction_set[0].operation.name, "cswap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cswap_reg_reg_inv(self): instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3).inverse() self.assertEqual(instruction_set[0].operation.name, "cswap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) class TestStandardMethods(QiskitTestCase): """Standard Extension Test.""" @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") def test_to_matrix(self): """test gates implementing to_matrix generate matrix which matches definition.""" from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate from qiskit.circuit.library.generalized_gates.pauli import PauliGate from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression params = [0.1 * (i + 1) for i in range(10)] gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() simulator = BasicAer.get_backend("unitary_simulator") for gate_class in gate_class_list: if hasattr(gate_class, "__abstractmethods__"): # gate_class is abstract continue sig = signature(gate_class) free_params = len(set(sig.parameters) - {"label", "ctrl_state"}) try: if gate_class == PauliGate: # special case due to PauliGate using string parameters gate = gate_class("IXYZ") elif gate_class == BooleanExpression: gate = gate_class("x") elif gate_class == PauliEvolutionGate: gate = gate_class(Pauli("XYZ")) else: gate = gate_class(*params[0:free_params]) except (CircuitError, QiskitError, AttributeError, TypeError): self.log.info("Cannot init gate with params only. Skipping %s", gate_class) continue if gate.name in ["U", "CX"]: continue circ = QuantumCircuit(gate.num_qubits) circ.append(gate, range(gate.num_qubits)) try: gate_matrix = gate.to_matrix() except CircuitError: # gate doesn't implement to_matrix method: skip self.log.info('to_matrix method FAILED for "%s" gate', gate.name) continue definition_unitary = execute([circ], simulator).result().get_unitary() with self.subTest(gate_class): # TODO check for exact equality once BasicAer can handle global phase self.assertTrue(matrix_equal(definition_unitary, gate_matrix, ignore_phase=True)) self.assertTrue(is_unitary_matrix(gate_matrix)) @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") def test_to_matrix_op(self): """test gates implementing to_matrix generate matrix which matches definition using Operator.""" from qiskit.circuit.library.generalized_gates.gms import MSGate from qiskit.circuit.library.generalized_gates.pauli import PauliGate from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression params = [0.1 * i for i in range(1, 11)] gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() for gate_class in gate_class_list: if hasattr(gate_class, "__abstractmethods__"): # gate_class is abstract continue sig = signature(gate_class) if gate_class == MSGate: # due to the signature (num_qubits, theta, *, n_qubits=Noe) the signature detects # 3 arguments but really its only 2. This if can be removed once the deprecated # n_qubits argument is no longer supported. free_params = 2 else: free_params = len(set(sig.parameters) - {"label", "ctrl_state"}) try: if gate_class == PauliGate: # special case due to PauliGate using string parameters gate = gate_class("IXYZ") elif gate_class == BooleanExpression: gate = gate_class("x") elif gate_class == PauliEvolutionGate: gate = gate_class(Pauli("XYZ")) else: gate = gate_class(*params[0:free_params]) except (CircuitError, QiskitError, AttributeError, TypeError): self.log.info("Cannot init gate with params only. Skipping %s", gate_class) continue if gate.name in ["U", "CX"]: continue try: gate_matrix = gate.to_matrix() except CircuitError: # gate doesn't implement to_matrix method: skip self.log.info('to_matrix method FAILED for "%s" gate', gate.name) continue if not hasattr(gate, "definition") or not gate.definition: continue definition_unitary = Operator(gate.definition).data self.assertTrue(matrix_equal(definition_unitary, gate_matrix)) self.assertTrue(is_unitary_matrix(gate_matrix)) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/Ben-Foxman/Quantum-Exploration
Ben-Foxman
my_list = [1, 3, 5, 2, 4, 9, 5, 8, 0, 7, 6] def the_oracle(my_input): winner = 7 return my_input == winner for index, trial_number in enumerate(my_list): if the_oracle(trial_number): print(f"Found the winner at index {index}!") print(f"{index+1} calls made") break from qiskit import * from qiskit.visualization import plot_histogram, array_to_latex from qiskit.providers.ibmq import least_busy import matplotlib.pyplot as plt import numpy as np grover_circuit = QuantumCircuit(2) def init_state(qc, qubits): for q in qubits: qc.h(q) return qc grover_circuit = init_state(grover_circuit, [0, 1]) grover_circuit.draw("mpl") #define the oracle circuit def oracle(qc, qubits): qc.cz(qubits[0], qubits[1]) qc = QuantumCircuit(2) oracle(qc, [0, 1]) qc.draw("mpl") usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{One can see that only the state }\ket{11}\\text{ has been flipped: }\n") def diffusion(qc, qubits): qc.h([0, 1]) qc.z([0, 1]) qc.cz(0, 1) qc.h([0, 1]) grover_circuit.barrier() oracle(grover_circuit, [0, 1]) grover_circuit.barrier() diffusion(grover_circuit, [0, 1]) grover_circuit.measure_all() grover_circuit.draw("mpl") # Let's see if the final statevector matches our expectations sv_sim = Aer.get_backend('statevector_simulator') result = sv_sim.run(grover_circuit).result() statevec = result.get_statevector() statevec aer_sim = Aer.get_backend('aer_simulator') result = execute(grover_circuit, aer_sim, shots=1024).result() result.get_counts() # Load IBM Q account and get the least busy backend device # Run the following line with your API token to use IBM's own quantum computers #IBMQ.save_account('') provider = IBMQ.load_account() provider = IBMQ.get_provider("ibm-q") device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_grover_circuit = transpile(grover_circuit, device, optimization_level=3) job = device.run(transpiled_grover_circuit) job_monitor(job, interval=2) # Get the results from the computation results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) grover_circuit = QuantumCircuit(3) grover_circuit = init_state(grover_circuit, [0, 1, 2]) grover_circuit.draw("mpl") oracle_qc = QuantumCircuit(3) oracle_qc.cz(0, 1) oracle_qc.cz(0, 2) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "U$_\omega$" def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> -> |11..1> for qubit in range(nqubits): qc.h(qubit) qc.x(qubit) # When these are combined, they function as a multi-controlled Z gate # A negative phase is added to |11..1> to flip the state qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> -> |s> for qubit in range(nqubits): qc.x(qubit) qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s num_qubits = 3 grover_circuit = QuantumCircuit(num_qubits) grover_circuit = init_state(grover_circuit, [0, 1, 2]) grover_circuit.barrier() grover_circuit.append(oracle_gate, [0, 1, 2]) grover_circuit.barrier() grover_circuit.append(diffuser(num_qubits), [0, 1, 2]) grover_circuit.measure_all() grover_circuit.draw("mpl") qasm_sim = Aer.get_backend('qasm_simulator') transpiled_grover_circuit = transpile(grover_circuit, qasm_sim) results = qasm_sim.run(transpiled_grover_circuit).result() counts = results.get_counts() plot_histogram(counts) backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 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 transpiled_grover_circuit = transpile(grover_circuit, device, optimization_level=3) job = device.run(transpiled_grover_circuit) job_monitor(job, interval=2) # Get the results from the computation results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer)
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Bitstring functions.""" from qiskit import QuantumCircuit def prepare_bitstring(bitstring, name=None): """Prepares bitstrings.""" # First bit in bitstring is the first qubit in the circuit. qcirc = QuantumCircuit(len(bitstring), name=name) for qb_idx, bit in enumerate(bitstring): if bit: qcirc.x(qb_idx) return qcirc
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# class unknown_qubit # available_qubit = 1000 -> you get at most 1000 qubit copies # get_qubits(number_of_qubits) -> you get the specified number of qubits for your experiment # measure_qubits() -> your qubits are measured and the result is returned as a dictionary variable # -> after measurement, these qubits are destroyed # rotate_qubits(angle) -> your qubits are rotated with the specified angle in radian # compare_my_guess(my_angle) -> your guess in radian is compared with the real angle from random import randrange from math import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer class unknown_qubit: def __init__(self): self.__theta = randrange(18000)/18000*pi self.__available_qubits = 1000 self.__active_qubits = 0 print(self.__available_qubits,"qubits are created") def get_qubits(self,number_of_qubits=None): if number_of_qubits is None or isinstance(number_of_qubits,int) is False or number_of_qubits < 1: print() print("ERROR: the method 'get_qubits' takes the number of qubit(s) as a positive integer, i.e., get_qubits(100)") elif number_of_qubits <= self.__available_qubits: self.__qc = QuantumCircuit(1,1) self.__qc.ry(2 * self.__theta,0) self.__active_qubits = number_of_qubits self.__available_qubits = self.__available_qubits - self.__active_qubits print() print("You have",number_of_qubits,"active qubits that are set to (cos(theta),sin(theta))") self.available_qubits() else: print() print("WARNING: you requested",number_of_qubits,"qubits, but there is not enough available qubits!") self.available_qubits() def measure_qubits(self): if self.__active_qubits > 0: self.__qc.measure(0,0) job = execute(self.__qc,Aer.get_backend('qasm_simulator'),shots=self.__active_qubits) counts = job.result().get_counts(self.__qc) print() print("your",self.__active_qubits,"qubits are measured") print("counts = ",counts) self.__active_qubits = 0 return counts else: print() print("WARNING: there is no active qubits -- you might first execute 'get_qubits()' method") self.available_qubits() def rotate_qubits(self,angle=None): if angle is None or (isinstance(angle,float) is False and isinstance(angle,int) is False): print() print("ERROR: the method 'rotate_qubits' takes a real-valued angle in radian as its parameter, i.e., rotate_qubits(1.2121)") elif self.__active_qubits > 0: self.__qc.ry(2 * angle,0) print() print("your active qubits are rotated by angle",angle,"in radian") else: print() print("WARNING: there is no active qubits -- you might first execute 'get_qubits()' method") self.available_qubits() def compare_my_guess(self,my_angle): if my_angle is None or (isinstance(my_angle,float) is False and isinstance(my_angle,int) is False): print("ERROR: the method 'compare_my_guess' takes a real-valued angle in radian as your guessed angle, i.e., compare_my_guess(1.2121)") else: self.__available_qubits = 0 diff = abs(my_angle-self.__theta) print() print(self.__theta,"is the original",) print(my_angle,"is your guess") print("the angle difference between the original theta and your guess is",diff/pi*180,"degree") print("-->the number of available qubits is (set to) zero, and so you cannot make any further experiment") def available_qubits(self): print("--> the number of available unused qubit(s) is",self.__available_qubits) from math import pi, cos, sin, acos, asin # an angle theta is randomly picked and it is fixed througout the experiment my_experiment = unknown_qubit() # # my_experiment.get_qubits(number_of_qubits) # my_experiment.rotate_qubits(angle) # my_experiment.measure_qubits() # my_experiment.compare_my_guess(my_angle) # # # your solution is here # # class unknown_qubit # available_qubit = 1000 -> you get at most 1000 qubit copies # get_qubits(number_of_qubits) -> you get the specified number of qubits for your experiment # measure_qubits() -> your qubits are measured and the result is returned as a dictionary variable # -> after measurement, these qubits are destroyed # rotate_qubits(angle) -> your qubits are rotated with the specified angle in radian # compare_my_guess(my_angle) -> your guess in radian is compared with the real angle from random import randrange from math import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer class unknown_qubit: def __init__(self): self.__theta = randrange(18000)/18000*pi self.__available_qubits = 1000 self.__active_qubits = 0 print(self.__available_qubits,"qubits are created") def get_qubits(self,number_of_qubits=None): if number_of_qubits is None or isinstance(number_of_qubits,int) is False or number_of_qubits < 1: print() print("ERROR: the method 'get_qubits' takes the number of qubit(s) as a positive integer, i.e., get_qubits(100)") elif number_of_qubits <= self.__available_qubits: self.__qc = QuantumCircuit(1,1) self.__qc.ry(2 * self.__theta,0) self.__active_qubits = number_of_qubits self.__available_qubits = self.__available_qubits - self.__active_qubits print() print("You have",number_of_qubits,"active qubits that are set to (cos(theta),sin(theta))") self.available_qubits() else: print() print("WARNING: you requested",number_of_qubits,"qubits, but there is not enough available qubits!") self.available_qubits() def measure_qubits(self): if self.__active_qubits > 0: self.__qc.measure(0,0) job = execute(self.__qc,Aer.get_backend('qasm_simulator'),shots=self.__active_qubits) counts = job.result().get_counts(self.__qc) print() print("your",self.__active_qubits,"qubits are measured") print("counts = ",counts) self.__active_qubits = 0 return counts else: print() print("WARNING: there is no active qubits -- you might first execute 'get_qubits()' method") self.available_qubits() def rotate_qubits(self,angle=None): if angle is None or (isinstance(angle,float) is False and isinstance(angle,int) is False): print() print("ERROR: the method 'rotate_qubits' takes a real-valued angle in radian as its parameter, i.e., rotate_qubits(1.2121)") elif self.__active_qubits > 0: self.__qc.ry(2 * angle,0) print() print("your active qubits are rotated by angle",angle,"in radian") else: print() print("WARNING: there is no active qubits -- you might first execute 'get_qubits()' method") self.available_qubits() def compare_my_guess(self,my_angle): if my_angle is None or (isinstance(my_angle,float) is False and isinstance(my_angle,int) is False): print("ERROR: the method 'compare_my_guess' takes a real-valued angle in radian as your guessed angle, i.e., compare_my_guess(1.2121)") else: self.__available_qubits = 0 diff = abs(my_angle-self.__theta) print() print(self.__theta,"is the original",) print(my_angle,"is your guess") print("the angle difference between the original theta and your guess is",diff/pi*180,"degree") print("-->the number of available qubits is (set to) zero, and so you cannot make any further experiment") def available_qubits(self): print("--> the number of available unused qubit(s) is",self.__available_qubits) from math import pi, cos, sin, acos, asin my_experiment = unknown_qubit() # we use 900 copies to determine our two candidates my_experiment.get_qubits(900) counts = my_experiment.measure_qubits() number_of_observed_zeros = 0 if '0' in counts: number_of_observed_zeros = counts['0'] probability_of_observing_zeros = number_of_observed_zeros/900 cos_theta = probability_of_observing_zeros ** 0.5 theta = acos(cos_theta) theta_first_candidate = theta theta_second_candidate = pi-theta print("the first candidate is",theta_first_candidate,"in radian and",theta_first_candidate*180/pi,"in degree") print("the second candidate is",theta_second_candidate,"in radian and",theta_second_candidate*180/pi,"in degree") my_experiment.get_qubits(100) my_experiment.rotate_qubits(-1 * theta_first_candidate) counts = my_experiment.measure_qubits() number_of_observed_zeros = 0 if '0' in counts: number_of_observed_zeros = counts['0'] if number_of_observed_zeros == 100: my_guess = theta_first_candidate else: my_guess = theta_second_candidate my_experiment.compare_my_guess(my_guess) for i in range(10): print("Experiment",(i+1)) print("___________") print() my_experiment = unknown_qubit() my_experiment.get_qubits(900) counts = my_experiment.measure_qubits() number_of_observed_zeros = 0 if '0' in counts: number_of_observed_zeros = counts['0'] probability_of_observing_zeros = number_of_observed_zeros/900 cos_theta = probability_of_observing_zeros ** 0.5 theta = acos(cos_theta) theta_first_candidate = theta theta_second_candidate = pi-theta my_experiment.get_qubits(100) my_experiment.rotate_qubits(-1 * theta_first_candidate) counts = my_experiment.measure_qubits() number_of_observed_zeros = 0 if '0' in counts: number_of_observed_zeros = counts['0'] if number_of_observed_zeros == 100: my_guess = theta_first_candidate else: my_guess = theta_second_candidate my_experiment.compare_my_guess(my_guess) print() print() print() # # your solution #
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 BackendSampler.""" import math import unittest from unittest.mock import patch from test import combine from test.python.transpiler._dummy_passes import DummyTP import numpy as np from ddt import ddt from qiskit import QuantumCircuit from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import BackendSampler, SamplerResult from qiskit.providers import JobStatus, JobV1 from qiskit.providers.fake_provider import FakeNairobi, FakeNairobiV2 from qiskit.providers.basicaer import QasmSimulatorPy from qiskit.test import QiskitTestCase from qiskit.transpiler import PassManager from qiskit.utils import optionals BACKENDS = [FakeNairobi(), FakeNairobiV2()] @ddt class TestBackendSampler(QiskitTestCase): """Test BackendSampler""" def setUp(self): super().setUp() hadamard = QuantumCircuit(1, 1) hadamard.h(0) hadamard.measure(0, 0) bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell.measure_all() self._circuit = [hadamard, bell] self._target = [ {0: 0.5, 1: 0.5}, {0: 0.5, 3: 0.5, 1: 0, 2: 0}, ] self._pqc = RealAmplitudes(num_qubits=2, reps=2) self._pqc.measure_all() self._pqc2 = RealAmplitudes(num_qubits=2, reps=3) self._pqc2.measure_all() self._pqc_params = [[0.0] * 6, [1.0] * 6] self._pqc_target = [{0: 1}, {0: 0.0148, 1: 0.3449, 2: 0.0531, 3: 0.5872}] self._theta = [ [0, 1, 1, 2, 3, 5], [1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], ] def _generate_circuits_target(self, indices): if isinstance(indices, list): circuits = [self._circuit[j] for j in indices] target = [self._target[j] for j in indices] else: raise ValueError(f"invalid index {indices}") return circuits, target def _generate_params_target(self, indices): if isinstance(indices, int): params = self._pqc_params[indices] target = self._pqc_target[indices] elif isinstance(indices, list): params = [self._pqc_params[j] for j in indices] target = [self._pqc_target[j] for j in indices] else: raise ValueError(f"invalid index {indices}") return params, target def _compare_probs(self, prob, target): if not isinstance(prob, list): prob = [prob] if not isinstance(target, list): target = [target] self.assertEqual(len(prob), len(target)) for p, targ in zip(prob, target): for key, t_val in targ.items(): if key in p: self.assertAlmostEqual(p[key], t_val, delta=0.1) else: self.assertAlmostEqual(t_val, 0, delta=0.1) @combine(backend=BACKENDS) def test_sampler_run(self, backend): """Test Sampler.run().""" bell = self._circuit[1] sampler = BackendSampler(backend=backend) job = sampler.run(circuits=[bell], shots=1000) self.assertIsInstance(job, JobV1) result = job.result() self.assertIsInstance(result, SamplerResult) self.assertEqual(result.quasi_dists[0].shots, 1000) self.assertEqual(result.quasi_dists[0].stddev_upper_bound, math.sqrt(1 / 1000)) self._compare_probs(result.quasi_dists, self._target[1]) @combine(backend=BACKENDS) def test_sample_run_multiple_circuits(self, backend): """Test Sampler.run() with multiple circuits.""" # executes three Bell circuits # Argument `parameters` is optional. bell = self._circuit[1] sampler = BackendSampler(backend=backend) result = sampler.run([bell, bell, bell]).result() # print([q.binary_probabilities() for q in result.quasi_dists]) self._compare_probs(result.quasi_dists[0], self._target[1]) self._compare_probs(result.quasi_dists[1], self._target[1]) self._compare_probs(result.quasi_dists[2], self._target[1]) @combine(backend=BACKENDS) def test_sampler_run_with_parameterized_circuits(self, backend): """Test Sampler.run() with parameterized circuits.""" # parameterized circuit pqc = self._pqc pqc2 = self._pqc2 theta1, theta2, theta3 = self._theta sampler = BackendSampler(backend=backend) result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result() # result of pqc(theta1) prob1 = { "00": 0.1309248462975777, "01": 0.3608720796028448, "10": 0.09324865232050054, "11": 0.41495442177907715, } self.assertDictAlmostEqual(result.quasi_dists[0].binary_probabilities(), prob1, delta=0.1) # result of pqc(theta2) prob2 = { "00": 0.06282290651933871, "01": 0.02877144385576705, "10": 0.606654494132085, "11": 0.3017511554928094, } self.assertDictAlmostEqual(result.quasi_dists[1].binary_probabilities(), prob2, delta=0.1) # result of pqc2(theta3) prob3 = { "00": 0.1880263994380416, "01": 0.6881971261189544, "10": 0.09326232720582443, "11": 0.030514147237179892, } self.assertDictAlmostEqual(result.quasi_dists[2].binary_probabilities(), prob3, delta=0.1) @combine(backend=BACKENDS) def test_run_1qubit(self, backend): """test for 1-qubit cases""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSampler(backend=backend) result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1) @combine(backend=BACKENDS) def test_run_2qubit(self, backend): """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 = BackendSampler(backend=backend) result = sampler.run([qc0, qc1, qc2, qc3]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 4) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[2], {2: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[3], {3: 1}, 0.1) @combine(backend=BACKENDS) def test_run_errors(self, backend): """Test for errors""" qc1 = QuantumCircuit(1) qc1.measure_all() qc2 = RealAmplitudes(num_qubits=1, reps=1) qc2.measure_all() sampler = BackendSampler(backend=backend) with self.assertRaises(ValueError): sampler.run([qc1], [[1e2]]).result() with self.assertRaises(ValueError): sampler.run([qc2], [[]]).result() with self.assertRaises(ValueError): sampler.run([qc2], [[1e2]]).result() @combine(backend=BACKENDS) def test_run_empty_parameter(self, backend): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) sampler = BackendSampler(backend=backend) with self.subTest("one circuit"): result = sampler.run([qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 1) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} self.assertDictAlmostEqual(quasi_dist, {0: 1.0}, delta=0.1) self.assertEqual(len(result.metadata), 1) with self.subTest("two circuits"): result = sampler.run([qc, qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 2) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} self.assertDictAlmostEqual(quasi_dist, {0: 1.0}, delta=0.1) self.assertEqual(len(result.metadata), 2) @combine(backend=BACKENDS) def test_run_numpy_params(self, backend): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2) qc.measure_all() k = 5 params_array = np.random.rand(k, qc.num_parameters) params_list = params_array.tolist() params_list_array = list(params_array) sampler = BackendSampler(backend=backend) target = sampler.run([qc] * k, params_list).result() with self.subTest("ndarrary"): result = sampler.run([qc] * k, params_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictAlmostEqual(result.quasi_dists[i], target.quasi_dists[i], delta=0.1) with self.subTest("list of ndarray"): result = sampler.run([qc] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictAlmostEqual(result.quasi_dists[i], target.quasi_dists[i], delta=0.1) @combine(backend=BACKENDS) def test_run_with_shots_option(self, backend): """test with shots option.""" params, target = self._generate_params_target([1]) sampler = BackendSampler(backend=backend) result = sampler.run( circuits=[self._pqc], parameter_values=params, shots=1024, seed=15 ).result() self._compare_probs(result.quasi_dists, target) @combine(backend=BACKENDS) def test_primitive_job_status_done(self, backend): """test primitive job's status""" bell = self._circuit[1] sampler = BackendSampler(backend=backend) job = sampler.run(circuits=[bell]) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_primitive_job_size_limit_backend_v2(self): """Test primitive respects backend's job size limit.""" class FakeNairobiLimitedCircuits(FakeNairobiV2): """FakeNairobiV2 with job size limit.""" @property def max_circuits(self): return 1 qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSampler(backend=FakeNairobiLimitedCircuits()) result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1) def test_primitive_job_size_limit_backend_v1(self): """Test primitive respects backend's job size limit.""" backend = FakeNairobi() config = backend.configuration() config.max_experiments = 1 backend._configuration = config qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSampler(backend=backend) result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_circuit_with_dynamic_circuit(self): """Test BackendSampler with QuantumCircuit with a dynamic circuit""" from qiskit_aer import Aer 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) backend = Aer.get_backend("aer_simulator") backend.set_options(seed_simulator=15) sampler = BackendSampler(backend, skip_transpilation=True) sampler.set_transpile_options(seed_transpiler=15) result = sampler.run(qc).result() self.assertDictAlmostEqual(result.quasi_dists[0], {0: 0.5029296875, 1: 0.4970703125}) def test_sequential_run(self): """Test sequential run.""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSampler(backend=FakeNairobi()) result = sampler.run([qc]).result() self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) result2 = sampler.run([qc2]).result() self.assertDictAlmostEqual(result2.quasi_dists[0], {1: 1}, 0.1) result3 = sampler.run([qc, qc2]).result() self.assertDictAlmostEqual(result3.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result3.quasi_dists[1], {1: 1}, 0.1) def test_outcome_bitstring_size(self): """Test that the result bitstrings are properly padded. E.g. measuring '0001' should not get truncated to '1'. """ qc = QuantumCircuit(4) qc.x(0) qc.measure_all() # We need a noise-free backend here (shot noise is fine) to ensure that # the only bit string measured is "0001". With device noise, it could happen that # strings with a leading 1 are measured and then the truncation cannot be tested. sampler = BackendSampler(backend=QasmSimulatorPy()) result = sampler.run(qc).result() probs = result.quasi_dists[0].binary_probabilities() self.assertIn("0001", probs.keys()) self.assertEqual(len(probs), 1) def test_bound_pass_manager(self): """Test bound pass manager.""" with self.subTest("Test single circuit"): dummy_pass = DummyTP() with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass: bound_pass = PassManager(dummy_pass) sampler = BackendSampler(backend=FakeNairobi(), bound_pass_manager=bound_pass) _ = sampler.run(self._circuit[0]).result() self.assertEqual(mock_pass.call_count, 1) with self.subTest("Test circuit batch"): dummy_pass = DummyTP() with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass: bound_pass = PassManager(dummy_pass) sampler = BackendSampler(backend=FakeNairobi(), bound_pass_manager=bound_pass) _ = sampler.run([self._circuit[0], self._circuit[0]]).result() self.assertEqual(mock_pass.call_count, 2) if __name__ == "__main__": unittest.main()
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": ### removed x gate ### pass if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/quantum-kittens/quantum-computing-basics
quantum-kittens
# run this cell if you're executing this notebook in your browser !pip install qiskit from IPython.display import clear_output clear_output() from qiskit import * import numpy as np qc = QuantumCircuit(2,2) qc.draw('mpl') qreg = QuantumRegister(2, name = 'qreg') creg = ClassicalRegister(2, name = 'creg') qc = QuantumCircuit(qreg, creg) qc.draw('mpl') qc = QuantumCircuit(1) # set the angles to whatever you want theta = np.pi/2 phi = np.pi/4 lambdaa = np.pi # comment/uncomment the gates to play with them qc.x(0) # x on qubit 0 qc.y(0) # y on qubit 0 qc.z(0) # z on qubit 0 qc.s(0) # s gate on qubit 0, sqrt of z qc.sdg(0) # s† on qubit 0 qc.t(0) # t gate on qubit 0, sqrt of s qc.tdg(0) # t† on qubit 0 ### rotations qc.rx(theta,0) # rx rotation on qubit 0 qc.ry(theta,0) # ry rotation on qubit 0 qc.rz(theta,0) # rz rotation on qubit 0 ### generic qc.u(theta, phi, lambdaa, 0) #u3 gate qc.u2(phi, lambdaa, 0) #u2 = u3(pi/2, phi, lambdaa) qc.p(lambdaa, 0) #p = u1 = u3(0, 0, lambdaa) # display(qc.draw('mpl')) display(qc.draw()) qc = QuantumCircuit(2) # set the angles to whatever you want theta = np.pi/2 phi = np.pi/4 lambdaa = np.pi # comment/uncomment any of the following to your heart's content qc.cx(0,1) # CNOT with qubit 0 as control and qubit 1 as target qc.cy(0,1) # controlled-Y with qubit 0 as control and qubit 1 as target qc.cz(0,1) # controlled-Z with qubit 0 as control and qubit 1 as target qc.ch(0, 1) # controlled-H with qubit 0 as control and qubit 1 as target qc.cu3(theta, phi, lambdaa, 0, 1) # controlled-u3 with qubit 0 as control and qubit 1 as target qc.swap(0,1) # swap qubits 0 and 1 # qc.draw('mpl') from qiskit.circuit.library import CXGate qc = QuantumCircuit(3) # Method 1: qc.ccx(0,1,2) # Method 2: qc.mct([0,1],2) #Method 3 our_ccx = CXGate().control() qc.append(our_ccx, [0,1,2]) qc.draw('mpl') qc_bell = QuantumCircuit(2) qc_bell.h(0) qc_bell.cx(0,1) qc_bell.x(1) qc_bell.z(1) display(qc_bell.draw('mpl')) from qiskit.quantum_info import Statevector state = Statevector(qc_bell) state.draw('latex', prefix = '\\left|\\psi^-\\right\\rangle = ' ) bell_qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; gate bell a, b { u(pi/2, 0, pi) a; cx a, b; } qreg q[2]; creg c[2]; bell q[0], q[1]; x q[1]; z q[1]; barrier q[0],q[1]; measure q[0] -> c[0]; measure q[1] -> c[1]; """ qc_bell_qasm = QuantumCircuit.from_qasm_str(bell_qasm_string) qc_bell_qasm.draw('mpl') qc_bell_string = qc_bell.qasm() print(qc_bell_string) qc_bell_init = QuantumCircuit(2) qc_bell_init.h(0) qc_bell_init.cx(0,1) display(qc_bell_init.draw('mpl')) bell_gate = qc_bell_init.to_gate() bell_gate.name ='Bell Gate' qc_bell_gate = QuantumCircuit(2) qc_bell_gate.append(bell_gate, [0,1]) display(qc_bell_gate.draw('mpl')) from qiskit.quantum_info import Operator from qiskit.visualization import array_to_latex U = Operator(qc_bell) array_to_latex(U.data, prefix = 'U = ') from qiskit.providers.aer import UnitarySimulator backend = UnitarySimulator() # alternative: backend = Aer.get_backend('unitary_simulator') job = execute(qc_bell, backend) U = job.result().get_unitary() display(array_to_latex(U.data, prefix = 'U = ')) from qiskit.providers.aer import QasmSimulator qc_measure = QuantumCircuit(2,2) qc_measure.barrier() qc_measure.measure([0,1], [0,1]) # alternative: qc_measure = QuantumCircuit(2) | qc_measure.measure_all() = .barrier() + measure every qubit + creates a classical register qc_bell_measure = qc_measure.compose(qc_bell, range(2), front = True) # combines two circuits, placing qc_bell in front of qc_measure display(qc_bell_measure.draw('mpl')) backend = QasmSimulator() # alternative: backend = Aer.get_backend('qasm_simulator') job = execute(qc_bell_measure, backend, shots = 1024) # alternative: qc_transpiled = transpile(qc_bell_measure, backend), job = backend.run(qc_transpiled, shots = 1024) counts = job.result().get_counts() print('Counts: ' + str(counts)) from qiskit.visualization import plot_histogram plot_histogram(counts) job = execute(qc_bell_measure, backend, shots = 1024) counts_2 = job.result().get_counts() print('Counts, second experiment: ' + str(counts_2)) legend = ['First Experiment', 'Second Experiment'] plot_histogram([counts, counts_2], legend = legend, color = ['teal', 'black'], figsize = (10, 7), bar_labels = False) qc_ghz = QuantumCircuit(3) qc_ghz.h(0) qc_ghz.cx(0,1) qc_ghz.ccx(0,1,2) qc_ghz.draw('mpl') #original circuit display(qc_ghz.decompose().draw('mpl')) #decompose one level down display(qc_ghz.decompose().decompose().draw('mpl')) #decompose two levels down from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller gates_pass = Unroller(['u1', 'u2', 'u3', 'cx']) #play around with this pm = PassManager(gates_pass) pm.run(qc_ghz).draw('mpl') print('The circuit depth of the Bell circuit without measurements is: ' + str(qc_bell.depth())) #Qiskit counts the measurements in the depth calculation: print('The circuit depth of the Bell circuit with measurements is: ' + str(qc_bell_measure.depth())) from qiskit.circuit.random import random_circuit import random #play around with these parameters: num_qubits = 3 max_depth = 10 add_measurements = True #True/False #random circuit: rand_circ = random_circuit(num_qubits, depth = random.randint(1,max_depth), measure=add_measurements) rand_circ.draw('mpl') # run this cell to see if you are correct print('The circuit depth is: ' + str(rand_circ.depth()))
https://github.com/nahumsa/volta
nahumsa
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import numpy as np from typing import Union from qiskit import QuantumCircuit from qiskit.opflow import OperatorBase, ListOp, PrimitiveOp, PauliOp from qiskit.algorithms.optimizers import Optimizer from qiskit.aqua import QuantumInstance from qiskit.providers import BaseBackend from volta.observables import sample_hamiltonian from volta.swaptest import ( measure_swap_test, measure_dswap_test, measure_amplitude_transition_test, ) class VQD(object): """Variational Quantum Deflation algorithm class. Based on https://arxiv.org/abs/1805.08138 """ def __init__( self, hamiltonian: Union[OperatorBase, ListOp, PrimitiveOp, PauliOp], ansatz: QuantumCircuit, n_excited_states: int, beta: float, optimizer: Optimizer, backend: Union[BaseBackend, QuantumInstance], overlap_method: str = "swap", num_shots: int = 10000, debug: bool = False, ) -> None: """Initialize the class. Args: hamiltonian (Union[OperatorBase, ListOp, PrimitiveOp, PauliOp]): Hamiltonian constructed using qiskit's aqua operators. ansatz (QuantumCircuit): Anstaz that you want to run VQD. n_excited_states (int): Number of excited states that you want to find the energy if you use 0, then it is the same as using a VQE. beta (float): Strenght parameter for the swap test. optimizer (qiskit.algorithms.optimizers.Optimizer): Classical Optimizers from Terra. backend (Union[BaseBackend, QuantumInstance]): Backend for running the algorithm. overlap_method (str): State overlap method. Methods available: swap, dswap, amplitude (Default: swap) num_shots (int): Number of shots. (Default: 10000) """ # Input parameters self.hamiltonian = hamiltonian self.n_qubits = hamiltonian.num_qubits self.optimizer = optimizer self.backend = backend self.NUM_SHOTS = num_shots self.BETA = beta self.overlap_method = overlap_method IMPLEMENTED_OVERLAP_METHODS = ["swap", "dswap", "amplitude"] if self.overlap_method not in IMPLEMENTED_OVERLAP_METHODS: raise NotImplementedError( f"overlapping method not implemented. Available implementing methods: {IMPLEMENTED_OVERLAP_METHODS}" ) # Helper Parameters self.n_excited_states = n_excited_states + 1 self.ansatz = ansatz self.n_parameters = self._get_num_parameters self._debug = debug # Logs self._states = [] self._energies = [] @property def energies(self) -> list: """Returns a list with energies. Returns: list: list with energies """ return self._energies @property def states(self) -> list: """Returns a list with states associated with each energy. Returns: list: list with states. """ return self._states @property def _get_num_parameters(self) -> int: """Get the number of parameters in a given ansatz. Returns: int: Number of parameters of the given ansatz. """ return len(self.ansatz.parameters) def _apply_varform_params(self, params: list): """Get an hardware-efficient ansatz for n_qubits given parameters. """ # Define variational Form var_form = self.ansatz # Get Parameters from the variational form var_form_params = sorted(var_form.parameters, key=lambda p: p.name) # Check if the number of parameters is compatible assert len(var_form_params) == len( params ), "The number of parameters don't match" # Create a dictionary with the parameters and values param_dict = dict(zip(var_form_params, params)) # Assing those values for the ansatz wave_function = var_form.assign_parameters(param_dict) return wave_function def cost_function(self, params: list) -> float: """Evaluate the cost function of VQD. Args: params (list): Parameter values for the ansatz. Returns: float: Cost function value. """ # Define Ansatz qc = self._apply_varform_params(params) # Hamiltonian hamiltonian_eval = sample_hamiltonian( hamiltonian=self.hamiltonian, ansatz=qc, backend=self.backend ) # Fidelity fidelity = 0.0 if len(self.states) != 0: for state in self.states: if self.overlap_method == "dswap": swap = measure_dswap_test(qc, state, self.backend, self.NUM_SHOTS) elif self.overlap_method == "swap": swap = measure_swap_test(qc, state, self.backend, self.NUM_SHOTS) elif self.overlap_method == "amplitude": swap = measure_amplitude_transition_test( qc, state, self.backend, self.NUM_SHOTS ) fidelity += swap if self._debug: print(fidelity) # Get the cost function cost = hamiltonian_eval + self.BETA * fidelity return cost def optimizer_run(self): # Random initialization params = np.random.rand(self.n_parameters) optimal_params, energy, n_iters = self.optimizer.optimize( num_vars=self.n_parameters, objective_function=self.cost_function, initial_point=params, ) # Logging the energies and states # TODO: Change to an ordered list. self._energies.append(energy) self._states.append(self._apply_varform_params(optimal_params)) def _reset(self): """Resets the energies and states helper variables.""" self._energies = [] self._states = [] def run(self, verbose: int = 1): self._reset() for i in range(self.n_excited_states): if verbose == 1: print(f"Calculating excited state {i}") self.optimizer_run()
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
!pip install tabulate %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 * from tabulate import tabulate # Loading your IBM Q account(s) provider = IBMQ.load_account() #Get the library to check the answers %pip install -I git+https://github.com/mnp-club/MnP_QC_Workshop.git from mnp_qc_workshop_2020.discrete_logarithm import qft_dagger, oracle, check_answer n_qubits = 3 #Number of qubits for the registers of |x1> and |x2> #For figuring out you would just need 2*n_qubits classical bits qc_disc_log = QuantumCircuit(4+n_qubits+n_qubits, n_qubits+n_qubits) for i in range(6): qc_disc_log.h(i) qc_disc_log.x(9)#Flip the first bit in third register to bring in state |1> taking q6 as LSB qc_disc_log.append(oracle(),range(10))#Applying oracle qc_disc_log.append(qft_dagger(n_qubits), range(n_qubits))#Inverse QFT on register 1 qc_disc_log.append(qft_dagger(n_qubits), range(n_qubits,2*n_qubits))#Inverse QFT on register 2 qc_disc_log.measure(range(6),range(6)) qc_disc_log.draw('text') backend = Aer.get_backend('qasm_simulator') results = execute(qc_disc_log, backend, shots=8192).result() counts = results.get_counts() plot_histogram(counts) rows_x_1, eigenvalues_x_1 = [], [] for output in counts: decimal = int(output, 2)//8 eigenvalue = decimal/(2**3) eigenvalues_x_1.append(eigenvalue) rows_x_1.append(["%s(bin) = %i(dec)" % (output[0:3], decimal), "%i/%i = %.2f" % (decimal, 2**3, eigenvalue)]) print(tabulate(rows_x_1, headers=["Register Output", "Phase"])) rows_x_2, eigenvalues_x_2 = [], [] for output in counts: decimal = int(output, 2) - ((int(output, 2)//8)*8) eigenvalue = decimal/(2**3) eigenvalues_x_2.append(eigenvalue) rows_x_2.append(["%s(bin) = %i(dec)" % (output[3:6], decimal), "%i/%i = %.2f" % (decimal, 2**3, eigenvalue)]) print(tabulate(rows_x_2, headers=["Register Output", "Phase"])) def make_guess_for_s(e1,e2): if e1==0 or e2==0: return "NaN" for a in range(2,4): if ((e1*a) - int(e1*a)) == e2: #This is because there will be roll over of the values in the register return a return "Nan" rows = [] for i in range(len(eigenvalues_x_1)): eigenvalue_x_1 = eigenvalues_x_1[i] numerator1, denominator1 = eigenvalue_x_1.as_integer_ratio() eigenvalue_x_2 = eigenvalues_x_2[i] numerator2, denominator2 = eigenvalue_x_2.as_integer_ratio() s_val = make_guess_for_s(eigenvalue_x_1,eigenvalue_x_2) rows.append([eigenvalue_x_1, "%i/%i" % (numerator1, denominator1), eigenvalue_x_2, "%i/%i" % (numerator2, denominator2), s_val]) print(tabulate(rows, headers=["Phase in 1st register","Fraction", "Phase in 2nd register", "Fraction", "Guess for s"], colalign=('right','right','right','right','right'))) #Store your value for s here s = 3 from math import gcd for i in range(2,15): j = 1 if(gcd(i,15)!=1): continue while(True): if (i**j)%15 == 1: break j = j+1 if(j == 4): print(i) qc_an = QuantumCircuit(10,4) qc_an.x(0)#This way the oracle multiplies by a mod 15 qc_an.x(9)#Flip the first bit in third register to bring in state |1> qc_an.append(oracle(),range(10))#Applying oracle qc_an.measure(range(6,10),range(4)) qc_an.draw('text') backend = Aer.get_backend('qasm_simulator') results = execute(qc_an, backend, shots=1024).result() counts = results.get_counts() plot_histogram(counts) qc_bn = QuantumCircuit(10,4) qc_bn.x(3)#This way the oracle multiplies by b mod 15 qc_bn.x(9)#Flip the first bit in third register to bring in state |1> qc_bn.append(oracle(),range(10))#Applying oracle qc_bn.measure(range(6,10),range(4)) qc_bn.draw('text') backend = Aer.get_backend('qasm_simulator') results = execute(qc_bn, backend, shots=1024).result() counts = results.get_counts() plot_histogram(counts) #Store values of a and b here a, b = 2,8 check_answer(s,a,b)
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. """Assemble function for converting a list of circuits into a qobj.""" import hashlib from collections import defaultdict from typing import Any, Dict, List, Tuple, Union from qiskit import qobj, pulse from qiskit.assembler.run_config import RunConfig from qiskit.exceptions import QiskitError from qiskit.pulse import instructions, transforms, library, schedule, channels from qiskit.qobj import utils as qobj_utils, converters from qiskit.qobj.converters.pulse_instruction import ParametricPulseShapes def assemble_schedules( schedules: List[ Union[ schedule.ScheduleBlock, schedule.ScheduleComponent, Tuple[int, schedule.ScheduleComponent], ] ], qobj_id: int, qobj_header: qobj.QobjHeader, run_config: RunConfig, ) -> qobj.PulseQobj: """Assembles a list of schedules into a qobj that can be run on the backend. Args: schedules: Schedules to assemble. qobj_id: Identifier for the generated qobj. qobj_header: Header to pass to the results. run_config: Configuration of the runtime environment. Returns: The Qobj to be run on the backends. Raises: QiskitError: when frequency settings are not supplied. Examples: .. code-block:: python from qiskit import pulse from qiskit.assembler import assemble_schedules from qiskit.assembler.run_config import RunConfig # Construct a Qobj header for the output Qobj header = {"backend_name": "FakeOpenPulse2Q", "backend_version": "0.0.0"} # Build a configuration object for the output Qobj config = RunConfig(shots=1024, memory=False, meas_level=1, meas_return='avg', memory_slot_size=100, parametric_pulses=[], init_qubits=True, qubit_lo_freq=[4900000000.0, 5000000000.0], meas_lo_freq=[6500000000.0, 6600000000.0], schedule_los=[]) # Build a Pulse schedule to assemble into a Qobj schedule = pulse.Schedule() schedule += pulse.Play(pulse.Waveform([0.1] * 16, name="test0"), pulse.DriveChannel(0), name="test1") schedule += pulse.Play(pulse.Waveform([0.1] * 16, name="test1"), pulse.DriveChannel(0), name="test2") schedule += pulse.Play(pulse.Waveform([0.5] * 16, name="test0"), pulse.DriveChannel(0), name="test1") # Assemble a Qobj from the schedule. pulseQobj = assemble_schedules(schedules=[schedule], qobj_id="custom-id", qobj_header=header, run_config=config) """ if not hasattr(run_config, "qubit_lo_freq"): raise QiskitError("qubit_lo_freq must be supplied.") if not hasattr(run_config, "meas_lo_freq"): raise QiskitError("meas_lo_freq must be supplied.") lo_converter = converters.LoConfigConverter( qobj.PulseQobjExperimentConfig, **run_config.to_dict() ) experiments, experiment_config = _assemble_experiments(schedules, lo_converter, run_config) qobj_config = _assemble_config(lo_converter, experiment_config, run_config) return qobj.PulseQobj( experiments=experiments, qobj_id=qobj_id, header=qobj_header, config=qobj_config ) def _assemble_experiments( schedules: List[Union[schedule.ScheduleComponent, Tuple[int, schedule.ScheduleComponent]]], lo_converter: converters.LoConfigConverter, run_config: RunConfig, ) -> Tuple[List[qobj.PulseQobjExperiment], Dict[str, Any]]: """Assembles a list of schedules into PulseQobjExperiments, and returns related metadata that will be assembled into the Qobj configuration. Args: schedules: Schedules to assemble. lo_converter: The configured frequency converter and validator. run_config: Configuration of the runtime environment. Returns: The list of assembled experiments, and the dictionary of related experiment config. Raises: QiskitError: when frequency settings are not compatible with the experiments. """ freq_configs = [lo_converter(lo_dict) for lo_dict in getattr(run_config, "schedule_los", [])] if len(schedules) > 1 and len(freq_configs) not in [0, 1, len(schedules)]: raise QiskitError( "Invalid 'schedule_los' setting specified. If specified, it should be " "either have a single entry to apply the same LOs for each schedule or " "have length equal to the number of schedules." ) instruction_converter = getattr( run_config, "instruction_converter", converters.InstructionToQobjConverter ) instruction_converter = instruction_converter(qobj.PulseQobjInstruction, **run_config.to_dict()) formatted_schedules = [transforms.target_qobj_transform(sched) for sched in schedules] compressed_schedules = transforms.compress_pulses(formatted_schedules) user_pulselib = {} experiments = [] for idx, sched in enumerate(compressed_schedules): qobj_instructions, max_memory_slot = _assemble_instructions( sched, instruction_converter, run_config, user_pulselib ) metadata = sched.metadata if metadata is None: metadata = {} # TODO: add other experimental header items (see circuit assembler) qobj_experiment_header = qobj.QobjExperimentHeader( memory_slots=max_memory_slot + 1, # Memory slots are 0 indexed name=sched.name or "Experiment-%d" % idx, metadata=metadata, ) experiment = qobj.PulseQobjExperiment( header=qobj_experiment_header, instructions=qobj_instructions ) if freq_configs: # This handles the cases where one frequency setting applies to all experiments and # where each experiment has a different frequency freq_idx = idx if len(freq_configs) != 1 else 0 experiment.config = freq_configs[freq_idx] experiments.append(experiment) # Frequency sweep if freq_configs and len(experiments) == 1: experiment = experiments[0] experiments = [] for freq_config in freq_configs: experiments.append( qobj.PulseQobjExperiment( header=experiment.header, instructions=experiment.instructions, config=freq_config, ) ) # Top level Qobj configuration experiment_config = { "pulse_library": [ qobj.PulseLibraryItem(name=name, samples=samples) for name, samples in user_pulselib.items() ], "memory_slots": max(exp.header.memory_slots for exp in experiments), } return experiments, experiment_config def _assemble_instructions( sched: Union[pulse.Schedule, pulse.ScheduleBlock], instruction_converter: converters.InstructionToQobjConverter, run_config: RunConfig, user_pulselib: Dict[str, List[complex]], ) -> Tuple[List[qobj.PulseQobjInstruction], int]: """Assembles the instructions in a schedule into a list of PulseQobjInstructions and returns related metadata that will be assembled into the Qobj configuration. Lookup table for pulses defined in all experiments are registered in ``user_pulselib``. This object should be mutable python dictionary so that items are properly updated after each instruction assemble. The dictionary is not returned to avoid redundancy. Args: sched: Schedule to assemble. instruction_converter: A converter instance which can convert PulseInstructions to PulseQobjInstructions. run_config: Configuration of the runtime environment. user_pulselib: User pulse library from previous schedule. Returns: A list of converted instructions, the user pulse library dictionary (from pulse name to pulse samples), and the maximum number of readout memory slots used by this Schedule. """ sched = transforms.target_qobj_transform(sched) max_memory_slot = 0 qobj_instructions = [] acquire_instruction_map = defaultdict(list) for time, instruction in sched.instructions: if isinstance(instruction, instructions.Play): if isinstance(instruction.pulse, (library.ParametricPulse, library.SymbolicPulse)): is_backend_supported = True try: pulse_shape = ParametricPulseShapes.from_instance(instruction.pulse).name if pulse_shape not in run_config.parametric_pulses: is_backend_supported = False except ValueError: # Custom pulse class, or bare SymbolicPulse object. is_backend_supported = False if not is_backend_supported: instruction = instructions.Play( instruction.pulse.get_waveform(), instruction.channel, name=instruction.name ) if isinstance(instruction.pulse, library.Waveform): name = hashlib.sha256(instruction.pulse.samples).hexdigest() instruction = instructions.Play( library.Waveform(name=name, samples=instruction.pulse.samples), channel=instruction.channel, name=name, ) user_pulselib[name] = instruction.pulse.samples # ignore explicit delay instrs on acq channels as they are invalid on IBMQ backends; # timing of other instrs will still be shifted appropriately if isinstance(instruction, instructions.Delay) and isinstance( instruction.channel, channels.AcquireChannel ): continue if isinstance(instruction, instructions.Acquire): if instruction.mem_slot: max_memory_slot = max(max_memory_slot, instruction.mem_slot.index) # Acquires have a single AcquireChannel per inst, but we have to bundle them # together into the Qobj as one instruction with many channels acquire_instruction_map[(time, instruction.duration)].append(instruction) continue qobj_instructions.append(instruction_converter(time, instruction)) if acquire_instruction_map: if hasattr(run_config, "meas_map"): _validate_meas_map(acquire_instruction_map, run_config.meas_map) for (time, _), instruction_bundle in acquire_instruction_map.items(): qobj_instructions.append( instruction_converter(time, instruction_bundle), ) return qobj_instructions, max_memory_slot def _validate_meas_map( instruction_map: Dict[Tuple[int, instructions.Acquire], List[instructions.Acquire]], meas_map: List[List[int]], ) -> None: """Validate all qubits tied in ``meas_map`` are to be acquired. Args: instruction_map: A dictionary grouping Acquire instructions according to their start time and duration. meas_map: List of groups of qubits that must be acquired together. Raises: QiskitError: If the instructions do not satisfy the measurement map. """ sorted_inst_map = sorted(instruction_map.items(), key=lambda item: item[0]) meas_map_sets = [set(m) for m in meas_map] # error if there is time overlap between qubits in the same meas_map for idx, inst in enumerate(sorted_inst_map[:-1]): inst_end_time = inst[0][0] + inst[0][1] next_inst = sorted_inst_map[idx + 1] next_inst_time = next_inst[0][0] if next_inst_time < inst_end_time: inst_qubits = {inst.channel.index for inst in inst[1]} next_inst_qubits = {inst.channel.index for inst in next_inst[1]} for meas_set in meas_map_sets: common_instr_qubits = inst_qubits.intersection(meas_set) common_next = next_inst_qubits.intersection(meas_set) if common_instr_qubits and common_next: raise QiskitError( "Qubits {} and {} are in the same measurement grouping: {}. " "They must either be acquired at the same time, or disjointly" ". Instead, they were acquired at times: {}-{} and " "{}-{}".format( common_instr_qubits, common_next, meas_map, inst[0][0], inst_end_time, next_inst_time, next_inst_time + next_inst[0][1], ) ) def _assemble_config( lo_converter: converters.LoConfigConverter, experiment_config: Dict[str, Any], run_config: RunConfig, ) -> qobj.PulseQobjConfig: """Assembles the QobjConfiguration from experimental config and runtime config. Args: lo_converter: The configured frequency converter and validator. experiment_config: Schedules to assemble. run_config: Configuration of the runtime environment. Returns: The assembled PulseQobjConfig. """ qobj_config = run_config.to_dict() qobj_config.update(experiment_config) # Run config not needed in qobj config qobj_config.pop("meas_map", None) qobj_config.pop("qubit_lo_range", None) qobj_config.pop("meas_lo_range", None) # convert enums to serialized values meas_return = qobj_config.get("meas_return", "avg") if isinstance(meas_return, qobj_utils.MeasReturnType): qobj_config["meas_return"] = meas_return.value meas_level = qobj_config.get("meas_level", 2) if isinstance(meas_level, qobj_utils.MeasLevel): qobj_config["meas_level"] = meas_level.value # convert LO frequencies to GHz qobj_config["qubit_lo_freq"] = [freq / 1e9 for freq in qobj_config["qubit_lo_freq"]] qobj_config["meas_lo_freq"] = [freq / 1e9 for freq in qobj_config["meas_lo_freq"]] # override defaults if single entry for ``schedule_los`` schedule_los = qobj_config.pop("schedule_los", []) if len(schedule_los) == 1: lo_dict = schedule_los[0] q_los = lo_converter.get_qubit_los(lo_dict) # Hz -> GHz if q_los: qobj_config["qubit_lo_freq"] = [freq / 1e9 for freq in q_los] m_los = lo_converter.get_meas_los(lo_dict) if m_los: qobj_config["meas_lo_freq"] = [freq / 1e9 for freq in m_los] return qobj.PulseQobjConfig(**qobj_config)
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/SunilBoopalan/quantum-chess-Qiskit
SunilBoopalan
from chess import * SquareSet(BB_DIAG_ATTACKS[36][BB_DIAG_MASKS[36] & BB_RANKS[6]]) SquareSet(BB_SQUARES[0] | BB_SQUARES[1]) 3423421312222322111 & 222 board = Board() board.turn = True Nf3 = chess.Move.from_uci("g1f3") Ng5 = chess.Move.from_uci("f3g5") # board.push(Nf3) board.push(Nf3) board.push(Ng5) chess.Piece.from_symbol('P') board em_board = Board(fen = None)
https://github.com/chaitanya-bhargava/QiskitSolutions
chaitanya-bhargava
## Enter Team ID import os os.environ["TEAMID"] = "Excalibur" from qiskit import QuantumCircuit from numpy import * def qram_4q(m, array): ### your code here size=int(floor(log2(m))+3) n=size-2 qc=QuantumCircuit(size) binary=[] k=str(n) for i in array: binary.append(format(i, f'0{k}b')) i=0 qc.h(0) qc.h(1) qc.x(0) qc.x(1) for j in range(1,n+1): if(binary[i][j-1]=='1'): qc.ccx(0,1,size-j) i=i+1 qc.x(0) qc.x(1) qc.x(1) for j in range(1,n+1): if(binary[i][j-1]=='1'): qc.ccx(0,1,size-j) i=i+1 qc.x(1) qc.x(0) for j in range(1,n+1): if(binary[i][j-1]=='1'): qc.ccx(0,1,size-j) i=i+1 qc.x(0) for j in range(1,n+1): if(binary[i][j-1]=='1'): qc.ccx(0,1,size-j) return qc ### your code here def test_function_1(): m = 6 array = [3, 4, 5, 6] qram = qram_4q(m, array) return qram test_function_1().draw('mpl') from grader.graders.problem_5.grader import grader1 grader1.evaluate(qram_4q) def qram_general(n, m, array): ### your code here k=int(floor(log2(m))+1) l=int(log2(n)) size=k+l qc=QuantumCircuit(size) index=list(range(l)) binary=[] for i in array: binary.append(format(i, f'0{k}b')) qc.h(index) for i in range(n): b=format(i,f'0{l}b') inverted=[] for p in range(0,l): if(b[p]=='0'): qc.x(l-p-1) inverted.append(l-p-1) for j in range(1,k+1): if(binary[i][j-1]=='1'): qc.mct(index,size-j) for q in inverted: qc.x(q) return qc ### your code here def test_function_2(): n = 4 m = 4 array = [3,4,5,6] qram = qram_general(n, m, array) return qram test_function_2().draw('mpl') from grader.graders.problem_5.grader import grader2 grader2.evaluate(qram_general) from qiskit.circuit.library import RYGate,RXGate,RZGate def qram_rotations(n, rotations): ### your code here l=int(log2(n)) size=l+1 qc=QuantumCircuit(size) index=list(range(l)) full=list(range(size)) qc.h(index) for i in range(n): b=format(i,f'0{l}b') inverted=[] for p in range(0,l): if(b[p]=='0'): qc.x(l-p-1) inverted.append(l-p-1) qc.barrier() if(rotations[i][0]=='x'): multirx = RXGate(rotations[i][1]*2*pi).control(l,label=None) qc.append(multirx,full) elif(rotations[i][0]=='y'): multiry = RYGate(rotations[i][1]*2*pi).control(l,label=None) qc.append(multiry,full) elif(rotations[i][0]=='z'): multirz = RZGate(rotations[i][1]*2*pi).control(l,label=None) qc.append(multirz,full) qc.barrier() for q in inverted: qc.x(q) qc.barrier() return qc ### your code here def test_function_3(): n = 8 rotations = [('x', 0.123), ('y', -0.912),('z',-0.12),('x', 0.5),('z',0.5),('y', -0.5),('z',0.5),('x', 0.5)] qram = qram_rotations(n, rotations) return qram test_function_3().draw('mpl') from grader.graders.problem_5.grader import grader3 grader3.evaluate(qram_rotations)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() print(problem) hamiltonian = problem.hamiltonian coefficients = hamiltonian.electronic_integrals print(coefficients.alpha) second_q_op = hamiltonian.second_q_op() print(second_q_op) hamiltonian.nuclear_repulsion_energy # NOT included in the second_q_op above problem.molecule problem.reference_energy problem.num_particles problem.num_spatial_orbitals problem.basis problem.properties problem.properties.particle_number problem.properties.angular_momentum problem.properties.magnetization problem.properties.electronic_dipole_moment from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper solver = GroundStateEigensolver( JordanWignerMapper(), NumPyMinimumEigensolver(), ) result = solver.solve(problem) print(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit.library import QFT def create_qpe_circuit(theta, num_qubits): '''Creates a QPE circuit given theta and num_qubits.''' # Step 1: Create a circuit with two quantum registers and one classical register. first = QuantumRegister(size=num_qubits, name='first') # the first register for phase estimation second = QuantumRegister(size=1, name='second') # the second register for storing eigenvector |psi> classical = ClassicalRegister(size=num_qubits, name='readout') # classical register for readout qpe_circuit = QuantumCircuit(first, second, classical) # Step 2: Initialize the qubits. # All qubits are initialized in |0> by default, no extra code is needed to initialize the first register. qpe_circuit.x(second) # Initialize the second register with state |psi>, which is |1> in this example. # Step 3: Create superposition in the first register. qpe_circuit.barrier() # Add barriers to separate each step of the algorithm for better visualization. qpe_circuit.h(first) # Step 4: Apply a controlled-U^(2^j) black box. qpe_circuit.barrier() for j in range(num_qubits): qpe_circuit.cp(theta*2*np.pi*(2**j), j, num_qubits) # Theta doesn't contain the 2 pi factor. # Step 5: Apply an inverse QFT to the first register. qpe_circuit.barrier() qpe_circuit.compose(QFT(num_qubits, inverse=True), inplace=True) # Step 6: Measure the first register. qpe_circuit.barrier() qpe_circuit.measure(first, classical) return qpe_circuit num_qubits = 4 qpe_circuit_fixed_phase = create_qpe_circuit(1/2, num_qubits) # Create a QPE circuit with fixed theta=1/2. qpe_circuit_fixed_phase.draw('mpl') from qiskit.circuit import Parameter theta = Parameter('theta') # Create a parameter `theta` whose values can be assigned later. qpe_circuit_parameterized = create_qpe_circuit(theta, num_qubits) qpe_circuit_parameterized.draw('mpl') number_of_phases = 21 phases = np.linspace(0, 2, number_of_phases) individual_phases = [[ph] for ph in phases] # Phases need to be expressed as a list of lists. from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" # use the simulator from qiskit_ibm_runtime import Sampler, Session with Session(service=service, backend=backend): results = Sampler().run( [qpe_circuit_parameterized]*len(individual_phases), parameter_values=individual_phases ).result() from qiskit.tools.visualization import plot_histogram idx = 6 plot_histogram(results.quasi_dists[idx].binary_probabilities(), legend=[f'$\\theta$={phases[idx]:.3f}']) def most_likely_bitstring(results_dict): '''Finds the most likely outcome bit string from a result dictionary.''' return max(results_dict, key=results_dict.get) def find_neighbors(bitstring): '''Finds the neighbors of a bit string. Example: For bit string '1010', this function returns ('1001', '1011') ''' if bitstring == len(bitstring)*'0': neighbor_left = len(bitstring)*'1' else: neighbor_left = format((int(bitstring,2)-1), '0%sb'%len(bitstring)) if bitstring == len(bitstring)*'1': neighbor_right = len(bitstring)*'0' else: neighbor_right = format((int(bitstring,2)+1), '0%sb'%len(bitstring)) return (neighbor_left, neighbor_right) def estimate_phase(results_dict): '''Estimates the phase from a result dictionary of a QPE circuit.''' # Find the most likely outcome bit string N1 and its neighbors. num_1_key = most_likely_bitstring(results_dict) neighbor_left, neighbor_right = find_neighbors(num_1_key) # Get probabilities of N1 and its neighbors. num_1_prob = results_dict.get(num_1_key) neighbor_left_prob = results_dict.get(neighbor_left) neighbor_right_prob = results_dict.get(neighbor_right) # Find the second most likely outcome N2 and its probability P2 among the neighbors. if neighbor_left_prob is None: # neighbor_left doesn't exist if neighbor_right_prob is None: # both neighbors don't exist, N2 is N1 num_2_key = num_1_key num_2_prob = num_1_prob else: # If only neighbor_left doesn't exist, N2 is neighbor_right. num_2_key = neighbor_right num_2_prob = neighbor_right_prob elif neighbor_right_prob is None: # If only neighbor_right doesn't exist, N2 is neighbor_left. num_2_key = neighbor_left num_2_prob = neighbor_left_prob elif neighbor_left_prob > neighbor_right_prob: # Both neighbors exist and neighbor_left has higher probability, so N2 is neighbor_left. num_2_key = neighbor_left num_2_prob = neighbor_left_prob else: # Both neighbors exist and neighbor_right has higher probability, so N2 is neighor_right. num_2_key = neighbor_right num_2_prob = neighbor_right_prob # Calculate the estimated phases for N1 and N2. num_qubits = len(num_1_key) num_1_phase = (int(num_1_key, 2) / 2**num_qubits) num_2_phase = (int(num_2_key, 2) / 2**num_qubits) # Calculate the weighted average phase from N1 and N2. phase_estimated = (num_1_phase * num_1_prob + num_2_phase * num_2_prob) / (num_1_prob + num_2_prob) return phase_estimated qpe_solutions = [] for idx, result_dict in enumerate(results.quasi_dists): qpe_solutions.append(estimate_phase(result_dict.binary_probabilities())) ideal_solutions = np.append( phases[:(number_of_phases-1)//2], # first period np.subtract(phases[(number_of_phases-1)//2:-1], 1) # second period ) ideal_solutions = np.append(ideal_solutions, np.subtract(phases[-1], 2)) # starting point of the third period import matplotlib.pyplot as plt fig = plt.figure(figsize=(10, 6)) plt.plot(phases, ideal_solutions, '--', label='Ideal solutions') plt.plot(phases, qpe_solutions, 'o', label='QPE solutions') plt.title('Quantum Phase Estimation Algorithm') plt.xlabel('Input Phase') plt.ylabel('Output Phase') 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/westernquantumclub/qiskit-intro
westernquantumclub
#In case you don't have qiskit, install it now %pip install qiskit --quiet #Installing/upgrading pylatexenc seems to have fixed my mpl issue #If you try this and it doesn't work, try also restarting the runtime/kernel %pip install pylatexenc --quiet !pip install -Uqq ipdb !pip install qiskit_optimization import networkx as nx import matplotlib.pyplot as plt from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import BasicAer from qiskit.compiler import transpile from qiskit.quantum_info.operators import Operator, Pauli from qiskit.quantum_info import process_fidelity from qiskit.extensions.hamiltonian_gate import HamiltonianGate from qiskit.extensions import RXGate, XGate, CXGate from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute import numpy as np from qiskit.visualization import plot_histogram import ipdb from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * #quadratic optimization from qiskit_optimization import QuadraticProgram from qiskit_optimization.converters import QuadraticProgramToQubo %pdb on # def ApplyCost(qc, gamma): # Ix = np.array([[1,0],[0,1]]) # Zx= np.array([[1,0],[0,-1]]) # Xx = np.array([[0,1],[1,0]]) # Temp = (Ix-Zx)/2 # T = Operator(Temp) # I = Operator(Ix) # Z = Operator(Zx) # X = Operator(Xx) # FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T) # ham = HamiltonianGate(FinalOp,gamma) # qc.append(ham,[0,1,2]) task = QuadraticProgram(name = 'QUBO on QC') task.binary_var(name = 'x') task.binary_var(name = 'y') task.binary_var(name = 'z') task.minimize(linear = {"x":-1,"y":2,"z":-3}, quadratic = {("x", "z"): -2, ("y", "z"): -1}) qubo = QuadraticProgramToQubo().convert(task) #convert to QUBO operator, offset = qubo.to_ising() print(operator) # ham = HamiltonianGate(operator,0) # print(ham) Ix = np.array([[1,0],[0,1]]) Zx= np.array([[1,0],[0,-1]]) Xx = np.array([[0,1],[1,0]]) Temp = (Ix-Zx)/2 T = Operator(Temp) I = Operator(Ix) Z = Operator(Zx) X = Operator(Xx) FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T) ham = HamiltonianGate(FinalOp,0) print(ham) #define PYBIND11_DETAILED_ERROR_MESSAGES def compute_expectation(counts): """ Computes expectation value based on measurement results Args: counts: dict key as bitstring, val as count G: networkx graph Returns: avg: float expectation value """ avg = 0 sum_count = 0 for bitstring, count in counts.items(): x = int(bitstring[2]) y = int(bitstring[1]) z = int(bitstring[0]) obj = -2*x*z-y*z-x+2*y-3*z avg += obj * count sum_count += count return avg/sum_count # We will also bring the different circuit components that # build the qaoa circuit under a single function def create_qaoa_circ(theta): """ Creates a parametrized qaoa circuit Args: G: networkx graph theta: list unitary parameters Returns: qc: qiskit circuit """ nqubits = 3 n,m=3,3 p = len(theta)//2 # number of alternating unitaries qc = QuantumCircuit(nqubits,nqubits) Ix = np.array([[1,0],[0,1]]) Zx= np.array([[1,0],[0,-1]]) Xx = np.array([[0,1],[1,0]]) Temp = (Ix-Zx)/2 T = Operator(Temp) I = Operator(Ix) Z = Operator(Zx) X = Operator(Xx) FinalOp=-2*(Z^I^Z)-(I^Z^Z)-(Z^I^I)+2*(I^Z^I)-3*(I^I^Z) beta = theta[:p] gamma = theta[p:] # initial_state for i in range(0, nqubits): qc.h(i) for irep in range(0, p): #ipdb.set_trace(context=6) # problem unitary # for pair in list(G.edges()): # qc.rzz(2 * gamma[irep], pair[0], pair[1]) #ApplyCost(qc,2*0) ham = HamiltonianGate(operator,2 * gamma[irep]) qc.append(ham,[0,1,2]) # mixer unitary for i in range(0, nqubits): qc.rx(2 * beta[irep], i) qc.measure(qc.qubits[:n],qc.clbits[:m]) return qc # Finally we write a function that executes the circuit on the chosen backend def get_expectation(shots=512): """ Runs parametrized circuit Args: G: networkx graph p: int, Number of repetitions of unitaries """ backend = Aer.get_backend('qasm_simulator') backend.shots = shots def execute_circ(theta): qc = create_qaoa_circ(theta) # ipdb.set_trace(context=6) counts = {} job = execute(qc, backend, shots=1024) result = job.result() counts=result.get_counts(qc) return compute_expectation(counts) return execute_circ from scipy.optimize import minimize expectation = get_expectation() res = minimize(expectation, [1, 1], method='COBYLA') expectation = get_expectation() res = minimize(expectation, res.x, method='COBYLA') res from qiskit.visualization import plot_histogram backend = Aer.get_backend('aer_simulator') backend.shots = 512 qc_res = create_qaoa_circ(res.x) backend = Aer.get_backend('qasm_simulator') job = execute(qc_res, backend, shots=1024) result = job.result() counts=result.get_counts(qc_res) plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Necessary imports import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import ZFeatureMap, RealAmplitudes from qiskit.utils import algorithm_globals from sklearn.datasets import make_classification from sklearn.preprocessing import MinMaxScaler from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier from qiskit_machine_learning.neural_networks import EffectiveDimension, LocalEffectiveDimension from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN # set random seed algorithm_globals.random_seed = 42 num_qubits = 3 # create a feature map feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1) # create a variational circuit ansatz = RealAmplitudes(num_qubits, reps=1) # combine feature map and ansatz into a single circuit qc = QuantumCircuit(num_qubits) qc.append(feature_map, range(num_qubits)) qc.append(ansatz, range(num_qubits)) qc.decompose().draw("mpl") # parity maps bitstrings to 0 or 1 def parity(x): return "{:b}".format(x).count("1") % 2 output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping. # construct QNN qnn = SamplerQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, sparse=False, ) # we can set the total number of input samples and weight samples for random selection num_input_samples = 10 num_weight_samples = 10 global_ed = EffectiveDimension( qnn=qnn, weight_samples=num_weight_samples, input_samples=num_input_samples ) # we can also provide user-defined samples and parameters input_samples = algorithm_globals.random.normal(0, 1, size=(10, qnn.num_inputs)) weight_samples = algorithm_globals.random.uniform(0, 1, size=(10, qnn.num_weights)) global_ed = EffectiveDimension(qnn=qnn, weight_samples=weight_samples, input_samples=input_samples) # finally, we will define ranges to test different numbers of data, n n = [5000, 8000, 10000, 40000, 60000, 100000, 150000, 200000, 500000, 1000000] global_eff_dim_0 = global_ed.get_effective_dimension(dataset_size=n[0]) d = qnn.num_weights print("Data size: {}, global effective dimension: {:.4f}".format(n[0], global_eff_dim_0)) print( "Number of weights: {}, normalized effective dimension: {:.4f}".format(d, global_eff_dim_0 / d) ) global_eff_dim_1 = global_ed.get_effective_dimension(dataset_size=n) print("Effective dimension: {}".format(global_eff_dim_1)) print("Number of weights: {}".format(d)) # plot the normalized effective dimension for the model plt.plot(n, np.array(global_eff_dim_1) / d) plt.xlabel("Number of data") plt.ylabel("Normalized GLOBAL effective dimension") plt.show() num_inputs = 3 num_samples = 50 X, y = make_classification( n_samples=num_samples, n_features=num_inputs, n_informative=3, n_redundant=0, n_clusters_per_class=1, class_sep=2.0, ) X = MinMaxScaler().fit_transform(X) y = 2 * y - 1 # labels in {-1, 1} estimator_qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # callback function that draws a live plot when the .fit() method is called def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() # construct classifier initial_point = algorithm_globals.random.random(estimator_qnn.num_weights) estimator_classifier = NeuralNetworkClassifier( neural_network=estimator_qnn, optimizer=COBYLA(maxiter=80), initial_point=initial_point, callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function (callback) objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data estimator_classifier.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier estimator_classifier.score(X, y) trained_weights = estimator_classifier.weights # get Local Effective Dimension for set of trained weights local_ed_trained = LocalEffectiveDimension( qnn=estimator_qnn, weight_samples=trained_weights, input_samples=X ) local_eff_dim_trained = local_ed_trained.get_effective_dimension(dataset_size=n) print( "normalized local effective dimensions for trained QNN: ", local_eff_dim_trained / estimator_qnn.num_weights, ) # get Local Effective Dimension for set of untrained weights local_ed_untrained = LocalEffectiveDimension( qnn=estimator_qnn, weight_samples=initial_point, input_samples=X ) local_eff_dim_untrained = local_ed_untrained.get_effective_dimension(dataset_size=n) print( "normalized local effective dimensions for untrained QNN: ", local_eff_dim_untrained / estimator_qnn.num_weights, ) # plot the normalized effective dimension for the model plt.plot(n, np.array(local_eff_dim_trained) / estimator_qnn.num_weights, label="trained weights") plt.plot( n, np.array(local_eff_dim_untrained) / estimator_qnn.num_weights, label="untrained weights" ) plt.xlabel("Number of data") plt.ylabel("Normalized LOCAL effective dimension") plt.legend() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/peiyong-addwater/Hackathon-QNLP
peiyong-addwater
import collections import pickle import warnings warnings.filterwarnings("ignore") import os from random import shuffle import random from discopy.tensor import Tensor from discopy import Word from discopy.rigid import Functor from discopy import grammar import seaborn as sns import pandas as pd import matplotlib.pyplot as plt from jax import numpy as np import numpy from lambeq import AtomicType, IQPAnsatz, remove_cups, NumpyModel, spiders_reader from lambeq import BobcatParser, TreeReader, cups_reader, DepCCGParser, TreeReaderMode from lambeq import Dataset from lambeq import QuantumTrainer, SPSAOptimizer from lambeq import TketModel from lambeq import Rewriter from pytket.extensions.qiskit import AerBackend import seaborn as sns import matplotlib.pyplot as plt from pytket.circuit.display import render_circuit_jupyter pd.set_option('display.width', 1000) pd.options.display.max_colwidth=80 print(os.getcwd()) warnings.filterwarnings("ignore") os.environ["TOKENIZERS_PARALLELISM"] = "false" BATCH_SIZE = 50 EPOCHS = 200 SEED = 0 TRAIN_INDEX_RATIO = 0.08 VAL_INDEX_RATIO = TRAIN_INDEX_RATIO + 0.01 TEST_INDEX_RATIO = VAL_INDEX_RATIO + 0.01 assert TEST_INDEX_RATIO <= 1 def load_pickled_dict_to_df(filename): saved_dict = pickle.load(open(filename, 'rb')) df = pd.DataFrame.from_dict(saved_dict) df = df.sample(frac=1, random_state=SEED).reset_index(drop=True) sentiment = [] for i in df['target']: if i == "Positive": sentiment.append(1) else: sentiment.append(0) df["Sentiment"] = sentiment return df cleaned_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data.pkl') cleaned_lemmatized_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_lematize.pkl') cleaned_lemmatized_stemmed_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_stem_lematize.pkl') cleaned_qnlp = load_pickled_dict_to_df(cleaned_qnlp_filename) cleaned_lemmatized_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_qnlp_filename) cleaned__lemmatized_stemmed_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_stemmed_qnlp_filename) cleaned_qnlp.head(10) cleaned_qnlp.info() sns.countplot(x = "target", data = cleaned_qnlp) cleaned_lemmatized_qnlp.head(10) cleaned_lemmatized_qnlp.info() sns.countplot(x='target', data = cleaned_lemmatized_qnlp) cleaned__lemmatized_stemmed_qnlp.head(10) cleaned__lemmatized_stemmed_qnlp.info() sns.countplot(x='target', data = cleaned__lemmatized_stemmed_qnlp) # parser = BobcatParser(verbose='text') # parser = DepCCGParser(root_cats=['S[dcl]']) # parser = spiders_reader parser = TreeReader(mode=TreeReaderMode.RULE_TYPE) NUM_DATA = 2578 loss = lambda y_hat, y: -np.sum(y * np.log(y_hat)) / len(y) # binary cross-entropy loss acc = lambda y_hat, y: np.sum(np.round(y_hat) == y) / len(y) / 2 # half due to double-counting rewriter = Rewriter(['prepositional_phrase', 'determiner', 'auxiliary', 'connector', 'coordination', 'object_rel_pronoun', 'subject_rel_pronoun', 'postadverb', 'preadverb']) def rewrite(diagram): # diagram = rewriter(diagram) return remove_cups(diagram) def create_diagrams_and_labels(total_df, NUM_DATA = 2578): total_text = total_df['data'].tolist() total_labels = total_df["Sentiment"].tolist() total_labels = [[t, 1-t] for t in total_labels] # [1, 0] for positive, [0, 1] for negative train_diagrams = parser.sentences2diagrams(total_text[:round(NUM_DATA*TRAIN_INDEX_RATIO)]) train_labels = total_labels[:round(NUM_DATA*TRAIN_INDEX_RATIO)] dev_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)]) dev_labels = total_labels[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)] test_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)]) test_labels = total_labels[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)] return train_diagrams, train_labels, dev_diagrams, dev_labels, test_diagrams, test_labels data = cleaned__lemmatized_stemmed_qnlp raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(data) print(len(raw_train_diagrams_1)) raw_train_diagrams_1[0].draw(figsize=(12,3)) train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1] dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1] test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1] train_diagrams_1[0].draw(figsize=(6,5)) alternate_parser = BobcatParser(verbose='text') dig_0 = alternate_parser.sentence2diagram(cleaned__lemmatized_stemmed_qnlp['data'].tolist()[0]) grammar.draw(dig_0, figsize=(14,3), fontsize=12) ansatz_1 = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1, AtomicType.PREPOSITIONAL_PHRASE: 1, AtomicType.NOUN_PHRASE:1, AtomicType.CONJUNCTION:1}, n_layers=1, n_single_qubit_params=3) train_circuits_1 = [ansatz_1(diagram) for diagram in train_diagrams_1] dev_circuits_1 = [ansatz_1(diagram) for diagram in dev_diagrams_1] test_circuits_1 = [ansatz_1(diagram) for diagram in test_diagrams_1] train_circuits_1[0].draw(figsize=(9, 12)) # train_circuits_1[0].draw(figsize=(9, 12)) render_circuit_jupyter(train_circuits_1[0].to_tk()) [(s, s.size) for s in train_circuits_1[0].free_symbols] all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1 model_1 = NumpyModel.from_diagrams(all_circuits_1, use_jit=True) # model_1 = TketModel.from_diagrams(all_circuits_1, backend_config=backend_config) trainer_1 = QuantumTrainer( model_1, loss_function=loss, epochs=EPOCHS, optimizer=SPSAOptimizer, optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS}, evaluate_functions={'acc': acc}, evaluate_on_train=True, verbose = 'text', seed=0 ) train_dataset_1 = Dataset( train_circuits_1, train_labels_1, batch_size=BATCH_SIZE) val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False) trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=1) fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8)) ax_tl.set_title('Training set') ax_tr.set_title('Development set') ax_bl.set_xlabel('Iterations') ax_br.set_xlabel('Iterations') ax_bl.set_ylabel('Accuracy') ax_tl.set_ylabel('Loss') colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color']) ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours)) ax_bl.plot(trainer_1.train_results['acc'], color=next(colours)) ax_tr.plot(trainer_1.val_costs, color=next(colours)) ax_br.plot(trainer_1.val_results['acc'], color=next(colours)) test_acc_1 = acc(model_1(test_circuits_1), test_labels_1) print('Test accuracy:', test_acc_1) data = cleaned_lemmatized_qnlp raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(data) print(len(raw_train_diagrams_1)) raw_train_diagrams_1[0].draw(figsize=(12,3)) train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1] dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1] test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1] train_diagrams_1[0].draw(figsize=(6,5)) ansatz_1 = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1, AtomicType.PREPOSITIONAL_PHRASE: 1, AtomicType.NOUN_PHRASE:1, AtomicType.CONJUNCTION:1}, n_layers=1, n_single_qubit_params=3) train_circuits_1 = [ansatz_1(diagram) for diagram in train_diagrams_1] dev_circuits_1 = [ansatz_1(diagram) for diagram in dev_diagrams_1] test_circuits_1 = [ansatz_1(diagram) for diagram in test_diagrams_1] train_circuits_1[0].draw(figsize=(9, 12)) render_circuit_jupyter(train_circuits_1[0].to_tk()) all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1 model_1 = NumpyModel.from_diagrams(all_circuits_1, use_jit=True) trainer_1 = QuantumTrainer( model_1, loss_function=loss, epochs=EPOCHS, optimizer=SPSAOptimizer, optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS}, evaluate_functions={'acc': acc}, evaluate_on_train=True, verbose = 'text', seed=0 ) train_dataset_1 = Dataset( train_circuits_1, train_labels_1, batch_size=BATCH_SIZE) val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False) trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=1) fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8)) ax_tl.set_title('Training set') ax_tr.set_title('Development set') ax_bl.set_xlabel('Iterations') ax_br.set_xlabel('Iterations') ax_bl.set_ylabel('Accuracy') ax_tl.set_ylabel('Loss') colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color']) ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours)) ax_bl.plot(trainer_1.train_results['acc'], color=next(colours)) ax_tr.plot(trainer_1.val_costs, color=next(colours)) ax_br.plot(trainer_1.val_results['acc'], color=next(colours)) test_acc_1 = acc(model_1(test_circuits_1), test_labels_1) print('Test accuracy:', test_acc_1) data = cleaned_qnlp raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(data) print(len(raw_train_diagrams_1)) raw_train_diagrams_1[0].draw(figsize=(12,3)) train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1] dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1] test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1] train_diagrams_1[0].draw(figsize=(6,5)) render_circuit_jupyter(train_circuits_1[0].to_tk()) all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1 model_1 = NumpyModel.from_diagrams(all_circuits_1, use_jit=True) trainer_1 = QuantumTrainer( model_1, loss_function=loss, epochs=EPOCHS, optimizer=SPSAOptimizer, optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS}, evaluate_functions={'acc': acc}, evaluate_on_train=True, verbose = 'text', seed=0 ) train_dataset_1 = Dataset( train_circuits_1, train_labels_1, batch_size=BATCH_SIZE) val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False) trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=1) fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8)) ax_tl.set_title('Training set') ax_tr.set_title('Development set') ax_bl.set_xlabel('Iterations') ax_br.set_xlabel('Iterations') ax_bl.set_ylabel('Accuracy') ax_tl.set_ylabel('Loss') colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color']) ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours)) ax_bl.plot(trainer_1.train_results['acc'], color=next(colours)) ax_tr.plot(trainer_1.val_costs, color=next(colours)) ax_br.plot(trainer_1.val_results['acc'], color=next(colours)) test_acc_1 = acc(model_1(test_circuits_1), test_labels_1) print('Test accuracy:', test_acc_1)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_qsphere(state)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Evaluator of auxiliary operators for algorithms.""" from __future__ import annotations import numpy as np from qiskit import QuantumCircuit from qiskit.opflow import ( CircuitSampler, ListOp, StateFn, OperatorBase, ExpectationBase, ) from qiskit.providers import Backend from qiskit.quantum_info import Statevector from qiskit.utils import QuantumInstance from qiskit.utils.deprecation import deprecate_func from .list_or_dict import ListOrDict @deprecate_func( additional_msg=( "Instead, use the function " "``qiskit_algorithms.observables_evaluator.estimate_observables``. See " "https://qisk.it/algo_migration for a migration guide." ), since="0.24.0", ) def eval_observables( quantum_instance: QuantumInstance | Backend, quantum_state: Statevector | QuantumCircuit | OperatorBase, observables: ListOrDict[OperatorBase], expectation: ExpectationBase, threshold: float = 1e-12, ) -> ListOrDict[tuple[complex, complex]]: """ Deprecated: Accepts a list or a dictionary of operators and calculates their expectation values - means and standard deviations. They are calculated with respect to a quantum state provided. A user can optionally provide a threshold value which filters mean values falling below the threshold. This function has been superseded by the :func:`qiskit_algorithms.observables_evaluator.eval_observables` function. It will be deprecated in a future release and subsequently removed after that. Args: quantum_instance: A quantum instance used for calculations. quantum_state: An unparametrized quantum circuit representing a quantum state that expectation values are computed against. observables: A list or a dictionary of operators whose expectation values are to be calculated. expectation: An instance of ExpectationBase which defines a method for calculating expectation values. threshold: A threshold value that defines which mean values should be neglected (helpful for ignoring numerical instabilities close to 0). Returns: A list or a dictionary of tuples (mean, standard deviation). Raises: ValueError: If a ``quantum_state`` with free parameters is provided. """ if ( isinstance( quantum_state, (QuantumCircuit, OperatorBase) ) # Statevector cannot be parametrized and len(quantum_state.parameters) > 0 ): raise ValueError( "A parametrized representation of a quantum_state was provided. It is not " "allowed - it cannot have free parameters." ) # Create new CircuitSampler to avoid breaking existing one's caches. sampler = CircuitSampler(quantum_instance) list_op = _prepare_list_op(quantum_state, observables) observables_expect = expectation.convert(list_op) observables_expect_sampled = sampler.convert(observables_expect) # compute means values = np.real(observables_expect_sampled.eval()) # compute standard deviations # We use sampler.quantum_instance to take care of case in which quantum_instance is Backend std_devs = _compute_std_devs( observables_expect_sampled, observables, expectation, sampler.quantum_instance ) # Discard values below threshold observables_means = values * (np.abs(values) > threshold) # zip means and standard deviations into tuples observables_results = list(zip(observables_means, std_devs)) # Return None eigenvalues for None operators if observables is a list. # None operators are already dropped in compute_minimum_eigenvalue if observables is a dict. return _prepare_result(observables_results, observables) def _prepare_list_op( quantum_state: Statevector | QuantumCircuit | OperatorBase, observables: ListOrDict[OperatorBase], ) -> ListOp: """ Accepts a list or a dictionary of operators and converts them to a ``ListOp``. Args: quantum_state: An unparametrized quantum circuit representing a quantum state that expectation values are computed against. observables: A list or a dictionary of operators. Returns: A ``ListOp`` that includes all provided observables. """ if isinstance(observables, dict): observables = list(observables.values()) if not isinstance(quantum_state, StateFn): quantum_state = StateFn(quantum_state) return ListOp([StateFn(obs, is_measurement=True).compose(quantum_state) for obs in observables]) def _prepare_result( observables_results: list[tuple[complex, complex]], observables: ListOrDict[OperatorBase], ) -> ListOrDict[tuple[complex, complex]]: """ Prepares a list or a dictionary of eigenvalues from ``observables_results`` and ``observables``. Args: observables_results: A list of of tuples (mean, standard deviation). observables: A list or a dictionary of operators whose expectation values are to be calculated. Returns: A list or a dictionary of tuples (mean, standard deviation). """ if isinstance(observables, list): observables_eigenvalues: ListOrDict[tuple[complex, complex]] = [None] * len(observables) key_value_iterator = enumerate(observables_results) else: observables_eigenvalues = {} key_value_iterator = zip(observables.keys(), observables_results) for key, value in key_value_iterator: if observables[key] is not None: observables_eigenvalues[key] = value return observables_eigenvalues def _compute_std_devs( observables_expect_sampled: OperatorBase, observables: ListOrDict[OperatorBase], expectation: ExpectationBase, quantum_instance: QuantumInstance | Backend, ) -> list[complex]: """ Calculates a list of standard deviations from expectation values of observables provided. Args: observables_expect_sampled: Expected values of observables. observables: A list or a dictionary of operators whose expectation values are to be calculated. expectation: An instance of ExpectationBase which defines a method for calculating expectation values. quantum_instance: A quantum instance used for calculations. Returns: A list of standard deviations. """ variances = np.real(expectation.compute_variance(observables_expect_sampled)) if not isinstance(variances, np.ndarray) and variances == 0.0: # when `variances` is a single value equal to 0., our expectation value is exact and we # manually ensure the variances to be a list of the correct length variances = np.zeros(len(observables), dtype=float) # TODO: this will crash if quantum_instance is a backend std_devs = np.sqrt(variances / quantum_instance.run_config.shots) return std_devs
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pygame from qiskit import BasicAer, execute, ClassicalRegister from utils.colors import * from utils.fonts import ARIAL_30 from utils.states import comp_basis_states from copy import deepcopy #from utils.paddle import * class StatevectorGrid(pygame.sprite.Sprite): """Displays a statevector grid""" def __init__(self, circuit, qubit_num, num_shots): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.basis_states = comp_basis_states(circuit.width()) self.set_circuit(circuit, qubit_num, num_shots) # def update(self): # # Nothing yet # a = 1ot def set_circuit(self, circuit, qubit_num, shot_num): backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circuit, backend_sv_sim, shots=shot_num) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circuit, decimals=3) # This square represent the probability of state after measurement self.image = pygame.Surface([(circuit.width()+1) * 50, 500]) self.image.convert() self.image.fill(BLACK) self.rect = self.image.get_rect() block_size = int(round(500 / 2 ** qubit_num)) x_offset = 50 y_offset = 15 self.paddle = pygame.Surface([10, block_size]) self.paddle.convert() for y in range(len(quantum_state)): text_surface = ARIAL_30.render("|"+self.basis_states[y]+">", False, (255, 255, 255)) self.image.blit(text_surface,(120, y * block_size + y_offset)) if abs(quantum_state[y]) > 0: #pygame.draw.rect(self.image, WHITE, rect, 0) self.paddle.fill(WHITE) self.paddle.set_alpha(int(round(abs(quantum_state[y])*255))) self.image.blit(self.paddle,(80,y * block_size)) def set_circuit_measure(self, circuit, qubit_num, shot_num): backend_sv_sim = BasicAer.get_backend('qasm_simulator') cr = ClassicalRegister(qubit_num) circuit2 = deepcopy(circuit) circuit2.add_register(cr) circuit2.measure(circuit2.qregs[0],circuit2.cregs[0]) job_sim = execute(circuit2, backend_sv_sim, shots=shot_num) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) print(counts) #quantum_state = result_sim.get_statevector(circuit, decimals=3) # This square represent the probability of state after measurement self.image = pygame.Surface([(circuit.width()+1) * 50, 500]) self.image.convert() self.image.fill(BLACK) self.rect = self.image.get_rect() block_size = int(round(500 / 2 ** qubit_num)) x_offset = 50 y_offset = 15 self.paddle = pygame.Surface([10, block_size]) self.paddle.convert() self.paddle.fill(WHITE) #for y in range(len(quantum_state)): # text_surface = ARIAL_30.render(self.basis_states[y], False, (0, 0, 0)) # self.image.blit(text_surface,(120, y * block_size + y_offset)) # if abs(quantum_state[y]) > 0: #pygame.draw.rect(self.image, WHITE, rect, 0) #self.paddle.fill(WHITE) # self.paddle.set_alpha(int(round(abs(quantum_state[y])*255))) print(counts.keys()) print(int(list(counts.keys())[0],2)) self.image.blit(self.paddle,(80,int(list(counts.keys())[0],2) * block_size)) #pygame.time.wait(100) return int(list(counts.keys())[0],2)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
!pip install tabulate %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 * from tabulate import tabulate import numpy as np # Loading your IBM Q account(s) provider = IBMQ.load_account() def qft_dagger(n): """n-qubit QFTdagger the first n qubits in circ""" qc = QuantumCircuit(n) # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cu1(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc def __c_amod15(power): """Controlled multiplication by a mod 15""" U = QuantumCircuit(4) for iteration in range(power): U.swap(2,3) U.swap(1,2) U.swap(0,1) for q in range(4): U.x(q) U = U.to_gate() U.name = "a^%i mod 15" % (power) c_U = U.control() return c_U t=3 qc = QuantumCircuit(t+4,t) for i in range(t): qc.h(i) # The first t qubits are the first register (storing 'x') qc.x(6) #The second register is in state |1> # Oracle for the f(x) mentioned above def Oracle(qc): for q in range(3): qc.append(__c_amod15(2**q), [q] + [i+3 for i in range(4)]) Oracle(qc) qc.append(qft_dagger(t),range(t)) # inverse quantum fourier transform only of the register (first 4 qubits) qc.measure(range(t), range(t)) def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 100000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc) print(counts) plot_histogram(counts) rows, eigenvalues = [], [] for output in counts: decimal = int(output, 2) eigenvalue = decimal/(2**t) eigenvalues.append(eigenvalue) rows.append(["%s(bin) = %i(dec)" % (output, decimal), "%i/%i = %.2f" % (decimal, 2**t, eigenvalue)]) print(tabulate(rows, headers=["Register Output", "Phase"])) 0.333333333.as_integer_ratio() rows = [] for eigenvalue in eigenvalues: numerator, denominator = eigenvalue.as_integer_ratio() rows.append([eigenvalue, "%i/%i" % (numerator, denominator), denominator]) print(tabulate(rows, headers=["Phase", "Fraction", "Guess for r"], colalign=('right','right','right')))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 42 from qiskit.circuit import Parameter from qiskit import QuantumCircuit params1 = [Parameter("input1"), Parameter("weight1")] qc1 = QuantumCircuit(1) qc1.h(0) qc1.ry(params1[0], 0) qc1.rx(params1[1], 0) qc1.draw("mpl") from qiskit.quantum_info import SparsePauliOp observable1 = SparsePauliOp.from_list([("Y" * qc1.num_qubits, 1)]) from qiskit_machine_learning.neural_networks import EstimatorQNN estimator_qnn = EstimatorQNN( circuit=qc1, observables=observable1, input_params=[params1[0]], weight_params=[params1[1]] ) estimator_qnn from qiskit.circuit import ParameterVector inputs2 = ParameterVector("input", 2) weights2 = ParameterVector("weight", 4) print(f"input parameters: {[str(item) for item in inputs2.params]}") print(f"weight parameters: {[str(item) for item in weights2.params]}") qc2 = QuantumCircuit(2) qc2.ry(inputs2[0], 0) qc2.ry(inputs2[1], 1) qc2.cx(0, 1) qc2.ry(weights2[0], 0) qc2.ry(weights2[1], 1) qc2.cx(0, 1) qc2.ry(weights2[2], 0) qc2.ry(weights2[3], 1) qc2.draw(output="mpl") from qiskit_machine_learning.neural_networks import SamplerQNN sampler_qnn = SamplerQNN(circuit=qc2, input_params=inputs2, weight_params=weights2) sampler_qnn estimator_qnn_input = algorithm_globals.random.random(estimator_qnn.num_inputs) estimator_qnn_weights = algorithm_globals.random.random(estimator_qnn.num_weights) print( f"Number of input features for EstimatorQNN: {estimator_qnn.num_inputs} \nInput: {estimator_qnn_input}" ) print( f"Number of trainable weights for EstimatorQNN: {estimator_qnn.num_weights} \nWeights: {estimator_qnn_weights}" ) sampler_qnn_input = algorithm_globals.random.random(sampler_qnn.num_inputs) sampler_qnn_weights = algorithm_globals.random.random(sampler_qnn.num_weights) print( f"Number of input features for SamplerQNN: {sampler_qnn.num_inputs} \nInput: {sampler_qnn_input}" ) print( f"Number of trainable weights for SamplerQNN: {sampler_qnn.num_weights} \nWeights: {sampler_qnn_weights}" ) estimator_qnn_forward = estimator_qnn.forward(estimator_qnn_input, estimator_qnn_weights) print( f"Forward pass result for EstimatorQNN: {estimator_qnn_forward}. \nShape: {estimator_qnn_forward.shape}" ) sampler_qnn_forward = sampler_qnn.forward(sampler_qnn_input, sampler_qnn_weights) print( f"Forward pass result for SamplerQNN: {sampler_qnn_forward}. \nShape: {sampler_qnn_forward.shape}" ) estimator_qnn_forward_batched = estimator_qnn.forward( [estimator_qnn_input, estimator_qnn_input], estimator_qnn_weights ) print( f"Forward pass result for EstimatorQNN: {estimator_qnn_forward_batched}. \nShape: {estimator_qnn_forward_batched.shape}" ) sampler_qnn_forward_batched = sampler_qnn.forward( [sampler_qnn_input, sampler_qnn_input], sampler_qnn_weights ) print( f"Forward pass result for SamplerQNN: {sampler_qnn_forward_batched}. \nShape: {sampler_qnn_forward_batched.shape}" ) estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward( estimator_qnn_input, estimator_qnn_weights ) print( f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad}" ) print( f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}" ) sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward( sampler_qnn_input, sampler_qnn_weights ) print( f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) estimator_qnn.input_gradients = True sampler_qnn.input_gradients = True estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward( estimator_qnn_input, estimator_qnn_weights ) print( f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad.shape}" ) print( f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}" ) sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward( sampler_qnn_input, sampler_qnn_weights ) print( f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad.shape}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) observable2 = SparsePauliOp.from_list([("Z" * qc1.num_qubits, 1)]) estimator_qnn2 = EstimatorQNN( circuit=qc1, observables=[observable1, observable2], input_params=[params1[0]], weight_params=[params1[1]], ) estimator_qnn_forward2 = estimator_qnn2.forward(estimator_qnn_input, estimator_qnn_weights) estimator_qnn_input_grad2, estimator_qnn_weight_grad2 = estimator_qnn2.backward( estimator_qnn_input, estimator_qnn_weights ) print(f"Forward output for EstimatorQNN1: {estimator_qnn_forward.shape}") print(f"Forward output for EstimatorQNN2: {estimator_qnn_forward2.shape}") print(f"Backward output for EstimatorQNN1: {estimator_qnn_weight_grad.shape}") print(f"Backward output for EstimatorQNN2: {estimator_qnn_weight_grad2.shape}") parity = lambda x: "{:b}".format(x).count("1") % 2 output_shape = 2 # parity = 0, 1 sampler_qnn2 = SamplerQNN( circuit=qc2, input_params=inputs2, weight_params=weights2, interpret=parity, output_shape=output_shape, ) sampler_qnn_forward2 = sampler_qnn2.forward(sampler_qnn_input, sampler_qnn_weights) sampler_qnn_input_grad2, sampler_qnn_weight_grad2 = sampler_qnn2.backward( sampler_qnn_input, sampler_qnn_weights ) print(f"Forward output for SamplerQNN1: {sampler_qnn_forward.shape}") print(f"Forward output for SamplerQNN2: {sampler_qnn_forward2.shape}") print(f"Backward output for SamplerQNN1: {sampler_qnn_weight_grad.shape}") print(f"Backward output for SamplerQNN2: {sampler_qnn_weight_grad2.shape}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Interlin-q/diskit
Interlin-q
import os from qiskit import * import qiskit.tools.visualization as qt from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi import matplotlib.pyplot as plt %matplotlib inline qreg_q = QuantumRegister(2, 'q') creg_c = ClassicalRegister(2, 'c') circuits = [] for i in range(0, 4): circuits.append(QuantumCircuit(qreg_q, creg_c)) circuits[0].reset(qreg_q[0]) circuits[0].reset(qreg_q[1]) circuits[0].cx(qreg_q[0], qreg_q[1]) circuits[0].measure(qreg_q[0], creg_c[0]) circuits[0].measure(qreg_q[1], creg_c[1]) circuits[0].draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result00 = execute(circuits[0], backend = simulator, shots = 1).result() counts00 = result00.get_counts() print(counts00) qt.plot_histogram(counts00, title="Histogram with the evaluating of |00> state under CNOT transformation") circuits[1].reset(qreg_q[0]) circuits[1].x(qreg_q[1]) circuits[1].cx(qreg_q[0], qreg_q[1]) circuits[1].measure(qreg_q[0], creg_c[0]) circuits[1].measure(qreg_q[1], creg_c[1]) circuits[1].draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result01 = execute(circuits[1], backend = simulator, shots = 1).result() counts01 = result01.get_counts() print(counts01) qt.plot_histogram(counts01, title="Histogram with the evaluating of |01> state under CNOT transformation") circuits[2].x(qreg_q[0]) circuits[2].reset(qreg_q[1]) circuits[2].cx(qreg_q[0], qreg_q[1]) circuits[2].measure(qreg_q[0], creg_c[0]) circuits[2].measure(qreg_q[1], creg_c[1]) circuits[2].draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result10 = execute(circuits[2], backend = simulator, shots = 1).result() counts10 = result10.get_counts() print(counts10) qt.plot_histogram(counts10, title="Histogram with the evaluating of |10> state under CNOT transformation") circuits[3].x(qreg_q[0]) circuits[3].x(qreg_q[1]) circuits[3].cx(qreg_q[0], qreg_q[1]) circuits[3].measure(qreg_q[0], creg_c[0]) circuits[3].measure(qreg_q[1], creg_c[1]) circuits[3].draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result11 = execute(circuits[3], backend = simulator, shots = 1).result() counts11 = result11.get_counts() print(counts11) qt.plot_histogram(counts11, title="Histogram with the evaluating of |11> state under CNOT transformation")
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import time import itertools import numpy as np from scipy.optimize import minimize, basinhopping from qiskit import * from qiskit.quantum_info import Statevector from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA from qiskit.opflow.state_fns import StateFn, CircuitStateFn from qiskit.providers.aer import StatevectorSimulator, AerSimulator import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.colors import BoundaryNorm from modules.utils import * %matplotlib inline cmap = plt.get_cmap("plasma") #'viridis' import qiskit #%matplotlib inline print(qiskit.__version__) ### Preliminaries L = 5 num_trash = 3 logspace_size=50 name = f'VQE_Ising_L5_anti_-1_50x50' # _1e-3 # name of the data produced by this notebook filename = "data/params_" + name # name of the data file that is used L = 5 anti = -1. VQE_params = np.load(filename + ".npz", allow_pickle=True) gx_list = VQE_params['gx_list'] gz_list = VQE_params['gz_list'] opt_params = VQE_params['opt_params'] gx_vals = np.unique(gx_list) gz_vals = np.unique(gz_list) mag = QMag(L,anti) #magnetization operator (Qiskit) Smag = Mag(L,anti) #magnetization operator (numpy) # the ~ is the adjoint, but also it turns the is_measurement attribute to True ~StateFn(mag) # state is technically a circuit, that prepares the ground state via VQE circuit #state.draw() # uncomment to see, but is very long Qen=np.zeros(len(opt_params)); Sen=np.zeros(len(opt_params)) #energies Qmags=np.zeros(len(opt_params)); Smags=np.zeros(len(opt_params)) #magnetizations load = True if load: temp = np.load(filename + "_mags-Es.npz",allow_pickle=True) Qmags = temp["Qmags"] Qen = temp["Qen"] Sen = temp["Sen"] Smags = temp["Smags"] if not load: for j in range(len(opt_params)): gx = gx_list[j] gz = gz_list[j] H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op state = init_vqe(opt_params[j], L=L) StateFn(state) meas_outcome = ~StateFn(mag) @ StateFn(state) Qmags[j] = meas_outcome.eval() e_outcome = ~StateFn(H) @ StateFn(state) Qen[j] = e_outcome.eval() init_state, E, ham = ising_groundstate(L, anti, np.float(gx), np.float(gz)) Sen[j] = E Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results np.savez(filename + "_mags-Es",Qmags=Qmags, Qen=Qen, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, abs(Smags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Magnetization ED L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, abs(Qmags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) fig,ax = plt.subplots(figsize=(8,5)) cmap = plt.get_cmap("plasma") #'viridis' im = ax.pcolormesh(gz_vals, gx_vals, Sen.reshape(len(gz_vals),len(gx_vals)) - Qen.reshape(len(gz_vals),len(gx_vals)), cmap=cmap) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) plt.xscale("log") plt.yscale("log") ax.set_title("Difference in energy L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) ############################################################################## ### II - Training ########################################################### ############################################################################## # Use Aer's qasm_simulator backend_sim = Aer.get_backend('qasm_simulator') thetas = np.random.uniform(0, 2*np.pi, num_trash*L+num_trash) # initial parameters without feature encoding # thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-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"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(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 range(num_trash): circ.ry(thetas[L-i-1], L-i-1) #circ.ry(circuit.Parameter(f'θ{i}'), L-i-1) return circ def prepare_circuit(thetas, L=5, num_trash=3, 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=True)#.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 = init_vqe(init_state,L=L) + circ 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 thetas.shape idx = 30 num_trash = 3 J, gx, gz = -1., gx_list[idx], gz_list[idx] # Ising parameters for which ground state should be compressed phi = opt_params[idx] # train on smallest lambda ;; this may grammatically be confusing, init_state = dictionary with unsorted parameters def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100): circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe) # Execute the circuit on the qasm simulator. job_sim = execute(circ, backend_sim, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible # Grab the results from the job. result_sim = job_sim.result() counts = result_sim.get_counts(circ) # print(counts) # mems = result_sim.get_memory(circ) # print(mems) return counts run_circuit(thetas, L, num_trash, phi)['11'] # translate to Rikes naming phis = opt_params gxs = gx_list gzs = gz_list def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0): """ 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) 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): """ 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]) else: cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding) return cost/n_samples def optimize(ising_params, L=6, num_trash=3, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None): if thetas is None: n_params = (2*L+2)*2 if param_encoding else (num_trash*L+num_trash) thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding print(f"initial thetas: {thetas}") 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=1e-1, #perturbation=0.4 ) # 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)), initial_point=thetas ) print("Time: {:.5f} sec".format(time.time()-start_time)) print(ret) return ret[0], values, accepted x,y = np.meshgrid(gx_vals, gz_vals) def run_inference(thetas, shots=1000, L=5): 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))): cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots) cost = cost.reshape((len(gx_vals), len(gz_vals))) return cost cmap = plt.get_cmap("plasma") def plot_result(cost): fig,axs = plt.subplots(ncols=2,figsize=(15,5)) nbins=100 ax = axs[0] im = ax.pcolormesh(x, y, cost, cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xscale("log") ax.set_yscale("log") ax.set_title(f"Loss",fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) for p in params: gz = gz_list[p] gx = gx_list[p] ax.plot(gz,gx,"o",label="training",color="cyan") ax = axs[1] im = ax.pcolormesh(gz_vals, gx_vals, abs(Qmags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap, shading="auto") cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xscale("log") ax.set_yscale("log") ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20) ax.set_xlabel(r"$g_z$",fontsize=24) ax.set_ylabel(r"$g_x$",fontsize=24) ax.tick_params(labelsize=20) #reset random seed np.random.seed(123) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 np.intersect1d( np.intersect1d(np.where(gx_list > 5e-2),np.where(1e-1 > gx_list)), np.intersect1d(np.where(gz_list > 5e-2),np.where(1e-1 > gz_list)) ) paramss =[ [0], # train on bottom left point [0], ] for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetass = [None] * len(paramss) losss = [None] * len(paramss) costs = [None] * len(paramss) thetas.shape run_circuit(thetas, L=5, num_trash=3, init_state = phis[0]) optimize(paramss[0], num_trash=3,L=5,max_iter=100) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") thetas, loss, accepted = optimize(params, num_trash=3, max_iter=100, L=5) #, pick_optimizer="adam") thetass[i], losss[i] = thetas, loss plt.plot(loss) cost = run_inference(thetas) costs[i] = cost filename2 = "data/" + name + "_thetas-loss-cost_vary-training-states_num_trash-3" np.savez(filename2, losss = losss, costs = costs, thetass = thetass) for i,params in enumerate(paramss): print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}") plot_result(np.load(filename2 + ".npz",allow_pickle=True)["costs"][i]) plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import IBMQ, transpile from qiskit import QuantumCircuit from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram from qiskit.providers.fake_provider import FakeVigo device_backend = FakeVigo() # Construct quantum circuit circ = QuantumCircuit(3, 3) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.measure([0, 1, 2], [0, 1, 2]) sim_ideal = AerSimulator() # Execute and get counts result = sim_ideal.run(transpile(circ, sim_ideal)).result() counts = result.get_counts(0) plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state') sim_vigo = AerSimulator.from_backend(device_backend) # Transpile the circuit for the noisy basis gates tcirc = transpile(circ, sim_vigo) # Execute noisy simulation and get counts result_noise = sim_vigo.run(tcirc).result() counts_noise = result_noise.get_counts(0) plot_histogram(counts_noise, title="Counts for 3-qubit GHZ state with device noise model") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-function-docstring """Test scheduled circuit (quantum circuit with duration).""" from ddt import ddt, data from qiskit import QuantumCircuit, QiskitError from qiskit import transpile, assemble, BasicAer from qiskit.circuit import Parameter from qiskit.providers.fake_provider import FakeParis from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.test.base import QiskitTestCase @ddt class TestScheduledCircuit(QiskitTestCase): """Test scheduled circuit (quantum circuit with duration).""" def setUp(self): super().setUp() self.backend_with_dt = FakeParis() self.backend_without_dt = FakeParis() delattr(self.backend_without_dt.configuration(), "dt") self.dt = 2.2222222222222221e-10 self.simulator_backend = BasicAer.get_backend("qasm_simulator") def test_schedule_circuit_when_backend_tells_dt(self): """dt is known to transpiler by backend""" qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") # 450000[dt] qc.delay(100, 0, unit="ns") # 450[dt] qc.h(0) # 160[dt] qc.h(1) # 160[dt] sc = transpile(qc, self.backend_with_dt, scheduling_method="alap", layout_method="trivial") self.assertEqual(sc.duration, 450610) self.assertEqual(sc.unit, "dt") self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 450450) self.assertEqual(sc.data[0].operation.unit, "dt") self.assertEqual(sc.data[1].operation.name, "rz") self.assertEqual(sc.data[1].operation.duration, 0) self.assertEqual(sc.data[1].operation.unit, "dt") self.assertEqual(sc.data[4].operation.name, "delay") self.assertEqual(sc.data[4].operation.duration, 450450) self.assertEqual(sc.data[4].operation.unit, "dt") qobj = assemble(sc, self.backend_with_dt) self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(qobj.experiments[0].instructions[0].params[0], 450450) self.assertEqual(qobj.experiments[0].instructions[4].name, "delay") self.assertEqual(qobj.experiments[0].instructions[4].params[0], 450450) def test_schedule_circuit_when_transpile_option_tells_dt(self): """dt is known to transpiler by transpile option""" qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") # 450000[dt] qc.delay(100, 0, unit="ns") # 450[dt] qc.h(0) qc.h(1) sc = transpile( qc, self.backend_without_dt, scheduling_method="alap", dt=self.dt, layout_method="trivial", ) self.assertEqual(sc.duration, 450610) self.assertEqual(sc.unit, "dt") self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 450450) self.assertEqual(sc.data[0].operation.unit, "dt") self.assertEqual(sc.data[1].operation.name, "rz") self.assertEqual(sc.data[1].operation.duration, 0) self.assertEqual(sc.data[1].operation.unit, "dt") self.assertEqual(sc.data[4].operation.name, "delay") self.assertEqual(sc.data[4].operation.duration, 450450) self.assertEqual(sc.data[4].operation.unit, "dt") def test_schedule_circuit_in_sec_when_no_one_tells_dt(self): """dt is unknown and all delays and gate times are in SI""" qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") qc.delay(100, 0, unit="ns") qc.h(0) qc.h(1) sc = transpile( qc, self.backend_without_dt, scheduling_method="alap", layout_method="trivial" ) self.assertAlmostEqual(sc.duration, 450610 * self.dt) self.assertEqual(sc.unit, "s") self.assertEqual(sc.data[0].operation.name, "delay") self.assertAlmostEqual(sc.data[0].operation.duration, 1.0e-4 + 1.0e-7) self.assertEqual(sc.data[0].operation.unit, "s") self.assertEqual(sc.data[1].operation.name, "rz") self.assertAlmostEqual(sc.data[1].operation.duration, 160 * self.dt) self.assertEqual(sc.data[1].operation.unit, "s") self.assertEqual(sc.data[4].operation.name, "delay") self.assertAlmostEqual(sc.data[4].operation.duration, 1.0e-4 + 1.0e-7) self.assertEqual(sc.data[4].operation.unit, "s") with self.assertRaises(QiskitError): assemble(sc, self.backend_without_dt) def test_cannot_schedule_circuit_with_mixed_SI_and_dt_when_no_one_tells_dt(self): """dt is unknown but delays and gate times have a mix of SI and dt""" qc = QuantumCircuit(2) qc.delay(100, 0, unit="ns") qc.delay(30, 0, unit="dt") qc.h(0) qc.h(1) with self.assertRaises(QiskitError): transpile(qc, self.backend_without_dt, scheduling_method="alap") def test_transpile_single_delay_circuit(self): qc = QuantumCircuit(1) qc.delay(1234, 0) sc = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") self.assertEqual(sc.duration, 1234) self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 1234) self.assertEqual(sc.data[0].operation.unit, "dt") def test_transpile_t1_circuit(self): qc = QuantumCircuit(1) qc.x(0) # 320 [dt] qc.delay(1000, 0, unit="ns") # 4500 [dt] qc.measure_all() # 19584 [dt] scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") self.assertEqual(scheduled.duration, 23060) def test_transpile_delay_circuit_with_backend(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(100, 1, unit="ns") # 450 [dt] qc.cx(0, 1) # 1760 [dt] scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" ) self.assertEqual(scheduled.duration, 2082) def test_transpile_delay_circuit_without_backend(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) scheduled = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)], ) self.assertEqual(scheduled.duration, 1200) def test_transpile_circuit_with_custom_instruction(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5154""" bell = QuantumCircuit(2, name="bell") bell.h(0) bell.cx(0, 1) qc = QuantumCircuit(2) qc.delay(500, 1) qc.append(bell.to_instruction(), [0, 1]) scheduled = transpile( qc, scheduling_method="alap", instruction_durations=[("bell", [0, 1], 1000)] ) self.assertEqual(scheduled.duration, 1500) def test_transpile_delay_circuit_with_dt_but_without_scheduling_method(self): qc = QuantumCircuit(1) qc.delay(100, 0, unit="ns") transpiled = transpile(qc, backend=self.backend_with_dt) self.assertEqual(transpiled.duration, None) # not scheduled self.assertEqual(transpiled.data[0].operation.duration, 450) # unit is converted ns -> dt def test_transpile_delay_circuit_without_scheduling_method_or_durs(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) not_scheduled = transpile(qc) self.assertEqual(not_scheduled.duration, None) def test_raise_error_if_transpile_with_scheduling_method_but_without_durations(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) with self.assertRaises(TranspilerError): transpile(qc, scheduling_method="alap") def test_invalidate_schedule_circuit_if_new_instruction_is_appended(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500 * self.dt, 1, "s") qc.cx(0, 1) scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") # append a gate to a scheduled circuit scheduled.h(0) self.assertEqual(scheduled.duration, None) def test_default_units_for_my_own_duration_users(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) # accept None for qubits scheduled = transpile( qc, basis_gates=["h", "cx", "delay"], scheduling_method="alap", instruction_durations=[("h", 0, 200), ("cx", None, 900)], ) self.assertEqual(scheduled.duration, 1400) # prioritize specified qubits over None scheduled = transpile( qc, basis_gates=["h", "cx", "delay"], scheduling_method="alap", instruction_durations=[("h", 0, 200), ("cx", None, 900), ("cx", [0, 1], 800)], ) self.assertEqual(scheduled.duration, 1300) def test_unit_seconds_when_using_backend_durations(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500 * self.dt, 1, "s") qc.cx(0, 1) # usual case scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" ) self.assertEqual(scheduled.duration, 2132) # update durations durations = InstructionDurations.from_backend(self.backend_with_dt) durations.update([("cx", [0, 1], 1000 * self.dt, "s")]) scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", instruction_durations=durations, layout_method="trivial", ) self.assertEqual(scheduled.duration, 1500) def test_per_qubit_durations(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5109""" qc = QuantumCircuit(3) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) qc.h(1) sc = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", None, 200), ("cx", [0, 1], 700)], ) self.assertEqual(sc.qubit_start_time(0), 300) self.assertEqual(sc.qubit_stop_time(0), 1200) self.assertEqual(sc.qubit_start_time(1), 500) self.assertEqual(sc.qubit_stop_time(1), 1400) self.assertEqual(sc.qubit_start_time(2), 0) self.assertEqual(sc.qubit_stop_time(2), 0) self.assertEqual(sc.qubit_start_time(0, 1), 300) self.assertEqual(sc.qubit_stop_time(0, 1), 1400) qc.measure_all() sc = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx", "measure"], instruction_durations=[("h", None, 200), ("cx", [0, 1], 700), ("measure", None, 1000)], ) q = sc.qubits self.assertEqual(sc.qubit_start_time(q[0]), 300) self.assertEqual(sc.qubit_stop_time(q[0]), 2400) self.assertEqual(sc.qubit_start_time(q[1]), 500) self.assertEqual(sc.qubit_stop_time(q[1]), 2400) self.assertEqual(sc.qubit_start_time(q[2]), 1400) self.assertEqual(sc.qubit_stop_time(q[2]), 2400) self.assertEqual(sc.qubit_start_time(*q), 300) self.assertEqual(sc.qubit_stop_time(*q), 2400) def test_change_dt_in_transpile(self): qc = QuantumCircuit(1, 1) qc.x(0) qc.measure(0, 0) # default case scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="asap") org_duration = scheduled.duration # halve dt in sec = double duration in dt scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="asap", dt=self.dt / 2 ) self.assertEqual(scheduled.duration, org_duration * 2) @data("asap", "alap") def test_duration_on_same_instruction_instance(self, scheduling_method): """See: https://github.com/Qiskit/qiskit-terra/issues/5771""" assert self.backend_with_dt.properties().gate_length( "cx", (0, 1) ) != self.backend_with_dt.properties().gate_length("cx", (1, 2)) qc = QuantumCircuit(3) qc.cz(0, 1) qc.cz(1, 2) sc = transpile(qc, backend=self.backend_with_dt, scheduling_method=scheduling_method) cxs = [inst.operation for inst in sc.data if inst.operation.name == "cx"] self.assertNotEqual(cxs[0].duration, cxs[1].duration) def test_transpile_and_assemble_delay_circuit_for_simulator(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5962""" qc = QuantumCircuit(1) qc.delay(100, 0, "ns") circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(qobj.experiments[0].instructions[0].params[0], 1e-7) def test_transpile_and_assemble_t1_circuit_for_simulator(self): """Check if no scheduling is done in transpiling for simulator backends""" qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(0.1, 0, "us") qc.measure(0, 0) circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[1].name, "delay") self.assertAlmostEqual(qobj.experiments[0].instructions[1].params[0], 1e-7) # Tests for circuits with parameterized delays def test_can_transpile_circuits_after_assigning_parameters(self): """Check if not scheduled but duration is converted in dt""" idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = qc.assign_parameters({idle_dur: 0.1}) circ = transpile(qc, self.backend_with_dt) self.assertEqual(circ.duration, None) # not scheduled self.assertEqual(circ.data[1].operation.duration, 450) # converted in dt def test_can_transpile_and_assemble_circuits_with_assigning_parameters_inbetween(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) circ = transpile(qc, self.backend_with_dt) circ = circ.assign_parameters({idle_dur: 0.1}) qobj = assemble(circ, self.backend_with_dt) self.assertEqual(qobj.experiments[0].instructions[1].name, "delay") self.assertEqual(qobj.experiments[0].instructions[1].params[0], 450) def test_can_transpile_circuits_with_unbounded_parameters(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) # not assign parameter circ = transpile(qc, self.backend_with_dt) self.assertEqual(circ.duration, None) # not scheduled self.assertEqual(circ.data[1].operation.unit, "dt") # converted in dt self.assertEqual( circ.data[1].operation.duration, idle_dur * 1e-6 / self.dt ) # still parameterized def test_fail_to_assemble_circuits_with_unbounded_parameters(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = transpile(qc, self.backend_with_dt) with self.assertRaises(QiskitError): assemble(qc, self.backend_with_dt) @data("asap", "alap") def test_can_schedule_circuits_with_bounded_parameters(self, scheduling_method): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = qc.assign_parameters({idle_dur: 0.1}) circ = transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method) self.assertIsNotNone(circ.duration) # scheduled @data("asap", "alap") def test_fail_to_schedule_circuits_with_unbounded_parameters(self, scheduling_method): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) # not assign parameter with self.assertRaises(TranspilerError): transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method)
https://github.com/Pitt-JonesLab/slam_decomposition
Pitt-JonesLab
"""Define circuits to test.""" from supermarq.benchmarks.ghz import GHZ from supermarq.benchmarks.hamiltonian_simulation import HamiltonianSimulation from supermarq.benchmarks.qaoa_vanilla_proxy import QAOAVanillaProxy from supermarq.converters import cirq_to_qiskit class CircuitTranspilerBenchmark: # TODO: circuit_lambda could take multiple params if desired def __init__(self, circuit_lambda, q_range, label): self.circuit_lambda = circuit_lambda # self.q_range = q_range self.label = label # FIXME should this be a class, q_range is a parameter, instead of dict use get methods circuits = {} depth = 10 q_range = None # deprecated, move to backendbenchmark object # Random # from qiskit.circuit.random import random_circuit # random_lambda = lambda q: random_circuit(q, depth, measure=False, max_operands=2) # label = "Randomized_QC" # circuits[label] = CircuitTranspilerBenchmark(random_lambda, q_range, label=label) # # Quantum Volume from qiskit.circuit.library import QuantumVolume def qv_lambda(q): return QuantumVolume(num_qubits=q, depth=q) label = "Quantum_Volume" circuits[label] = CircuitTranspilerBenchmark(qv_lambda, q_range, label=label) # QFT from qiskit.circuit.library.basis_change import QFT def qft_lambda(q): return QFT(q) label = "QFT" circuits[label] = CircuitTranspilerBenchmark(qft_lambda, q_range, label=label) # # Inverse QFT # inverse_qft_lambda = lambda q: QFT(q, inverse=True) # label = "IQFT" # circuits[label] = CircuitTranspilerBenchmark(inverse_qft_lambda, q_range, label=label) # QAOA, takes a long time to generate - consider capping max size before 20 # qaoa_lambda = lambda q: cirq_to_qiskit(QAOAFermionicSwapProxy(q).circuit()) # label = "QAOA_Fermionic_Swap" # circuits[label] = CircuitTranspilerBenchmark(qaoa_lambda, q_range, label=label) # # QAOA vanilla def qaoa_vanilla_lambda(q): return cirq_to_qiskit(QAOAVanillaProxy(q).circuit()) label = "QAOA_Vanilla" circuits[label] = CircuitTranspilerBenchmark(qaoa_vanilla_lambda, q_range, label=label) # VQE - very slow to generate # vqe_lambda = lambda q: cirq_to_qiskit(VQEProxy(q, 4).circuit()[0]) # label = "VQE" # circuits[label] = CircuitTranspilerBenchmark(vqe_lambda, q_range, label=label) # Simulation def hamiltonian_lambda(q): return cirq_to_qiskit(HamiltonianSimulation(q, 1 / depth, 0.5).circuit()) label = "TIM_Hamiltonian" circuits[label] = CircuitTranspilerBenchmark(hamiltonian_lambda, q_range, label=label) from qiskit import QuantumCircuit # weighted adder or ripple carry adder from qiskit.circuit.library.arithmetic.adders.cdkm_ripple_carry_adder import ( CDKMRippleCarryAdder, ) # using trick of composing into an empty circuit so that it builds everything into a single quantumregister def adder_lambda(q): return ( QuantumCircuit(q) .compose(CDKMRippleCarryAdder(num_state_qubits=int((q - 1) / 2)), inplace=False) .decompose() .decompose() .decompose() ) label = "Adder" circuits[label] = CircuitTranspilerBenchmark(adder_lambda, q_range, label=label) # multiplier # from qiskit.circuit.library.arithmetic.multipliers import RGQFTMultiplier # multiplier_lambda = ( # lambda q: QuantumCircuit(q) # .compose(RGQFTMultiplier(num_state_qubits=int(q / 4)), inplace=False) # .decompose() # .decompose() # .decompose() # ) # label = "Multiplier" # circuits[label] = CircuitTranspilerBenchmark(multiplier_lambda, q_range, label=label) # # GHZ def ghz_lambda(q): return cirq_to_qiskit(GHZ(q).circuit()) label = "GHZ" circuits[label] = CircuitTranspilerBenchmark(ghz_lambda, q_range, label=label)
https://github.com/yaelbh/qiskit-sympy-provider
yaelbh
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=invalid-name,missing-docstring from test.common import QiskitSympyTestCase import unittest from sympy import sqrt from qiskit import (load_qasm_file, execute, QuantumRegister, ClassicalRegister, QuantumCircuit, wrapper) from qiskit_addon_sympy import SympyProvider class SympyStatevectorSimulatorTest(QiskitSympyTestCase): """Test local statevector simulator.""" def setUp(self): self.qasm_filename = self._get_resource_path('simple.qasm') self.q_circuit = load_qasm_file(self.qasm_filename) def test_sympy_statevector_simulator(self): """Test final state vector for single circuit run.""" SyQ = SympyProvider() backend = SyQ.get_backend('statevector_simulator') result = execute(self.q_circuit, backend).result() actual = result.get_statevector(self.q_circuit) self.assertEqual(result.get_status(), 'COMPLETED') self.assertEqual(actual[0], sqrt(2)/2) self.assertEqual(actual[1], 0) self.assertEqual(actual[2], 0) self.assertEqual(actual[3], sqrt(2)/2) class TestQobj(QiskitSympyTestCase): """Check the objects compiled for this backend create names properly""" def setUp(self): qr = QuantumRegister(2, name="qr2") cr = ClassicalRegister(2, name=None) qc = QuantumCircuit(qr, cr, name="qc10") qc.h(qr[0]) qc.measure(qr[0], cr[0]) self.qr_name = qr.name self.cr_name = cr.name self.circuits = [qc] def test_qobj_sympy_statevector_simulator(self): SyQ = SympyProvider() backend = SyQ.get_backend('statevector_simulator') qobj = wrapper.compile(self.circuits, backend) cc = qobj.experiments[0].as_dict() ccq = qobj.experiments[0].header.compiled_circuit_qasm self.assertIn(self.qr_name, map(lambda x: x[0], cc['header']['qubit_labels'])) self.assertIn(self.qr_name, ccq) self.assertIn(self.cr_name, map(lambda x: x[0], cc['header']['clbit_labels'])) self.assertIn(self.cr_name, ccq) if __name__ == '__main__': unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
hamburgerguy
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """ # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle #set b equal to '11' b = '11' #1) initialize qubits n = 2 simon_circuit_2 = QuantumCircuit(n*2, n) #2) Apply Hadamard gates before querying the oracle simon_circuit_2.h(range(n)) #3) Query oracle simon_circuit_2 += simon_oracle(b) #5) Apply Hadamard gates to the input register simon_circuit_2.h(range(n)) #3) and 6) Measure qubits simon_circuit_2.measure(range(n), range(n)) # Load saved IBMQ accounts and get the least busy backend device IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Execute and monitor the job from qiskit.tools.monitor import job_monitor shots = 1024 job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) # Get results and plot counts device_counts = job.result().get_counts() plot_histogram(device_counts) #additionally, function for calculating dot product of results def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) print('b = ' + b) for z in device_counts: print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots)) #the most significant results are those for which b dot z=0(mod 2). '''b = 11 11.00 = 0 (mod 2) (45.0%) 11.01 = 1 (mod 2) (6.2%) 11.10 = 1 (mod 2) (6.4%) 11.11 = 0 (mod 2) (42.4%)'''
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can choose different colors for the real and imaginary parts of the density matrix. from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = DensityMatrix(qc) plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import * qr = QuantumRegister(3, 'q') cr = ClassicalRegister(2, 'zx_meas') qc = QuantumCircuit(qr,cr) qc.reset(range(3)) qc.barrier() qc.h(1) qc.cx([1,0],[2,1]) qc.h(0) qc.barrier() qc.measure([0,1], [0,1]) qc.barrier() qc.z(2).c_if(cr, 1) qc.x(2).c_if(cr, 2)
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
mcoggins96
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute,IBMQ from qiskit.tools.monitor import job_monitor import numpy import matplotlib.pyplot as plt pi = numpy.pi IBMQ.enable_account('ENTER API KEY HERE') provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_armonk') q = QuantumRegister(1,'q') c = ClassicalRegister(1,'c') phi = 0 a = [] b = [] xticks = [] qc_list = [] while phi <= 2*pi: xticks.append(phi) circuit = QuantumCircuit(q,c) circuit.rx(phi,q[0]) #RX gate where Phi is the rotation angle circuit.measure(q,c) # Qubit Measurement qc_list.append(circuit) phi += pi/8 job = execute(qc_list, backend, shots=8192) job_monitor(job) counts = job.result().get_counts() highest_count1 = 0 highest_count1_1 = 0 highest_count1_0 = 0 index1 = 0 highest_count0 = 0 highest_count0_1 = 0 highest_count0_0 = 0 index0 = 0 for count in counts: a.append(count['0']) b.append(count['1']) if count['1'] > highest_count1: highest_count1 = count['1'] index1 = counts.index(count) highest_count1_1 = count['1'] highest_count1_0 = count['0'] if count['0'] > highest_count0: highest_count0 = count['0'] index0 = counts.index(count) highest_count0_1 = count['1'] highest_count0_0 = count['0'] print("\nOptimal rotation angle for '1' is: ", xticks[index1], ", Counts: 0:", highest_count1_0, "1:", highest_count1_1) print("Optimal rotation angle for '0' is: ", xticks[index0], ", Counts: 0:", highest_count0_0, "1:", highest_count0_1) plt.suptitle('Rabi Oscillations on IBMQ Armonk') plt.plot(xticks,a) plt.plot(xticks,b) plt.legend(["Measurements for '0' ", "Measurements for '1'"]) plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Useful additional packages import matplotlib.pyplot as plt import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') q = QuantumRegister(1) qc = QuantumCircuit(q) qc.u(pi/2,pi/4,pi/8,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.p(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.id(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.x(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.y(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.z(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.h(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.s(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.sdg(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.t(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.tdg(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rx(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ry(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rz(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cx(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cy(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cz(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ch(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.crz(pi/2,q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cp(pi/2,q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cu(pi/2, pi/2, pi/2, 0, q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.swap(q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.ccx(q[0], q[1], q[2]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cswap(q[0], q[1], q[2]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.measure(q, c) qc.draw() backend = BasicAer.get_backend('qasm_simulator') job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q,c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) # Initializing a three-qubit quantum state import math 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] q = QuantumRegister(3) qc = QuantumCircuit(q) qc.initialize(desired_vector, [q[0],q[1],q[2]]) qc.draw() backend = BasicAer.get_backend('statevector_simulator') job = backend.run(transpile(qc, backend)) qc_state = job.result().get_statevector(qc) qc_state state_fidelity(desired_vector,qc_state) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit import register #import Qconfig and set APIToken and API url import sys, getpass try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} print('Qconfig loaded from %s.' % Qconfig.__file__) except: APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url":"https://quantumexperience.ng.bluemix.net/api"} print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.') register(qx_config['APItoken'], qx_config['url']) from battleships_engine import * title_screen() device = ask_for_device() from qiskit import get_backend backend = get_backend(device) shipPos = ask_for_ships() # the game variable will be set to False once the game is over game = True # the variable bombs[X][Y] will hold the number of times position Y has been bombed by player X+1 bomb = [ [0]*5 for _ in range(2)] # all values are initialized to zero # set the number of samples used for statistics shots = 1024 # the variable grid[player] will hold the results for the grid of each player grid = [{},{}] while (game): # ask both players where they want to bomb, and update the list of bombings so far bomb = ask_for_bombs( bomb ) # now we create and run the quantum programs that implement this on the grid for each player qc = [] for player in range(2): # now to set up the quantum program to simulate the grid for this player # set up registers and program q = QuantumRegister(5) c = ClassicalRegister(5) qc.append( QuantumCircuit(q, c) ) # add the bombs (of the opposing player) for position in range(5): # add as many bombs as have been placed at this position for n in range( bomb[(player+1)%2][position] ): # the effectiveness of the bomb # (which means the quantum operation we apply) # depends on which ship it is for ship in [0,1,2]: if ( position == shipPos[player][ship] ): frac = 1/(ship+1) # add this fraction of a NOT to the QASM qc[player].u3(frac * math.pi, 0.0, 0.0, q[position]) # Finally, measure them for position in range(5): qc[player].measure(q[position], c[position]) # compile and run the quantum program job = execute(qc, backend, shots=shots) if device=='ibmqx4': print("\nWe've now get submitted the job to the quantum computer to see what happens to the ships of each player\n(it might take a while).\n") else: print("\nWe've now get submitted the job to the simulator to see what happens to the ships of each player.\n") # and extract data for player in range(2): grid[player] = job.result().get_counts(qc[player]) game = display_grid ( grid, shipPos, shots )
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
from qiskit_chemistry import FermionicOperator, QMolecule from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD from qiskit_aqua.components.optimizers import COBYLA from qiskit_aqua import Operator from qiskit_aqua.algorithms import VQE, ExactEigensolver from qiskit import Aer from scipy import linalg as la import numpy as np import yaml as yml from yaml import SafeLoader as Loader import os from qiskit.tools.parallel import parallel_map from qiskit.tools.events import TextProgressBar import Load_Hamiltonians as lh #Define functions that can be used in parallel algorithm def read_variables(root_dir, file1): #print('Root directory\n',root_dir) #print('The file: \n', file1) Ham_data_file = str(os.path.join(root_dir, file1)) try: doc_nw = open(Ham_data_file, 'r') dat = yml.load(doc_nw, Loader) finally: doc_nw.close() # Import all the data from a yaml file print('Getting data') #Importing the integrals one_e = dat['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values'] two_e = dat['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values'] num_spatial_orbitals = dat['integral_sets'][0]['n_orbitals'] coulomb_energy = dat['integral_sets'][0]['coulomb_repulsion']['value'] num_orbitals = 2 * num_spatial_orbitals num_particles = dat['integral_sets'][0]['n_electrons'] d = 2 * dat['integral_sets'][0]['geometry']['atoms'][1]['coords'][2] print('Bond distance is {}'.format(d)) if map_type == 'parity': # For two-qubit reduction num_qubits = num_orbitals - 2 else: num_qubits = num_orbitals return num_spatial_orbitals, num_orbitals, num_particles, num_qubits, d, coulomb_energy, one_e, two_e def get_molecular_qubit_operator(one_ints, two_ints, n_orbitals, thresh, qubit_map): # Getting spatial integrals and spin integrals to construct Hamiltonian one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_ints, two_ints, n_orbitals) h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals, two_electron_spatial_integrals, n_orbitals, thresh) # Constructing the fermion operator and qubit operator from integrals data fop = FermionicOperator(h1, h2) qop_paulis = fop.mapping(qubit_map, num_workers=1) return qop_paulis def run_vqe(pauli_operator, num_orbitals, num_particles, num_qubits, coulomb_energy, mapping, backend): var_energy = 0 #Get Variational form and intial state initial_state = HartreeFock(num_qubits, num_orbitals, num_particles, mapping, two_qubit_reduction=False) var_op = UCCSD(num_qubits, 1, num_orbitals, num_particles, active_occupied=None, active_unoccupied=None, initial_state=initial_state, qubit_mapping=mapping) ######################## VQE RESULT ############################### # setup a classical optimizer for VQE max_eval = 200 optimizer = COBYLA(maxiter=max_eval, disp=True, tol=1e-3) print('Doing VQE') algorithm = VQE(pauli_operator, var_op, optimizer,'paulis', initial_point=None, ) result = algorithm.run(backend) var_energy = result['energy'] + coulomb_energy # vqe_params = result['opt_params'] return var_energy def run_exact(pauli_operator, coulomb_energy): exact_eigensolver = ExactEigensolver(pauli_operator, k=1) ret = exact_eigensolver.run() print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real)) print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + coulomb_energy)) ed_energy = ret['eigvals'][0].real + coulomb_energy return ed_energy def final(file, root_directory, backend): # print('Starting Loop') spatial_orbitals, spin_orbitals, particle_num, qubits_num, dist, nuclear_energy, one_electron_import, two_electron_import = read_variables(root_directory, file) # print('Have variables') qop = get_molecular_qubit_operator(one_electron_import, two_electron_import, spatial_orbitals, truncation_threshold, map_type) # print('Have qubit operator') # vqe_energy = run_vqe(qop, spin_orbitals, particle_num, qubits_num, nuclear_energy, map_type, backend) vqe_energy = 0 exact_energy = run_exact(qop, nuclear_energy) # print('Obtained the energy') my_info = [dist, exact_energy, vqe_energy] # print('info: ',my_info) return my_info ##Carefully upgrade terra to see if qasm/state-vector simulator perform quicker.## #################### WALK ROOT DIR ############################ #U root_dir = '/Users/mmetcalf/Dropbox/Quantum Embedding/Codes/Lithium_Downfolding/Qiskit Chem/HamiltonianDownfolding_w_IBM/IntegralData/vqe-data-master/Li2_cc-pVTZ/4_ORBITALS/' data_file_list = [] for dirName, subdirList, fileList in os.walk(root_dir): print('Found directory: %s' % dirName) for fname in sorted(fileList): if fname.endswith('.yaml'): data_file_list.append(fname) ############# Output Files to Plot stuff ############### # print(data_file_list) Fout = open('Mekena_OutputData.dat',"w") ########################################################### #Variables that can be assigned outside of Loop map_type = str('jordan_wigner') truncation_threshold = 0.01 ################# IBM BACKEND ##################### backend1 = Aer.get_backend('statevector_simulator') ################################################### result = parallel_map(final, data_file_list, task_args=(root_dir, backend1)) print(result) # print(output_data) Fout.close()
https://github.com/JavaFXpert/llm-grovers-search-party
JavaFXpert
import os os.environ["OPENAI_API_KEY"] = "" !pip install langchain !pip install langchain[llms] !pip install openai from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.chains import LLMChain llm = OpenAI(temperature=0.0) template = """Create a boolean expression that expresses the following situation: Situation: Alice and Bob are in a relationship, as are Carol and David. However, Alice and David had a bad breakup a while ago and haven't been civil with each other since. Expression: ((Alice & Bob) | (Carol & David)) & ~(Alice and David) Situation: {situation} Expression:""" prompt_template = PromptTemplate( input_variables=["situation"], template=template, ) chain = LLMChain(llm=llm, prompt=prompt_template) from qiskit.algorithms import AmplificationProblem, Grover from qiskit.circuit.library import PhaseOracle from qiskit import Aer from qiskit.visualization import plot_histogram situation = """There are four people, Abe, Amira, Jin, Olivia. Abe and Olivia are good friends from Qiskit Camp. Abe and Amira just had a big fight and don't want to hang""" bool_expr = chain.run(situation).strip() print(bool_expr) oracle = PhaseOracle(bool_expr) problem = AmplificationProblem(oracle) backend = Aer.get_backend("aer_simulator") grover = Grover(quantum_instance=backend) result = grover.amplify(problem) counts = result.circuit_results plot_histogram(counts)