repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/googlercolin/Qiskit-Course
|
googlercolin
|
import numpy as np
import torch
from torchvision.transforms import ToTensor
from torch import no_grad
from torchvision import datasets
import torch.optim as optim
from torch.nn import (Module, Conv2d, Linear, Dropout2d, NLLLoss, MaxPool2d, Flatten, Sequential, ReLU)
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from qiskit import *
from qiskit import transpile, assemble, IBMQ
from qiskit.visualization import *
from qiskit import Aer, QuantumCircuit
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.opflow import AerPauliExpectation
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit.circuit import ParameterVector
from qiskit_machine_learning.neural_networks import CircuitQNN, TwoLayerQNN
from qiskit_machine_learning.connectors import TorchConnector
import qiskit.providers.fake_provider as fake
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer import AerSimulator, QasmSimulator
import matplotlib.pyplot as plt
provider = IBMQ.load_account()
# Declare Quantum instance
noisy_backend = provider.get_backend('ibmq_manila')
backend_sim = AerSimulator.from_backend(noisy_backend)
qi = QuantumInstance(backend_sim)
print(backend_sim)
### Training and test data downloaded from FashionMNIST and transformed into tensors ###
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor()
)
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor()
)
### Inspecting the images in the training data set with their labels ###
labels_map = {
0: "T-Shirt",
1: "Trouser",
2: "Pullover",
3: "Dress",
4: "Coat",
5: "Sandal",
6: "Shirt",
7: "Sneaker",
8: "Bag",
9: "Ankle Boot",
}
figure = plt.figure(figsize=(8, 8))
cols, rows = 3, 3
for i in range(1, cols * rows + 1):
sample_idx = torch.randint(len(training_data), size=(1,)).item()
img, label = training_data[sample_idx]
figure.add_subplot(rows, cols, i)
plt.title(labels_map[label])
plt.axis("off")
plt.imshow(img.squeeze(), cmap="gray")
plt.show()
### Load training data into Torch DataLoader ###
X_train = training_data
n_samples = 500
batch_size = 64
# Filter out labels (originally 0-9), leaving only labels 0 and 1
idx = np.append(np.where(X_train.targets == 0)[0][:n_samples],
np.where(X_train.targets == 1)[0][:n_samples])
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
# A torch dataloader is defined with filtered data
train_loader = DataLoader(X_train, batch_size=64, shuffle=True)
# Load test data into Torch DataLoader
X_test = test_data
# Filter out labels (originally 0-9), leaving only labels 0 and 1
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
# Define torch dataloader with filtered data
test_loader = DataLoader(X_test, batch_size=64, shuffle=True)
pi = np.pi
feature_dim = 2
reps = 2
duplicates = 3 # only use odd integers here
feature_map_circuit = QuantumCircuit(feature_dim, name=f'feature_map_circuit, duplicates = {duplicates}')
x = ParameterVector('x', feature_dim * reps)
for i in range(reps):
for j in range(feature_dim):
for k in range(duplicates):
feature_map_circuit.h(j)
for m in range(duplicates):
feature_map_circuit.p(2.0*x[0], 0)
feature_map_circuit.p(2.0*x[1], 1)
for m in range(duplicates):
feature_map_circuit.cnot(0, 1)
for m in range(duplicates):
feature_map_circuit.p(2.0*(pi - x[0])*(pi - x[1]), 1)
for m in range(duplicates):
feature_map_circuit.cnot(0, 1)
feature_map_circuit.draw()
num_qubits = 2
ansatz_circuit = QuantumCircuit(num_qubits, name=f'ansatz_circuit, duplicates = {duplicates}')
reps = 1
params = ParameterVector('θ', num_qubits + num_qubits * reps)
counter = 0
for i in range(num_qubits):
for n in range(duplicates):
ansatz_circuit.ry(params[counter], i)
counter += 1
for j in range(reps):
for k in range(num_qubits-1):
for n in range(duplicates):
ansatz_circuit.cnot(k, k+1)
for m in range(num_qubits):
for n in range(duplicates):
ansatz_circuit.ry(params[counter], m)
counter += 1
ansatz_circuit.draw()
qnn2 = TwoLayerQNN(2, feature_map_circuit, ansatz_circuit, input_gradients=True,
exp_val=AerPauliExpectation(), quantum_instance=qi)
print(qnn2.operator)
### Torch NN module from Qiskit ###
class Net(Module):
def __init__(self):
super().__init__()
self.conv1 = Conv2d(1, 2, kernel_size=5)
self.conv2 = Conv2d(2, 16, kernel_size=5)
self.dropout = Dropout2d()
self.fc1 = Linear(256, 64)
self.fc2 = Linear(64, 2) # 2-dimensional input to QNN
# Apply torch connector, weights chosen
self.qnn = TorchConnector(qnn2)
# uniformly at random from interval [-1,1].
self.fc3 = Linear(1, 1)
# 1-dimensional output from QNN
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.qnn(x) # apply QNN
x = self.fc3(x)
return torch.cat((x, 1 - x), -1)
### Model trained and the loss computed ###
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
### Loss convergence plotted ###
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg. Log Likelihood Loss')
plt.show()
torch.save(model.state_dict(
), 'Models/d3ZZ_d3RealAmp.pth')
### Model evaluated ###
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
(correct / len(test_loader) / batch_size) * 100))
### Predicted images displayed. Either T-shirt or Trouser ###
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(15, 5))
model.eval()
with no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model(data[0:1])
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
if pred.item() == 0:
axes[count].set_title('Predicted item: T-Shirt')
elif pred.item() == 1:
axes[count].set_title('Predicted item: Trouser')
count += 1
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/orpgol/quantum_algorithms_qiskit
|
orpgol
|
import numpy as np
from qiskit import BasicAer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
from qiskit import IBMQ, assemble, transpile
from qiskit.tools.monitor import job_monitor
from qiskit.tools.monitor import job_monitor
import argparse, sys
import time
provider = IBMQ.load_account()
parser = argparse.ArgumentParser()
parser.add_argument('--s', help = 'Enter the secret string.')
class Bernstein_Vazirani(object):
def __init__(self, n, s):
self.n = n
self.s = s
def _run_bv(self):
bv_circuit = QuantumCircuit(self.n+1,self.n)
bv_circuit.h(self.n)
bv_circuit.barrier()
bv_circuit.z(self.n)
bv_circuit.barrier()
for i in range(self.n):
bv_circuit.h(i)
bv_circuit.barrier()
s = self.s[::-1]
for q in range(self.n):
if s[q] == '0':
bv_circuit.i(q)
else:
bv_circuit.cx(q, self.n)
bv_circuit.barrier()
for i in range(self.n):
bv_circuit.h(i)
bv_circuit.barrier()
for i in range(self.n):
bv_circuit.measure(i, i)
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= len(self.qubits) and not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
shots = 8000
job = execute(bv_circuit, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
try:
result = job.result()
except:
print(job.error_message())
return -1, -1
answer = result.get_counts(bv_circuit)
print(answer)
fi = plot_histogram(answer)
fi.savefig(fname = "bv_results4_8000.png")
print("--%s seconds--" % result.time_taken)
if __name__ == '__main__':
start_time = time.time()
args = parser.parse_args()
s = args.s
for i in s:
if i != '0' and i != '1':
raise AssertionError("s must be a bitstring")
n = len(s)
bv = Bernstein_Vazirani(n, s)
bv._run_bv()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Basic rescheduling functions which take schedule or instructions and return new schedules."""
import warnings
from collections import defaultdict
from typing import List, Optional, Iterable, Union, Type
import numpy as np
from qiskit.pulse import channels as chans, exceptions, instructions
from qiskit.pulse.channels import ClassicalIOChannel
from qiskit.pulse.exceptions import PulseError
from qiskit.pulse.exceptions import UnassignedDurationError
from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap
from qiskit.pulse.instructions import directives
from qiskit.pulse.schedule import Schedule, ScheduleBlock, ScheduleComponent
def block_to_schedule(block: ScheduleBlock) -> Schedule:
"""Convert ``ScheduleBlock`` to ``Schedule``.
Args:
block: A ``ScheduleBlock`` to convert.
Returns:
Scheduled pulse program.
Raises:
UnassignedDurationError: When any instruction duration is not assigned.
PulseError: When the alignment context duration is shorter than the schedule duration.
.. note:: This transform may insert barriers in between contexts.
"""
if not block.is_schedulable():
raise UnassignedDurationError(
"All instruction durations should be assigned before creating `Schedule`."
"Please check `.parameters` to find unassigned parameter objects."
)
schedule = Schedule.initialize_from(block)
for op_data in block.blocks:
if isinstance(op_data, ScheduleBlock):
context_schedule = block_to_schedule(op_data)
if hasattr(op_data.alignment_context, "duration"):
# context may have local scope duration, e.g. EquispacedAlignment for 1000 dt
post_buffer = op_data.alignment_context.duration - context_schedule.duration
if post_buffer < 0:
raise PulseError(
f"ScheduleBlock {op_data.name} has longer duration than "
"the specified context duration "
f"{context_schedule.duration} > {op_data.duration}."
)
else:
post_buffer = 0
schedule.append(context_schedule, inplace=True)
# prevent interruption by following instructions.
# padding with delay instructions is no longer necessary, thanks to alignment context.
if post_buffer > 0:
context_boundary = instructions.RelativeBarrier(*op_data.channels)
schedule.append(context_boundary.shift(post_buffer), inplace=True)
else:
schedule.append(op_data, inplace=True)
# transform with defined policy
return block.alignment_context.align(schedule)
def compress_pulses(schedules: List[Schedule]) -> List[Schedule]:
"""Optimization pass to replace identical pulses.
Args:
schedules: Schedules to compress.
Returns:
Compressed schedules.
"""
existing_pulses = []
new_schedules = []
for schedule in schedules:
new_schedule = Schedule.initialize_from(schedule)
for time, inst in schedule.instructions:
if isinstance(inst, instructions.Play):
if inst.pulse in existing_pulses:
idx = existing_pulses.index(inst.pulse)
identical_pulse = existing_pulses[idx]
new_schedule.insert(
time,
instructions.Play(identical_pulse, inst.channel, inst.name),
inplace=True,
)
else:
existing_pulses.append(inst.pulse)
new_schedule.insert(time, inst, inplace=True)
else:
new_schedule.insert(time, inst, inplace=True)
new_schedules.append(new_schedule)
return new_schedules
def flatten(program: Schedule) -> Schedule:
"""Flatten (inline) any called nodes into a Schedule tree with no nested children.
Args:
program: Pulse program to remove nested structure.
Returns:
Flatten pulse program.
Raises:
PulseError: When invalid data format is given.
"""
if isinstance(program, Schedule):
flat_sched = Schedule.initialize_from(program)
for time, inst in program.instructions:
flat_sched.insert(time, inst, inplace=True)
return flat_sched
else:
raise PulseError(f"Invalid input program {program.__class__.__name__} is specified.")
def inline_subroutines(program: Union[Schedule, ScheduleBlock]) -> Union[Schedule, ScheduleBlock]:
"""Recursively remove call instructions and inline the respective subroutine instructions.
Assigned parameter values, which are stored in the parameter table, are also applied.
The subroutine is copied before the parameter assignment to avoid mutation problem.
Args:
program: A program which may contain the subroutine, i.e. ``Call`` instruction.
Returns:
A schedule without subroutine.
Raises:
PulseError: When input program is not valid data format.
"""
if isinstance(program, Schedule):
return _inline_schedule(program)
elif isinstance(program, ScheduleBlock):
return _inline_block(program)
else:
raise PulseError(f"Invalid program {program.__class__.__name__} is specified.")
def _inline_schedule(schedule: Schedule) -> Schedule:
"""A helper function to inline subroutine of schedule.
.. note:: If subroutine is ``ScheduleBlock`` it is converted into Schedule to get ``t0``.
"""
ret_schedule = Schedule.initialize_from(schedule)
for t0, inst in schedule.children:
# note that schedule.instructions unintentionally flatten the nested schedule.
# this should be performed by another transformer node.
if isinstance(inst, instructions.Call):
# bind parameter
subroutine = inst.assigned_subroutine()
# convert into schedule if block is given
if isinstance(subroutine, ScheduleBlock):
subroutine = block_to_schedule(subroutine)
# recursively inline the program
inline_schedule = _inline_schedule(subroutine)
ret_schedule.insert(t0, inline_schedule, inplace=True)
elif isinstance(inst, Schedule):
# recursively inline the program
inline_schedule = _inline_schedule(inst)
ret_schedule.insert(t0, inline_schedule, inplace=True)
else:
ret_schedule.insert(t0, inst, inplace=True)
return ret_schedule
def _inline_block(block: ScheduleBlock) -> ScheduleBlock:
"""A helper function to inline subroutine of schedule block.
.. note:: If subroutine is ``Schedule`` the function raises an error.
"""
ret_block = ScheduleBlock.initialize_from(block)
for inst in block.blocks:
if isinstance(inst, instructions.Call):
# bind parameter
subroutine = inst.assigned_subroutine()
if isinstance(subroutine, Schedule):
raise PulseError(
f"A subroutine {subroutine.name} is a pulse Schedule. "
"This program cannot be inserted into ScheduleBlock because "
"t0 associated with instruction will be lost."
)
# recursively inline the program
inline_block = _inline_block(subroutine)
ret_block.append(inline_block, inplace=True)
elif isinstance(inst, ScheduleBlock):
# recursively inline the program
inline_block = _inline_block(inst)
ret_block.append(inline_block, inplace=True)
else:
ret_block.append(inst, inplace=True)
return ret_block
def remove_directives(schedule: Schedule) -> Schedule:
"""Remove directives.
Args:
schedule: A schedule to remove compiler directives.
Returns:
A schedule without directives.
"""
return schedule.exclude(instruction_types=[directives.Directive])
def remove_trivial_barriers(schedule: Schedule) -> Schedule:
"""Remove trivial barriers with 0 or 1 channels.
Args:
schedule: A schedule to remove trivial barriers.
Returns:
schedule: A schedule without trivial barriers
"""
def filter_func(inst):
return isinstance(inst[1], directives.RelativeBarrier) and len(inst[1].channels) < 2
return schedule.exclude(filter_func)
def align_measures(
schedules: Iterable[ScheduleComponent],
inst_map: Optional[InstructionScheduleMap] = None,
cal_gate: str = "u3",
max_calibration_duration: Optional[int] = None,
align_time: Optional[int] = None,
align_all: Optional[bool] = True,
) -> List[Schedule]:
"""Return new schedules where measurements occur at the same physical time.
This transformation will align the first :class:`.Acquire` on
every channel to occur at the same time.
Minimum measurement wait time (to allow for calibration pulses) is enforced
and may be set with ``max_calibration_duration``.
By default only instructions containing a :class:`.AcquireChannel` or :class:`.MeasureChannel`
will be shifted. If you wish to keep the relative timing of all instructions in the schedule set
``align_all=True``.
This method assumes that ``MeasureChannel(i)`` and ``AcquireChannel(i)``
correspond to the same qubit and the acquire/play instructions
should be shifted together on these channels.
.. code-block::
from qiskit import pulse
from qiskit.pulse import transforms
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
a0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
sched = pulse.Schedule()
sched.append(pulse.Play(pulse.Constant(10, 0.5), d0), inplace=True)
sched.append(pulse.Play(pulse.Constant(10, 1.), m0).shift(sched.duration), inplace=True)
sched.append(pulse.Acquire(20, a0, mem0).shift(sched.duration), inplace=True)
sched_shifted = sched << 20
aligned_sched, aligned_sched_shifted = transforms.align_measures([sched, sched_shifted])
assert aligned_sched == aligned_sched_shifted
If it is desired to only shift acquisition and measurement stimulus instructions
set the flag ``align_all=False``:
.. code-block::
aligned_sched, aligned_sched_shifted = transforms.align_measures(
[sched, sched_shifted],
align_all=False,
)
assert aligned_sched != aligned_sched_shifted
Args:
schedules: Collection of schedules to be aligned together
inst_map: Mapping of circuit operations to pulse schedules
cal_gate: The name of the gate to inspect for the calibration time
max_calibration_duration: If provided, inst_map and cal_gate will be ignored
align_time: If provided, this will be used as final align time.
align_all: Shift all instructions in the schedule such that they maintain
their relative alignment with the shifted acquisition instruction.
If ``False`` only the acquisition and measurement pulse instructions
will be shifted.
Returns:
The input list of schedules transformed to have their measurements aligned.
Raises:
PulseError: If the provided alignment time is negative.
"""
def get_first_acquire_times(schedules):
"""Return a list of first acquire times for each schedule."""
acquire_times = []
for schedule in schedules:
visited_channels = set()
qubit_first_acquire_times = defaultdict(lambda: None)
for time, inst in schedule.instructions:
if isinstance(inst, instructions.Acquire) and inst.channel not in visited_channels:
visited_channels.add(inst.channel)
qubit_first_acquire_times[inst.channel.index] = time
acquire_times.append(qubit_first_acquire_times)
return acquire_times
def get_max_calibration_duration(inst_map, cal_gate):
"""Return the time needed to allow for readout discrimination calibration pulses."""
# TODO (qiskit-terra #5472): fix behavior of this.
max_calibration_duration = 0
for qubits in inst_map.qubits_with_instruction(cal_gate):
cmd = inst_map.get(cal_gate, qubits, np.pi, 0, np.pi)
max_calibration_duration = max(cmd.duration, max_calibration_duration)
return max_calibration_duration
if align_time is not None and align_time < 0:
raise exceptions.PulseError("Align time cannot be negative.")
first_acquire_times = get_first_acquire_times(schedules)
# Extract the maximum acquire in every schedule across all acquires in the schedule.
# If there are no acquires in the schedule default to 0.
max_acquire_times = [max(0, *times.values()) for times in first_acquire_times]
if align_time is None:
if max_calibration_duration is None:
if inst_map:
max_calibration_duration = get_max_calibration_duration(inst_map, cal_gate)
else:
max_calibration_duration = 0
align_time = max(max_calibration_duration, *max_acquire_times)
# Shift acquires according to the new scheduled time
new_schedules = []
for sched_idx, schedule in enumerate(schedules):
new_schedule = Schedule.initialize_from(schedule)
stop_time = schedule.stop_time
if align_all:
if first_acquire_times[sched_idx]:
shift = align_time - max_acquire_times[sched_idx]
else:
shift = align_time - stop_time
else:
shift = 0
for time, inst in schedule.instructions:
measurement_channels = {
chan.index
for chan in inst.channels
if isinstance(chan, (chans.MeasureChannel, chans.AcquireChannel))
}
if measurement_channels:
sched_first_acquire_times = first_acquire_times[sched_idx]
max_start_time = max(
sched_first_acquire_times[chan]
for chan in measurement_channels
if chan in sched_first_acquire_times
)
shift = align_time - max_start_time
if shift < 0:
warnings.warn(
"The provided alignment time is scheduling an acquire instruction "
"earlier than it was scheduled for in the original Schedule. "
"This may result in an instruction being scheduled before t=0 and "
"an error being raised."
)
new_schedule.insert(time + shift, inst, inplace=True)
new_schedules.append(new_schedule)
return new_schedules
def add_implicit_acquires(schedule: ScheduleComponent, meas_map: List[List[int]]) -> Schedule:
"""Return a new schedule with implicit acquires from the measurement mapping replaced by
explicit ones.
.. warning:: Since new acquires are being added, Memory Slots will be set to match the
qubit index. This may overwrite your specification.
Args:
schedule: Schedule to be aligned.
meas_map: List of lists of qubits that are measured together.
Returns:
A ``Schedule`` with the additional acquisition instructions.
"""
new_schedule = Schedule.initialize_from(schedule)
acquire_map = {}
for time, inst in schedule.instructions:
if isinstance(inst, instructions.Acquire):
if inst.mem_slot and inst.mem_slot.index != inst.channel.index:
warnings.warn(
"One of your acquires was mapped to a memory slot which didn't match"
" the qubit index. I'm relabeling them to match."
)
# Get the label of all qubits that are measured with the qubit(s) in this instruction
all_qubits = []
for sublist in meas_map:
if inst.channel.index in sublist:
all_qubits.extend(sublist)
# Replace the old acquire instruction by a new one explicitly acquiring all qubits in
# the measurement group.
for i in all_qubits:
explicit_inst = instructions.Acquire(
inst.duration,
chans.AcquireChannel(i),
mem_slot=chans.MemorySlot(i),
kernel=inst.kernel,
discriminator=inst.discriminator,
)
if time not in acquire_map:
new_schedule.insert(time, explicit_inst, inplace=True)
acquire_map = {time: {i}}
elif i not in acquire_map[time]:
new_schedule.insert(time, explicit_inst, inplace=True)
acquire_map[time].add(i)
else:
new_schedule.insert(time, inst, inplace=True)
return new_schedule
def pad(
schedule: Schedule,
channels: Optional[Iterable[chans.Channel]] = None,
until: Optional[int] = None,
inplace: bool = False,
pad_with: Optional[Type[instructions.Instruction]] = None,
) -> Schedule:
"""Pad the input Schedule with ``Delay``s on all unoccupied timeslots until
``schedule.duration`` or ``until`` if not ``None``.
Args:
schedule: Schedule to pad.
channels: Channels to pad. Defaults to all channels in
``schedule`` if not provided. If the supplied channel is not a member
of ``schedule`` it will be added.
until: Time to pad until. Defaults to ``schedule.duration`` if not provided.
inplace: Pad this schedule by mutating rather than returning a new schedule.
pad_with: Pulse ``Instruction`` subclass to be used for padding.
Default to :class:`~qiskit.pulse.instructions.Delay` instruction.
Returns:
The padded schedule.
Raises:
PulseError: When non pulse instruction is set to `pad_with`.
"""
until = until or schedule.duration
channels = channels or schedule.channels
if pad_with:
if issubclass(pad_with, instructions.Instruction):
pad_cls = pad_with
else:
raise PulseError(
f"'{pad_with.__class__.__name__}' is not valid pulse instruction to pad with."
)
else:
pad_cls = instructions.Delay
for channel in channels:
if isinstance(channel, ClassicalIOChannel):
continue
if channel not in schedule.channels:
schedule = schedule.insert(0, instructions.Delay(until, channel), inplace=inplace)
continue
prev_time = 0
timeslots = iter(schedule.timeslots[channel])
to_pad = []
while prev_time < until:
try:
t0, t1 = next(timeslots)
except StopIteration:
to_pad.append((prev_time, until - prev_time))
break
if prev_time < t0:
to_pad.append((prev_time, min(t0, until) - prev_time))
prev_time = t1
for t0, duration in to_pad:
schedule = schedule.insert(t0, pad_cls(duration, channel), inplace=inplace)
return schedule
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test library of weighted adder circuits."""
import unittest
from collections import defaultdict
from ddt import ddt, data
import numpy as np
from qiskit.test.base import QiskitTestCase
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import WeightedAdder
@ddt
class TestWeightedAdder(QiskitTestCase):
"""Test the weighted adder circuit."""
def assertSummationIsCorrect(self, adder):
"""Assert that ``adder`` correctly implements the summation w.r.t. its set weights."""
circuit = QuantumCircuit(adder.num_qubits)
circuit.h(list(range(adder.num_state_qubits)))
circuit.append(adder.to_instruction(), list(range(adder.num_qubits)))
backend = BasicAer.get_backend("statevector_simulator")
statevector = execute(circuit, backend).result().get_statevector()
probabilities = defaultdict(float)
for i, statevector_amplitude in enumerate(statevector):
i = bin(i)[2:].zfill(circuit.num_qubits)[adder.num_ancillas :]
probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2)
expectations = defaultdict(float)
for x in range(2**adder.num_state_qubits):
bits = np.array(list(bin(x)[2:].zfill(adder.num_state_qubits)), dtype=int)
summation = bits.dot(adder.weights[::-1])
entry = bin(summation)[2:].zfill(adder.num_sum_qubits) + bin(x)[2:].zfill(
adder.num_state_qubits
)
expectations[entry] = 1 / 2**adder.num_state_qubits
for state, probability in probabilities.items():
self.assertAlmostEqual(probability, expectations[state])
@data([0], [1, 2, 1], [4], [1, 2, 1, 1, 4])
def test_summation(self, weights):
"""Test the weighted adder on some examples."""
adder = WeightedAdder(len(weights), weights)
self.assertSummationIsCorrect(adder)
def test_mutability(self):
"""Test the mutability of the weighted adder."""
adder = WeightedAdder()
with self.subTest(msg="missing number of state qubits"):
with self.assertRaises(AttributeError):
print(adder.draw())
with self.subTest(msg="default weights"):
adder.num_state_qubits = 3
default_weights = 3 * [1]
self.assertListEqual(adder.weights, default_weights)
with self.subTest(msg="specify weights"):
adder.weights = [3, 2, 1]
self.assertSummationIsCorrect(adder)
with self.subTest(msg="mismatching number of state qubits and weights"):
with self.assertRaises(ValueError):
adder.weights = [0, 1, 2, 3]
print(adder.draw())
with self.subTest(msg="change all attributes"):
adder.num_state_qubits = 4
adder.weights = [2, 0, 1, 1]
self.assertSummationIsCorrect(adder)
if __name__ == "__main__":
unittest.main()
|
https://github.com/WhenTheyCry96/qiskitHackathon2022
|
WhenTheyCry96
|
import warnings
warnings.filterwarnings('ignore')
from qiskit_metal import designs, MetalGUI
design = designs.DesignPlanar()
design.overwrite_enabled = True
design.chips.main.size_x = '12mm'
design.chips.main.size_y = '10mm'
gui = MetalGUI(design)
from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL
design.delete_all_components()
design_span_x = 5
design_span_y = 3
half_chip_width = design_span_x / 2
half_chip_height = design_span_y / 2
connection_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
b = dict(loc_W=1, loc_H=1),
c = dict(loc_W=-1, loc_H=-1)
)
connection23_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
c = dict(loc_W=-1, loc_H=-1)
)
transmons = []
transmons.append(TransmonPocketCL(design, 'Q1',
options=dict(pos_x=f'-{half_chip_width}mm',
pos_y=f'{-half_chip_height}mm',
connection_pads=dict(**connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q2',
options=dict(pos_x=f'0mm',
pos_y=f'{half_chip_height}mm',
orientation=-90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q3',
options=dict(pos_x=f'0mm',
pos_y=f'{-half_chip_height}mm',
orientation=90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q4',
options=dict(pos_x=f'{half_chip_width}mm',
pos_y=f'{half_chip_height}mm',
orientation=180,
connection_pads=dict(**connection_pads_options))))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal import Dict
fillet='99.99um'
options = Dict(
meander=Dict(
lead_start='0.1mm',
lead_end='0.1mm',
asymmetry='0 um')
)
def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str,
length: str,
asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False):
"""Connect two pins with a CPW."""
myoptions = Dict(
pin_inputs=Dict(
start_pin=Dict(
component=component1,
pin=pin1),
end_pin=Dict(
component=component2,
pin=pin2)),
lead=Dict(
start_straight=start_strght,
end_straight=end_strght
),
total_length=length,
fillet = '99.9um')
myoptions.update(options)
myoptions.meander.asymmetry = asymmetry
myoptions.meander.lead_direction_inverted = 'true' if flip else 'false'
return RouteMeander(design, component_name, myoptions)
asym_h = 100
asym_v = 100
cpw = []
cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled
readouts_lwc = []
control_lwc = []
offset_x = 0
offset_y = 1
#Readouts
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1',
options = dict(
pos_x = '-5mm',
pos_y = f'-{half_chip_height+offset_y}mm',
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2',
options = dict(
pos_x = '-1mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3',
options = dict(
pos_x = '1mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4',
options = dict(
pos_x = '5mm',
pos_y = f'{half_chip_height+offset_y}mm',
orientation = 180,
lead_length = '30um')))
#Controls
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1',
options = dict(
pos_x = '-5mm',
pos_y = '2mm',
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2',
options = dict(
pos_x = '4mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3',
options = dict(
pos_x = '-4mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4',
options = dict(
pos_x = '5mm',
pos_y = '-2mm',
orientation = 180,
lead_length = '30um')))
gui.rebuild()
gui.autoscale()
readout_lines = []
asym_14 = 700
asym_23 = 700
options = Dict(
lead=Dict(
start_straight='330um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um'))
options = Dict(
lead=Dict(
start_straight='430um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors
from collections import OrderedDict
import numpy as np
control_lines = []
def connectRouteAnchor(name: str,
component1: str, pin1: str, component2: str, pin2: str,
anchor_points: OrderedDict) -> RouteAnchors:
options_line_cl = dict(
pin_inputs = dict(start_pin = dict(component = component1, pin = pin1),
end_pin = dict(component = component2, pin = pin2)),
anchors = anchor_points,
lead = dict(start_straight = '200um',
end_straight = '225um'),
fillet = fillet
)
return RouteAnchors(design, name, options_line_cl)
anchors1c = OrderedDict()
anchors1c[0] = np.array([-4, -1.42])
anchors1c[1] = np.array([-4, 2])
control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c))
anchors2c = OrderedDict()
anchors2c[0] = np.array([0.08, 3.25])
anchors2c[1] = np.array([4, 3.25])
control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c))
anchors3c = OrderedDict()
anchors3c[0] = np.array([-0.08, -3.25])
anchors3c[1] = np.array([-4, -3.25])
control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c))
anchors4c = OrderedDict()
anchors4c[0] = np.array([4, 1.42])
anchors4c[1] = np.array([4, -2])
control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c))
gui.rebuild()
gui.autoscale()
gui.autoscale()
gui.screenshot(name="full_design")
import numpy as np
from scipy.constants import c, h, pi, hbar, e
from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength
# constants:
phi0 = h/(2*e)
varphi0 = phi0/(2*pi)
# project target parameters
f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz
f_rList = f_qList + 1.8 # GHz
L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH
# initial CPW readout lengths
def find_resonator_length(frequency, line_width, line_gap, N):
#frequency in GHz
#line_width/line_gap in um
#N -> 2 for lambda/2, 4 for lambda/4
[lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6,
line_gap*10**-6, 750*10**-6, 200*10**-9)
return str(lambdaG/N*10**3)+" mm"
find_resonator_length(f_rList, 10, 6, 2)
find_resonator_length(np.around(np.linspace(8, 9.2, 4), 2), 10, 6, 2)
transmons[0].options.pad_gap = '40um'
transmons[0].options.pad_width = '550um' # 405
transmons[0].options.pad_height = '120um'
transmons[1].options.pad_gap = '40um'
transmons[1].options.pad_width = '540um' # 405
transmons[1].options.pad_height = '120um'
transmons[2].options.pad_gap = '40um'
transmons[2].options.pad_width = '530um' # 405
transmons[2].options.pad_height = '120um'
transmons[3].options.pad_gap = '40um'
transmons[3].options.pad_width = '520um' # 405
transmons[3].options.pad_height = '120um'
readout_lines[0].options.total_length = '8.63mm'
readout_lines[1].options.total_length = '8.42mm'
readout_lines[2].options.total_length = '8.24mm'
readout_lines[3].options.total_length = '8.06mm'
cpw[0].options.total_length = '7.6mm'
cpw[1].options.total_length = '7.2mm'
cpw[2].options.total_length = '6.9mm'
cpw[3].options.total_length = '6.6mm'
gui.rebuild()
gui.autoscale()
qcomps = design.components # short handle (alias)
qcomps['Q1'].options['hfss_inductance'] = 'Lj1'
qcomps['Q1'].options['hfss_capacitance'] = 'Cj1'
qcomps['Q2'].options['hfss_inductance'] = 'Lj2'
qcomps['Q2'].options['hfss_capacitance'] = 'Cj2'
qcomps['Q3'].options['hfss_inductance'] = 'Lj3'
qcomps['Q3'].options['hfss_capacitance'] = 'Cj3'
qcomps['Q4'].options['hfss_inductance'] = 'Lj4'
qcomps['Q4'].options['hfss_capacitance'] = 'Cj4'
from qiskit_metal.analyses.quantization import EPRanalysis, LOManalysis
c1 = LOManalysis(design, "q3d")
q3d1 = c1.sim.renderer
q3d1.start()
q3d1.activate_ansys_design("qubit_pad_w_550_520", 'capacitive')
q3d1.render_design([], [])
q3d1.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05)
q3d1.analyze_setup("Setup")
c1.sim.capacitance_matrix, c1.sim.units = q3d1.get_capacitance_matrix()
c1.sim.capacitance_all_passes, _ = q3d1.get_capacitance_all_passes()
c1.sim.capacitance_matrix
Out[14].to_csv("full_pad_width550_520_C.txt")
|
https://github.com/JanLahmann/RasQberry
|
JanLahmann
|
#!/usr/bin/env python
# coding: utf-8
# Credits: https://github.com/wmazin/Visualizing-Quantum-Computing-using-fractals
#############################################################
# Importing standard python libraries
from typing import Tuple, List
from math import pi
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from numpy import complex64, ndarray
import numpy as np
class QuantumFractalCircuit:
def __init__(self, number_of_qubits:int = 1, number_of_frames: int = 60) -> None:
self.n_qubits = number_of_qubits
self.n_frames = number_of_frames
# Create the circuit for which the gates will be applied
self.quantum_circuit = QuantumCircuit(number_of_qubits)
self.quantum_circuit.h(0)
# noinspection PyUnresolvedReferences
def get_quantum_circuit(self, frame_iteration:int = 0) -> Tuple[complex64, QuantumCircuit, ndarray[complex64]]:
# Create a fresh copy of the Quantum Circuit
quantum_circuit = self.quantum_circuit.copy()
# Calculate the rotation Phi and apply it to the local Quantum Circuit
phi_rotation = frame_iteration * 2 * pi / self.n_frames
quantum_circuit.rz(phi_rotation, 0)
# Simulate the Quantum Circuit and extract the statevector
statevector_array = Statevector(quantum_circuit)
statevector_idx_n = statevector_array.data.astype(complex64)
statevector_idx_0 = statevector_array.data[0].astype(complex64)
statevector_idx_1 = statevector_array.data[1].astype(complex64)
# Check statevector values and calculate a new statevector
if statevector_idx_1.real != 0 or statevector_idx_1.imag != 0:
statevector_new = statevector_idx_0 / statevector_idx_1
statevector_new = round(statevector_new.real, 2) + round(statevector_new.imag, 2) * 1j
else:
statevector_new = 0
return statevector_new.astype(complex64), quantum_circuit, statevector_idx_n
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Decorator for using with Qiskit unit tests."""
import functools
import os
import sys
import unittest
from .utils import Path
from .http_recorder import http_recorder
from .testing_options import get_test_options
def is_aer_provider_available():
"""Check if the C++ simulator can be instantiated.
Returns:
bool: True if simulator executable is available
"""
# TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC
if sys.platform == 'darwin':
return False
try:
import qiskit.providers.aer # pylint: disable=unused-import
except ImportError:
return False
return True
def requires_aer_provider(test_item):
"""Decorator that skips test if qiskit aer provider is not available
Args:
test_item (callable): function or class to be decorated.
Returns:
callable: the decorated function.
"""
reason = 'Aer provider not found, skipping test'
return unittest.skipIf(not is_aer_provider_available(), reason)(test_item)
def slow_test(func):
"""Decorator that signals that the test takes minutes to run.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(*args, **kwargs):
skip_slow = not TEST_OPTIONS['run_slow']
if skip_slow:
raise unittest.SkipTest('Skipping slow tests')
return func(*args, **kwargs)
return _wrapper
def _get_credentials(test_object, test_options):
"""Finds the credentials for a specific test and options.
Args:
test_object (QiskitTestCase): The test object asking for credentials
test_options (dict): Options after QISKIT_TESTS was parsed by
get_test_options.
Returns:
Credentials: set of credentials
Raises:
ImportError: if the
Exception: when the credential could not be set and they are needed
for that set of options
"""
try:
from qiskit.providers.ibmq.credentials import (Credentials,
discover_credentials)
except ImportError:
raise ImportError('qiskit-ibmq-provider could not be found, and is '
'required for mocking or executing online tests.')
dummy_credentials = Credentials(
'dummyapiusersloginWithTokenid01',
'https://quantumexperience.ng.bluemix.net/api')
if test_options['mock_online']:
return dummy_credentials
if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''):
# Special case: instead of using the standard credentials mechanism,
# load them from different environment variables. This assumes they
# will always be in place, as is used by the Travis setup.
return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL'))
else:
# Attempt to read the standard credentials.
discovered_credentials = discover_credentials()
if discovered_credentials:
# Decide which credentials to use for testing.
if len(discovered_credentials) > 1:
try:
# Attempt to use QE credentials.
return discovered_credentials[dummy_credentials.unique_id()]
except KeyError:
pass
# Use the first available credentials.
return list(discovered_credentials.values())[0]
# No user credentials were found.
if test_options['rec']:
raise Exception('Could not locate valid credentials. You need them for '
'recording tests against the remote API.')
test_object.log.warning('No user credentials were detected. '
'Running with mocked data.')
test_options['mock_online'] = True
return dummy_credentials
def requires_qe_access(func):
"""Decorator that signals that the test uses the online API:
It involves:
* determines if the test should be skipped by checking environment
variables.
* if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is
set, it reads the credentials from an alternative set of environment
variables.
* if the test is not skipped, it reads `qe_token` and `qe_url` from
`Qconfig.py`, environment variables or qiskitrc.
* if the test is not skipped, it appends `qe_token` and `qe_url` as
arguments to the test function.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if TEST_OPTIONS['skip_online']:
raise unittest.SkipTest('Skipping online tests')
credentials = _get_credentials(self, TEST_OPTIONS)
self.using_ibmq_credentials = credentials.is_ibmq()
kwargs.update({'qe_token': credentials.token,
'qe_url': credentials.url})
decorated_func = func
if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']:
# For recording or for replaying existing cassettes, the test
# should be decorated with @use_cassette.
vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none'
decorated_func = http_recorder(
vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func)
return decorated_func(self, *args, **kwargs)
return _wrapper
TEST_OPTIONS = get_test_options()
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
import scipy as sci
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(4,name='q')
H_qc = QuantumCircuit(q,name='qc')
H_qc.x(q[0])
H_qc.id(q[1])
H_qc.x(q[2])
print('_____Initial State_________')
oq.Wavefunction(H_qc)
H_qc.h(q[0])
H_qc.x(q[1])
H_qc.y(q[2])
H_qc.z(q[3])
print('\n_____Operator H + X + Y + Z_________')
oq.Wavefunction(H_qc)
H_qc.h(q[0])
H_qc.x(q[1])
H_qc.y(q[2])
H_qc.z(q[3])
print('\n_____Operator H + X + Y + Z_________')
oq.Wavefunction(H_qc);
q = QuantumRegister(1,name='q')
XZ_qc = QuantumCircuit(q,name='qc')
XZ_qc.id(q[0])
print('_____Initial State_________')
oq.Wavefunction(XZ_qc)
XZ_qc.x(q[0])
XZ_qc.z(q[0])
print('\n_____Operator XZ_________')
oq.Wavefunction(XZ_qc)
XZ_qc.x(q[0])
XZ_qc.z(q[0])
print('\n_____Operator XZ_________')
oq.Wavefunction(XZ_qc);
q = QuantumRegister(1,name='q')
XZ_qc = QuantumCircuit(q,name='qc')
XZ_qc.id(q[0])
print('_____Initial State_________')
oq.Wavefunction(XZ_qc)
XZ_qc.x(q[0])
XZ_qc.z(q[0])
print('\n_____Operator XZ_________')
oq.Wavefunction(XZ_qc)
XZ_qc.z(q[0])
XZ_qc.x(q[0])
print('\n_____Operator ZX_________')
oq.Wavefunction(XZ_qc);
q = QuantumRegister(2,name='q')
F_qc = QuantumCircuit(q,name='qc')
F_qc.x(q[0])
F_qc.h(q[0])
F_qc.x(q[1])
F_qc.h(q[1])
print('_____Initial State_________')
oq.Wavefunction(F_qc)
F_qc.h(q[0])
F_qc.cp(m.pi/2,q[1],q[0])
F_qc.h(q[1])
print('\n_____After QFT_________')
oq.Wavefunction(F_qc);
q = QuantumRegister(3,name='q')
F_qc = QuantumCircuit(q,name='qc')
F_qc.x(q[2])
print('_____Initial State_________')
oq.Wavefunction(F_qc)
#---------------------------- qubit 0
F_qc.h(q[0])
F_qc.cp(m.pi/2,q[1],q[0])
F_qc.cp(m.pi/4,q[2],q[0])
#---------------------------- qubit 1
F_qc.h(q[1])
F_qc.cp(m.pi/4,q[2],q[1])
#---------------------------- qubit 2
F_qc.h(q[2])
print('\n_____After QFT_________')
oq.Wavefunction(F_qc);
q = QuantumRegister(2,name='q')
F_qc = QuantumCircuit(q,name='qc')
F_qc.x(q[0])
F_qc.h(q[0])
F_qc.x(q[1])
F_qc.h(q[1])
print('_____Initial State_________')
oq.Wavefunction(F_qc)
oq.QFT(F_qc,q,2)
print('\n_____First QFT_________')
oq.Wavefunction(F_qc)
oq.QFT(F_qc,q,2)
print('\n_____Second QFT_________')
oq.Wavefunction(F_qc);
q = QuantumRegister(2,name='q')
F_qc = QuantumCircuit(q,name='qc')
F_qc.x(q[0])
F_qc.h(q[0])
F_qc.x(q[1])
F_qc.h(q[1])
print('_____Initial State_________')
oq.Wavefunction(F_qc)
print(' ')
F_qc.h(q[0])
F_qc.cp(m.pi/2,q[1],q[0])
F_qc.h(q[1])
print('_____QFT_________')
oq.Wavefunction(F_qc)
print(' ')
F_qc.h(q[1])
F_qc.cp(-m.pi/2,q[1],q[0])
F_qc.h(q[0])
print('_____Inverse QFT_________')
oq.Wavefunction(F_qc);
q = QuantumRegister(2,name='q')
F_qc = QuantumCircuit(q,name='qc')
F_qc.x(q[0])
F_qc.h(q[0])
F_qc.x(q[1])
F_qc.h(q[1])
print('_____Initial State_________')
oq.Wavefunction(F_qc)
oq.QFT(F_qc,q,2)
print('\n_____QFT_________')
oq.Wavefunction(F_qc)
oq.QFT_dgr(F_qc,q,2)
print('\n_____Inverse QFT_________')
oq.Wavefunction(F_qc);
X = [0,1/m.sqrt(8),0,0,0,0,0,0]
FX = oq.DFT(X, inverse = True)
print('______DFT\u2020_________')
for i in range(len(FX)):
print ('State: ',oq.Binary(i,2**3), ' Amplitude: ', FX[i])
#===================================================================
q = QuantumRegister(3, name='q')
qc = QuantumCircuit(q, name='qc')
qc.x(q[2])
oq.QFT(qc,q,3)
print('\n_____QFT________')
oq.Wavefunction(qc);
X = [0,1/m.sqrt(8),0,0,0,0,0,0]
FX = oq.DFT(X, inverse = True)
print('______DFT\u2020_________')
for i in range(len(FX)):
print ('State: ',oq.Binary(i,2**3), ' Amplitude: ', FX[i])
#===================================================================
q = QuantumRegister(3, name='q')
qc = QuantumCircuit(q, name='qc')
qc.x(q[2])
oq.QFT(qc,q,3)
qc.swap(q[0],q[2])
print('\n_____QFT________')
oq.Wavefunction(qc);
q = QuantumRegister(2, name='q')
anc = QuantumRegister(1, name='anc')
FG_qc = QuantumCircuit(q, anc, name='qc')
marked = [1,0]
FG_qc.x(anc[0])
print('marked state: ',marked)
print(' ')
oq.QFT(FG_qc,q,2)
print('_____Initial State (QFT)_________')
oq.Wavefunction(FG_qc, systems=[2,1], show_systems=[True,False])
print(' ')
oq.X_Transformation(FG_qc, q, marked)
FG_qc.h(anc[0])
FG_qc.ccx(q[0],q[1],anc[0])
oq.X_Transformation(FG_qc,q,marked)
FG_qc.h(anc[0])
print('__________Flip the marked state_____________')
oq.Wavefunction(FG_qc, systems=[2,1], show_systems=[True,False])
print(' ')
oq.QFT(FG_qc,q,2)
print('_____QFT_________')
oq.Wavefunction(FG_qc, systems=[2,1], show_systems=[True,False])
print(' ')
FG_qc.h(anc[0])
oq.X_Transformation(FG_qc, q, [0,0])
FG_qc.ccx(q[0],q[1],anc[0])
FG_qc.h(anc[0])
oq.X_Transformation(FG_qc,q,[0,0])
print('__________Flip the |00> state_____________')
oq.Wavefunction(FG_qc, systems=[2,1], show_systems=[True,False])
print(' ')
oq.QFT_dgr(FG_qc,q,2)
print('_____QFT_dgr_________')
oq.Wavefunction(FG_qc, systems=[2,1], show_systems=[True,False]);
X = [0,1/m.sqrt(8),0,0,0,0,0,0]
FX = oq.DFT(X, inverse = True)
print('______DFT\u2020_________')
for i in range(len(FX)):
print ('State: ',oq.Binary(i,2**3), ' Amplitude: ', FX[i])
#===================================================================
q = QuantumRegister(3, name='q')
qc = QuantumCircuit(q, name='qc')
qc.x(q[2])
oq.QFT(qc,q,3,swap=True)
print('\n_____QFT________')
oq.Wavefunction(qc);
qc.draw(output='mpl')
|
https://github.com/baronefr/perceptron-dqa
|
baronefr
|
import tensorflow as tf
import tensorflow.linalg as tfl
import numpy as np
import matplotlib.pyplot as plt
from tqdm.notebook import tqdm
physical_devices = tf.config.list_physical_devices('GPU')
print('GPU devices:', physical_devices)
if physical_devices:
for device in physical_devices:
tf.config.experimental.set_memory_growth(device, True)
sigma_x = tfl.LinearOperatorFullMatrix([[0., 1.], [1., 0.]])
sigma_z = tfl.LinearOperatorFullMatrix([[1., 0.], [0., -1.]])
id = tfl.LinearOperatorIdentity(2)
def H_perc(data, labels):
n_data, n = data.shape
# define a batch of ientities operators where batch is the #data
id_batch = tfl.LinearOperatorIdentity(2, batch_shape=[n_data])
# define a batch of sigma_z operators where batch is the #data
sigma_z_batch = tf.tile(tf.expand_dims(tf.constant([[1., 0.], [0., -1.]]), axis=0), [n_data, 1, 1])
sigma_z_op = tfl.LinearOperatorFullMatrix(sigma_z_batch)
# define a batch of data operators where batch is the #data.
# each coordinate of a single datum is casted into a 2x2 operator,
# which will be composed with the corresponding sigma_z operator
# result is a list of n [n_data, 2, 2] opearators
data_ops = [tfl.LinearOperatorDiag(tf.repeat(data, [2], axis=1)[:,i:i+2]) for i in range(0, n*2, 2)]
ops = [tfl.LinearOperatorKronecker([id_batch]*i+[tfl.LinearOperatorComposition([data_ops[i], sigma_z_op])]+[id_batch]*(n-i-1)).to_dense() for i in range(n)]
# opearotrs are first stacked on the n dimension and reduced, then labels are applied,
# then heaviside step function is applied (relu), and finally reduced over n_data
return tf.reduce_sum(tf.nn.relu(-tf.reshape(labels, (-1, 1, 1))*tf.reduce_sum(tf.stack(ops), axis=0)), axis=0)# / tf.sqrt(n+0.)
# reimplementation of the previous function with an eye over ram usage
def H_perc_nobatch(data, labels):
n_data, n = data.shape
h_perc = tf.zeros((2**n, 2**n), dtype='float32')
for i in tqdm(range(n_data), desc='Constructing H_perc'):
op = tf.zeros((2**n, 2**n), dtype='float32')
for j in range(n):
data_op = tfl.LinearOperatorDiag(tf.repeat(data[i, :], [2], axis=0)[2*j:2*(j+1)])
op += tfl.LinearOperatorKronecker([id]*j+[tfl.LinearOperatorComposition([data_op, sigma_z])]+[id]*(n-j-1)).to_dense()
del data_op
h_perc += tf.nn.relu(-labels[i]*op)
del op
return h_perc #/ tf.sqrt(n+0.)
def H_x(n):
sigma_xs = [tfl.LinearOperatorKronecker([id]*i+[sigma_x]+[id]*(n-i-1)).to_dense() for i in range(n)]
return -tf.reduce_sum(tf.stack(sigma_xs), axis=0)
def H_z(n):
sigma_zs = [tfl.LinearOperatorKronecker([id]*i+[sigma_z]+[id]*(n-i-1)).to_dense() for i in range(n)]
return tf.reduce_sum(tf.stack(sigma_zs), axis=0)
def H_QA(p, P, Hz, Hx):
frac = p/P
return tf.cast(frac*Hz + (1-frac)*Hx, dtype='complex128')
def init_state(n):
return tf.ones((2**n,), dtype='complex128')/tf.sqrt((2.**n+0.j))
data = tf.constant([[1., -1.], [-1., -1.]])
labels = tf.constant([1., -1.])
h_perc = H_perc(data, labels)
h_perc
n_data, n = data.shape
# define a batch of ientities operators where batch is the #data
id_batch = tfl.LinearOperatorIdentity(2, batch_shape=[n_data])
# define a batch of sigma_z operators where batch is the #data
sigma_z_batch = tf.tile(tf.expand_dims(tf.constant([[1., 0.], [0., -1.]]), axis=0), [n_data, 1, 1])
sigma_z_op = tfl.LinearOperatorFullMatrix(sigma_z_batch)
# define a batch of data operators where batch is the #data.
# each coordinate of a single datum is casted into a 2x2 operator,
# which will be composed with the corresponding sigma_z operator
# result is a list of n [n_data, 2, 2] opearators
data_ops = [tfl.LinearOperatorDiag(tf.repeat(data, [2], axis=1)[:,i:i+2]) for i in range(0, n*2, 2)]
ops = [tfl.LinearOperatorKronecker([id_batch]*i+[tfl.LinearOperatorComposition([data_ops[i], sigma_z_op])]+[id_batch]*(n-i-1)).to_dense() for i in range(n)]
tfl.LinearOperatorKronecker([tfl.LinearOperatorFullMatrix(np.array([[0., 0.], [0., 1.]], 'float32')), id]).to_dense()
tfl.LinearOperatorKronecker([id, tfl.LinearOperatorFullMatrix(np.array([[0., 0.], [0., 1.]], 'float32'))]).to_dense()
n = 10
hadamard = tfl.LinearOperatorFullMatrix(np.array([[1., 1.], [1., -1.]], 'float32') / np.sqrt(2.))
ops = [tfl.LinearOperatorKronecker([id]*i+[hadamard]+[id]*(n-i-1)).to_dense() for i in range(n)]
np.diag(tfl.LinearOperatorKronecker([sigma_z]*10).to_dense())[:4]
tf.reduce_sum(tf.stack(ops), axis=0)[:,0]
# define a batch of sigma_z operators where batch is the #data
sigma_z_batch = tf.tile(tf.expand_dims(tf.constant([[1., 0.], [0., -1.]]), axis=0), [n_data, 1, 1])
sigma_z_op = tfl.LinearOperatorFullMatrix(sigma_z_batch)
# define a batch of data operators where batch is the #data.
# each coordinate of a single datum is casted into a 2x2 operator,
# which will be composed with the corresponding sigma_z operator
# result is a list of n [n_data, 2, 2] opearators
data_ops = [tfl.LinearOperatorDiag(tf.repeat(data, [2], axis=1)[:,i:i+2]) for i in range(0, n*2, 2)]
ops = [tfl.LinearOperatorKronecker([id_batch]*i+[tfl.LinearOperatorComposition([data_ops[i], sigma_z_op])]+[id_batch]*(n-i-1)).to_dense() for i in range(n)]
H_perc_nobatch(data, labels)
tfl.eigh(h_perc)
h_x = H_x(10)
h_x = tf.cast(h_x, 'complex64')
eigvals, eigvecs = tfl.eigh(h_x)
tfl.matmul(eigvecs, tfl.matmul(tfl.diag(tf.exp(-1.j*eigvals)), eigvecs, adjoint_b=True), adjoint_a=False)
datum_ops = [tfl.LinearOperatorDiag(tf.repeat(data[0,:], [2], axis=0)[i:i+2]) for i in range(0, 2*2, 2)]
datum_ops[1].to_dense()
init_state(2)
h_t = H_QA(1, 1_000, h_perc, h_x)
h_t
def ed_qa_step(state, Ht, dt):
eigvals, eigvecs = tfl.eigh(Ht)
# define time evolution operator
U = tf.exp(-1.j*eigvals*dt)
# rewrite state in eigenvector basis, apply time evolution operator, project back to computational basis
evolved = tfl.matvec(eigvecs, U * tfl.matvec(eigvecs, state, adjoint_a=True))
return evolved
def create_dataset(N : int, features : int):
"""Create dataset as described by ref. paper, i.e. random +-1 values."""
x = np.random.randint(2, size=(N, features))
x[ x == 0 ] = -1 # data is encoded as +- 1
return x
tau = 1_000
P = 1_000
dt = tau/P
N_data = 8
N_feat = 10
data = create_dataset(N_data, N_feat).astype('float32')
labels = tf.ones((N_data), 'float32')
data = np.load('patterns8_10.npy')
#h_perc = tf.cast(H_perc_nobatch(data, labels), 'complex128')
h_perc = tf.cast(H_perc_nobatch(data, labels), 'complex128')
E0 = tfl.eigh(h_perc)[0][0]
h_x = tf.cast(H_x(data.shape[1]), 'complex128')
#h_z = tf.cast(H_z(data.shape[1]), 'complex128')
state = init_state(data.shape[1])
loss = []
pbar = tqdm(range(P), desc='ED QA')
for i in pbar:
h_t = H_QA(i+1, P, h_perc, h_x)
state = ed_qa_step(state, h_t, dt)
loss.append(tf.cast((tf.tensordot(tf.math.conj(state), tfl.matvec(tf.cast(h_perc, 'complex128'), state), axes=1)-E0)/N_feat, 'float32').numpy())
pbar.set_postfix({'loss':loss[-1], 'norm':tf.cast(tf.norm(state), 'float32').numpy()})
state
np.save('result', state.numpy())
which_down = tf.where(tf.cast(tfl.eigh(h_perc)[1][0], 'float32') > 0.).numpy()
which_down
state.numpy()[which_down[0]]
plt.plot((np.array(range(P))+1)/P, abs(np.asarray(loss)))
plt.yscale('log')
plt.ylabel(r'$\epsilon(s)$')
plt.xlabel(r'$s$')
plt.grid(alpha=0.2)
# comparison with dQA approach
psi_dqa = np.load('stato2.npy')
psi_qa = np.load('result.npy')
tf.cast(tf.norm(tfl.matvec(tf.cast(psi_dqa, 'complex128'), psi_qa, adjoint_a=True )), 'float32')
tau = 500
P = 1_000
dt = tau/P
N_data = 3
N_feat = 4
data = create_dataset(N_data, N_feat)
labels = np.ones((N_data), 'float32')
h_perc_diag = H_perc_diag(data, labels)
E0 = np.sort(h_perc_diag)[0]
h_x = H_x(data.shape[1])
h_perc = np.diag(h_perc_diag)
eigvals_array = np.empty((P, 2**N_feat))
pbar = tqdm(range(P), desc='Spectral analysis')
for i in pbar:
h_t = H_QA(i+1, P, h_perc, h_x)
eigvals, eigvecs = ncp.linalg.eigh(h_t)
eigvals_array[i] = np.real_if_close(eigvals.get())
np.save('eigvals_3-4', eigvals_array)
plt.plot(np.linspace(0, 1, P), eigvals_array[:,::1], lw=1.8)
plt.xlabel(r'$s(t)$', fontsize=14)
plt.ylabel(r'Energy [$a.u.$]', fontsize=14)
plt.tick_params('both', which='major', labelsize=12)
plt.title('Quantum Annealing\neigenvalues evolution', fontsize=16)
#plt.grid(alpha=0.3)
plt.savefig('qa_eigevolution.svg')
plt.savefig('qa_eigevolution.svg')
state = tf.cast(psi_dqa.squeeze(), 'complex128')
epsilon = (tf.cast(tf.tensordot(tf.math.conj(state), tfl.matvec(h_perc, state), axes=1), 'float32').numpy()-E0)/N_data
epsilon
state
import matplotlib.pyplot as plt
import numpy as np
import cupy
import math
from datetime import datetime
from tqdm.notebook import tqdm
from importlib.util import find_spec
GPU = True
if GPU:
if find_spec('cupy') is not None:
import cupy as ncp
else:
print('Selected device is GPU but cupy is not installed, falling back to numpy')
import numpy as ncp
else:
import numpy as ncp
def kronecker_prod(operators):
result = operators[0]
for op in operators[1:]:
result = ncp.kron(result, op)
return result
def ReLU(x):
return x * (x > 0)
def H_perc_diag(data, labels):
## ASSUMING H_PERC IS DIAGONAL, WHICH IS IN THE COMPUTATIONAL BASIS ##
n_data, n = data.shape
identity = ncp.ones((2,), 'float64')
sigma_z = ncp.array([1., -1.])
h_perc = ncp.zeros((2**n,), dtype='float64')
for i in range(n_data):
op = ncp.zeros((2**n,), dtype='float64')
for j in range(n):
op += kronecker_prod([identity]*j+[data[i, j] * sigma_z]+[identity]*(n-j-1))
h_perc += ReLU(-labels[i]*op)
del op
return h_perc / ncp.sqrt(n)
def H_x(n):
identity = ncp.diag([1., 1.])
sigma_x = ncp.array([[0., 1.], [1., 0.]])
op = ncp.zeros((2**n, 2**n), dtype='float64')
for j in range(n):
op += kronecker_prod([identity]*j+[sigma_x]+[identity]*(n-j-1))
return -op
def H_QA(p, P, Hz, Hx):
frac = p/P
return (frac*Hz + (1-frac)*Hx).astype('complex128')
def init_state(n):
return (ncp.ones((2**n,))/ncp.sqrt(2**n)).astype('complex128')
def ed_qa_step(state, Ht, dt):
eigvals, eigvecs = ncp.linalg.eigh(Ht)
# define time evolution operator
U = ncp.exp(-1.j*eigvals*dt)
# rewrite state in eigenvector basis, apply time evolution operator, project back to computational basis
evolved = ncp.dot(eigvecs, U * ncp.dot(eigvecs.transpose().conjugate(), state))
return evolved
def create_dataset(N : int, features : int):
"""Create dataset as described by ref. paper, i.e. random +-1 values."""
x = np.random.randint(2, size=(N, features))
x[ x == 0 ] = -1 # data is encoded as +- 1
return x
tau = 1_000
P = 5
dt = 0.5
N_feats = np.array([i for i in range(1, 14)])
N_datas = np.arange(1, np.floor(0.83*N_feats[[-1]]), dtype='int64')
memory = cupy.get_default_memory_pool()
#data = np.load('../data/patterns8_10.npy')
N_datas
used_ram_tot = np.empty((N_feats.shape[0], N_datas.shape[0], P, 4))
times = np.empty((N_feats.shape[0], N_datas.shape[0], P+1))
data_pbar = tqdm(total=len(N_datas), desc='testing N_data', leave=True)
p_pbar = tqdm(total=P, desc='ED QA', leave=True)
for m, N_feat in enumerate(tqdm(N_feats, desc='testing N_feat')):
for n, N_data in enumerate(N_datas):
start = datetime.now()
data = create_dataset(N_data, N_feat)
labels = np.ones((N_data), 'float32')
h_perc_diag = H_perc_diag(data, labels)
E0 = np.sort(h_perc_diag)[0]
h_x = H_x(data.shape[1])
h_perc = np.diag(h_perc_diag)
#h_z = tf.cast(H_z(data.shape[1]), 'complex128')
state = init_state(data.shape[1])
end = datetime.now()
times[m, n, -1] = (end-start).microseconds
loss = []
for i in range(P):
start = datetime.now()
h_t = H_QA(i+1, P, h_perc, h_x)
used_ram_tot[m, n, i, 0] = memory.used_bytes()
state = ed_qa_step(state, h_t, dt)
used_ram_tot[m, n, i, 1] = memory.used_bytes()
loss.append(ncp.real_if_close((ncp.tensordot(state.conjugate(), ncp.dot(h_perc, state), axes=1)-E0)/N_feat))
end = datetime.now()
times[m, n, i] = (end-start).microseconds
pbar.set_postfix({'loss':ncp.real_if_close(loss[-1]), 'norm':ncp.real_if_close(ncp.linalg.norm(state))})
used_ram_tot[m, n, i, 2] = memory.used_bytes()
del h_t
used_ram_tot[m, n, i, 3] = memory.used_bytes()
p_pbar.update()
del state
p_pbar.refresh()
p_pbar.reset()
data_pbar.update()
memory.free_all_blocks()
data_pbar.refresh()
data_pbar.reset()
used_ram_tot = np.load('perf_ram.npy')
times = np.load('perf_time.npy')
FONTSIZE=12
fig, (ax_ram, ax_time) = plt.subplots(2, 1, figsize=(8, 7), tight_layout=True, sharex=True)
ram_cmap = ax_ram.imshow(used_ram_tot[:,:,:,2].mean(axis=2).T/1e3, cmap='plasma', norm='log', origin='lower')
time_cmap = ax_time.imshow((times[:,:,:-1].mean(axis=2) + times[:,:,-1]).T/1e3, cmap='viridis', norm='log', origin='lower')
ax_ram.set_ylabel('#patterns', fontsize=FONTSIZE+2)
ax_ram.tick_params(axis='y', which='major', labelsize=FONTSIZE)
ax_ram.set_yticks(range(0,len(N_datas),2), labels=N_datas[::2])
ax_ram.set_title(r'RAM usage [$KB$]', fontsize=FONTSIZE+4)
ax_time.set_xlabel('#qbits', fontsize=FONTSIZE+2)
ax_time.set_ylabel('#patterns', fontsize=FONTSIZE+2)
ax_time.tick_params(axis='both', which='major', labelsize=FONTSIZE)
ax_time.set_xticks(range(0,len(N_feats),2), labels=N_feats[::2])
ax_time.set_yticks(range(0,len(N_datas),2), labels=N_datas[::2])
ax_time.set_title(r'Execution time [$ms$]', fontsize=FONTSIZE+4)
fig.colorbar(ram_cmap, ax=ax_ram)
fig.colorbar(time_cmap, ax=ax_time)
fig.suptitle('Exact diagonalization performances', fontsize=FONTSIZE+6, x=0.5845)
fig.savefig('ed_performances.svg')
plt.imshow(times[:,:,-1].T, cmap='plasma', origin='lower')
plt.plot(((ncp.array(range(P))+1)/P).get(), ncp.asarray(loss).get())
plt.yscale('log')
plt.ylabel(r'$\epsilon(s)$')
plt.xlabel(r'$s$')
plt.grid(alpha=0.2)
FONTSIZE=12
fig, ax = plt.subplots(figsize=(5, 4), tight_layout=True)
handle1 = ax.plot(N_feats, used_ram_tot[:,:,2].mean(axis=1)/1e3, label='RAM', lw=2)
ax.set_yscale('log')
ax.set_xlabel('#qbits', fontsize=FONTSIZE+2)
ax.set_xticks(N_feats[1::2])
ax.tick_params(axis='both', which='major', labelsize=FONTSIZE)
ax.set_ylabel(r'RAM usage [$KB$]', fontsize=FONTSIZE+2)
ax2 = ax.twinx()
handle2 = ax2.plot(N_feats, times[:,:-1].mean(axis=1)/1e3, c='tab:orange', label='Time', lw=2)
ax2.set_yscale('log')
ax2.tick_params(axis='y', which='major', labelsize=FONTSIZE)
ax2.set_ylabel(r'Execution time [$ms$]', fontsize=FONTSIZE+2)
ax.legend(handles=handle1+handle2, fontsize=FONTSIZE+2)
ax.set_title('Exact diagonalization performances', fontsize=FONTSIZE+4)
ax.grid(alpha=0.3)
ax2.grid(alpha=0.3)
plt.plot(N_feats, times[:,-1])
FONTSIZE=12
fig, ax = plt.subplots(figsize=(5, 4), tight_layout=True)
handle1 = ax.plot(N_feats, used_ram_tot[:,:,2].mean(axis=1)/1e3, label='RAM', lw=2)
ax.set_yscale('log')
ax.set_xlabel('#qbits', fontsize=FONTSIZE+2)
ax.set_xticks(N_feats[1::2])
ax.tick_params(axis='both', which='major', labelsize=FONTSIZE)
ax.set_ylabel(r'RAM usage [$KB$]', fontsize=FONTSIZE+2)
ax2 = ax.twinx()
handle2 = ax2.plot(N_feats, times[:,:-1].mean(axis=1)/1e3, c='tab:orange', label='Time', lw=2)
ax2.set_yscale('log')
ax2.tick_params(axis='y', which='major', labelsize=FONTSIZE)
ax2.set_ylabel(r'Execution time [$ms$]', fontsize=FONTSIZE+2)
ax.legend(handles=handle1+handle2, fontsize=FONTSIZE+2)
ax.set_title('Exact diagonalization performances', fontsize=FONTSIZE+4)
ax.grid(alpha=0.3)
ax2.grid(alpha=0.3)
plt.plot(N_feats, times[:,-1])
def H_perc2(state, data, labels):
n_data, n = data.shape
h_perc = tf.zeros((2**n, 2**n), dtype='complex128')
id = tfl.LinearOperatorIdentity(2)
sigma_z = tfl.LinearOperatorFullMatrix(tf.constant([[1., 0.], [0., -1.]]))
for i in range(n_data):
datum_ops = [tfl.LinearOperatorDiag(tf.repeat(data[i,:], [2], axis=0)[j:j+2]) for j in range(0, n*2, 2)]
ops = [tfl.LinearOperatorKronecker([id]*i+[tfl.LinearOperatorComposition([sigma_z, datum_ops[i]])]+[id]*(n-i-1)).to_dense() for j in range(n)]
result_op = tf.cast(-tf.reshape(labels[i], (1, 1))*tf.reduce_sum(tf.stack(ops), axis=0), 'complex128')
if tf.cast(tf.tensordot(tf.math.conj(state), tfl.matvec(result_op, state), axes=1), 'float32') < 0.:
continue
else:
h_perc = h_perc + result_op
return h_perc
|
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/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# vector v
v = [1,2,-3]
# vector u
u=[-2,3]
vu = []
for i in range(len(v)): # Each element of v will be replaced
for j in range(len(u)): # the vector u will come here after multiplying with the entry there
vu.append( v[i] * u[j] )
print("v=",v)
print("u=",u)
print("vu=",vu)
#
# your solution is here
#
import numpy as np
u = [-2, -1, 0, 1]
v = [1, 2, 3]
uv = np.tensordot(np.array(u), np.array(v), axes = 0)
print("uv: " + str(uv))
# matrix M
M = [
[-1,0,1],
[-2,-1,2],
[1,2,-2]
]
# matrix N
N = [
[0,2,1],
[3,-1,-2],
[-1,1,0]
]
# MN will be a (9x9)-dimensional matrix
# let's prepare it as a zero matrix
# this helps us to easily fill it
MN=[]
for i in range(9):
MN.append([])
for j in range(9):
MN[i].append(0)
for i in range(3): # row of M
for j in range(3): # column of M
for k in range(3): # row of N
for l in range(3): # column of N
MN[i*3+k][3*j+l] = M[i][j] * N[k][l]
print("M-tensor-N is")
for i in range(9):
print(MN[i])
# matrices M and N were defined above
# matrix NM will be prepared as a (9x9)-dimensional zero matrix
NM=[]
for i in range(9):
NM.append([])
for j in range(9):
NM[i].append(0)
for i in range(3): # row of N
for j in range(3): # column of N
for k in range(3): # row of M
for l in range(3): # column of M
NM[i*3+k][3*j+l] = N[i][j] * M[k][l]
print("N-tensor-M is")
for i in range(9):
print(NM[i])
#
# your solution is here
#
A = [
[-1,0,1],
[-2,-1,2]
]
B = [
[0,2],
[3,-1],
[-1,1]
]
print("A =")
for i in range(len(A)):
print(A[i])
print() # print a line
print("B =")
for i in range(len(B)):
print(B[i])
# let's define A-tensor-B as a (6x6)-dimensional zero matrix
AB = []
for i in range(6):
AB.append([])
for j in range(6):
AB[i].append(0)
# let's find A-tensor-B
for i in range(2):
for j in range(3):
# for each A(i,j) we execute the following codes
a = A[i][j]
# we access each element of B
for m in range(3):
for n in range(2):
b = B[m][n]
# now we put (a*b) in the appropriate index of AB
AB[3*i+m][2*j+n] = a * b
print() # print a line
print("A-tensor-B =")
print() # print a line
for i in range(6):
print(AB[i])
#
# your solution is here
#
A = [
[-1,0,1],
[-2,-1,2]
]
B = [
[0,2],
[3,-1],
[-1,1]
]
print() # print a line
print("B =")
for i in range(len(B)):
print(B[i])
print("A =")
for i in range(len(A)):
print(A[i])
# let's define B-tensor-A as a (6x6)-dimensional zero matrix
BA = []
for i in range(6):
BA.append([])
for j in range(6):
BA[i].append(0)
# let's find B-tensor-A
for i in range(3):
for j in range(2):
# for each B(i,j) we execute the following codes
b = B[i][j]
# we access each element of A
for m in range(2):
for n in range(3):
a = A[m][n]
# now we put (a*b) in the appropriate index of AB
BA[2*i+m][3*j+n] = b * a
print() # print a line
print("B-tensor-A =")
print() # print a line
for i in range(6):
print(BA[i])
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
This module contains the definition of a base class for quantum fourier transforms.
"""
from abc import abstractmethod
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import Pluggable, AquaError
class QFT(Pluggable):
"""Base class for QFT.
This method should initialize the module and its configuration, and
use an exception if a component of the module is
available.
Args:
configuration (dict): configuration dictionary
"""
@abstractmethod
def __init__(self, *args, **kwargs):
super().__init__()
@classmethod
def init_params(cls, params):
qft_params = params.get(Pluggable.SECTION_KEY_QFT)
kwargs = {k: v for k, v in qft_params.items() if k != 'name'}
return cls(**kwargs)
@abstractmethod
def _build_matrix(self):
raise NotImplementedError
@abstractmethod
def _build_circuit(self, qubits=None, circuit=None, do_swaps=True):
raise NotImplementedError
def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True):
"""Construct the circuit.
Args:
mode (str): 'matrix' or 'circuit'
qubits (QuantumRegister or qubits): register or qubits to build the circuit on.
circuit (QuantumCircuit): circuit for construction.
do_swaps (bool): include the swaps.
Returns:
The matrix or circuit depending on the specified mode.
"""
if mode == 'circuit':
return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps)
elif mode == 'matrix':
return self._build_matrix()
else:
raise AquaError('Unrecognized mode: {}.'.format(mode))
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
import numpy as np
from qiskit import *
%matplotlib inline
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
#circ.draw()
circ.draw(output='mpl')
# Import Aer
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator')
job = execute(circ, backend)
result = job.result()
# Show the results
print(result.get_unitary(circ, decimals=3))
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3),range(3))
# The Qiskit circuit object supports composition using
# the addition operator.
qc = circ+meas
#drawing the circuit
qc.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = execute(qc, backend_sim, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
from qiskit import IBMQ
#IBMQ.save_account('APIKEY')
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider(group='open')
provider.backends()
simulator_backend = provider.get_backend('ibmq_qasm_simulator')
job_cloud = execute(qc, backend=simulator_backend)
result_cloud = job_cloud.result()
counts_cloud = result_cloud.get_counts(qc)
plot_histogram(counts_cloud)
#example of backend filtering, you can modify the filters or ask just for the least_busy device
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
#here we ask for the backend properties
backend.configuration()
from qiskit.tools.monitor import job_monitor
job_exp = execute(qc, backend=backend)
job_monitor(job_exp)
result_exp = job_exp.result()
counts_exp = result_exp.get_counts(qc)
plot_histogram([counts_exp,counts], legend=['Device', 'Simulator'])
#uncomment the line below in case you are not able to specify 'latex' in the draw method
#!pip install pylatexenc
#!pip install pillow
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer
qr0 = QuantumRegister(1,name='qb') # qb for "qubit", but the name is optional
cr0 = ClassicalRegister(1,name='b') # b for "bit", but the name is optional
qc0 = QuantumCircuit(qr0,cr0)
qc0.draw(output='latex')
from qiskit.tools.visualization import plot_bloch_vector
import math
theta = math.pi/2 # You can try to change the parameters theta and phi
phi = math.pi/4 # to see how the vector moves on the sphere
plot_bloch_vector([math.cos(phi)*math.sin(theta),math.sin(phi)*math.sin(theta),math.cos(theta)]) # Entries of the
# input vector are
# coordinates [x,y,z]
qc0.measure(qr0,cr0)
#Select the output method to use for drawing the circuit. Valid choices are text, latex, latex_source, or mpl. By default the ‘text’ drawer is used unless a user config file has an alternative backend set as the default.
#If the output kwarg is set, that backend will always be used over the default in a user config file.
qc0.draw('latex')
#backend_sim = Aer.get_backend('qasm_simulator') already defined above
job = execute(qc0, backend_sim, shots=1024)
result = job.result()
counts = result.get_counts()
print(counts)
qc1 = QuantumCircuit(qr0,cr0)
qc1.x(0) # A X gate targeting the first (and only) qubit in register qr0
qc1.measure(qr0,cr0)
qc1.draw(output='mpl')
job1 = execute(qc1, backend_sim, shots=1024)
result1 = job1.result()
counts1 = result1.get_counts()
print(counts1)
from qiskit.tools.visualization import plot_bloch_multivector
vec_backend = Aer.get_backend('statevector_simulator')
result_vec0 = execute(qc0, vec_backend).result()
result_vec1 = execute(qc1, vec_backend).result()
psi0 = result_vec0.get_statevector()
psi1 = result_vec1.get_statevector()
plot_bloch_multivector(psi0)
plot_bloch_multivector(psi1)
qc2 = QuantumCircuit(qr0,cr0)
qc2.h(0)
qc2.measure(qr0,cr0)
qc2.draw(output='mpl')
job2 = execute(qc2, backend_sim, shots=1024)
result2 = job2.result()
counts2 = result2.get_counts()
print(counts2)
result_vec2 = execute(qc2, vec_backend).result()
psi2 = result_vec2.get_statevector()
plot_bloch_multivector(psi2)
qc3 = QuantumCircuit(qr0,cr0)
qc3.h(0)
qc3.s(0) # Use sdg instead of s for the adjoint
qc3.measure(qr0,cr0)
qc3.draw(output='mpl')
job3 = execute(qc3, backend_sim, shots=1024)
result3 = job3.result()
counts3 = result3.get_counts()
print(counts3)
result_vec3 = execute(qc3, vec_backend).result()
psi3 = result_vec3.get_statevector()
plot_bloch_multivector(psi3)
qc4 = QuantumCircuit(qr0,cr0)
qc4.h(0)
qc4.t(0) # Use tdg instead of t for the adjoint
qc4.measure(qr0,cr0)
qc4.draw(output='mpl')
job4 = execute(qc4, backend_sim, shots=1024)
result4 = job4.result()
counts4 = result4.get_counts()
print(counts4)
result_vec4 = execute(qc4, vec_backend).result()
psi4 = result_vec4.get_statevector()
plot_bloch_multivector(psi4)
qc4b = QuantumCircuit(qr0)
qc4b.tdg(0)
qc4b.draw('mpl')
backend_unit = BasicAer.get_backend('unitary_simulator')
job = execute(qc4b, backend_unit)
job.result().get_unitary(qc4b, decimals=3)
lmbd = 1.2 # Change this value to rotate the output vector on the equator of the Bloch sphere
qc5 = QuantumCircuit(qr0,cr0)
qc5.h(0)
qc5.u1(lmbd,0)
qc5.measure(qr0,cr0)
qc5.draw(output='mpl')
result_vec5 = execute(qc5, vec_backend).result()
psi5 = result_vec5.get_statevector()
plot_bloch_multivector(psi5)
qc6 = QuantumCircuit(qr0,cr0)
qc6.u2(0,math.pi, 0)
qc6.measure(qr0,cr0)
result_vec6 = execute(qc6, vec_backend).result()
psi6 = result_vec6.get_statevector()
plot_bloch_multivector(psi6)
theta = math.pi
phi = math.pi
lmb = math.pi
qc7 = QuantumCircuit(qr0,cr0)
qc7.u3(theta,phi, lmb, 0)
qc7.measure(qr0,cr0)
result_vec7 = execute(qc7, vec_backend).result()
psi7 = result_vec7.get_statevector()
plot_bloch_multivector(psi7)
qr = QuantumRegister(2,name='qr') # we need a 2-qubit register now
cr = ClassicalRegister(2,name='cr')
cnot_example = QuantumCircuit(qr,cr)
cnot_example.x(0)
cnot_example.cx(0,1) # First entry is control, the second is the target
cnot_example.measure(qr,cr)
cnot_example.draw(output='mpl')
job_cnot = execute(cnot_example, backend_sim, shots=1024)
result_cnot = job_cnot.result()
counts_cnot = result_cnot.get_counts()
print(counts_cnot)
cnot_reversed = QuantumCircuit(qr,cr)
cnot_reversed.x(0)
# This part uses cx(qr[1],qr[0]) but is equivalent to cx(qr[0],qr[1])
cnot_reversed.h(0)
cnot_reversed.h(1)
cnot_reversed.cx(1,0)
cnot_reversed.h(0)
cnot_reversed.h(1)
#
cnot_reversed.measure(qr,cr)
cnot_reversed.draw(output='mpl')
job_cnot_rev = execute(cnot_reversed, backend_sim, shots=1024)
result_cnot_rev = job_cnot_rev.result()
counts_cnot_rev = result_cnot_rev.get_counts()
print(counts_cnot_rev)
bell_phi_p = QuantumCircuit(qr,cr)
bell_phi_p.h(0)
bell_phi_p.cx(0,1)
bell_phi_p.measure(qr,cr)
bell_phi_p.draw(output='mpl')
job_bell_phi_p = execute(bell_phi_p, backend_sim, shots=1024)
result_bell_phi_p = job_bell_phi_p.result()
counts_bell_phi_p = result_bell_phi_p.get_counts()
print(counts_bell_phi_p)
cz_example = QuantumCircuit(qr)
cz_example.cz(0,1)
cz_example.draw(output='mpl')
job_cz = execute(cz_example, backend_unit)
job_cz.result().get_unitary(cz_example, decimals=3)
cz_from_cnot = QuantumCircuit(qr)
#notice here a more verbose way of writing gates and assign them to qubits
cz_from_cnot.h(qr[1])
cz_from_cnot.cx(qr[0],qr[1])
cz_from_cnot.h(qr[1])
cz_from_cnot.draw(output='mpl')
swap_test = QuantumCircuit(qr)
swap_test.swap(qr[0],qr[1])
swap_test.draw(output='mpl')
swap_from_cnot = QuantumCircuit(qr)
swap_from_cnot.cx(qr[0],qr[1])
swap_from_cnot.cx(qr[1],qr[0])
swap_from_cnot.cx(qr[0],qr[1])
swap_from_cnot.draw(output='mpl')
qr_many = QuantumRegister(5)
control_example = QuantumCircuit(qr_many)
control_example.cy(qr_many[0],qr_many[1])
control_example.ch(qr_many[1],qr_many[2])
control_example.crz(0.2,qr_many[2],qr_many[3])
control_example.cu3(0.5, 0, 0, qr_many[3],qr_many[4])
control_example.draw(output='mpl')
qrthree = QuantumRegister(3)
toffoli_example = QuantumCircuit(qrthree)
toffoli_example.ccx(0,1,2)
toffoli_example.draw(output='mpl')
toffoli_from_cnot = QuantumCircuit(qrthree)
toffoli_from_cnot.h(qrthree[2])
toffoli_from_cnot.cx(qrthree[1],qrthree[2])
toffoli_from_cnot.tdg(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[2])
toffoli_from_cnot.t(qrthree[2])
toffoli_from_cnot.cx(qrthree[1],qrthree[2])
toffoli_from_cnot.tdg(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[2])
toffoli_from_cnot.tdg(qrthree[1])
toffoli_from_cnot.t(qrthree[2])
toffoli_from_cnot.h(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[1])
toffoli_from_cnot.tdg(qrthree[1])
toffoli_from_cnot.cx(qrthree[0],qrthree[1])
toffoli_from_cnot.s(qrthree[1])
toffoli_from_cnot.t(qrthree[0])
toffoli_from_cnot.draw(output='mpl')
# 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(output='latex')
backend = BasicAer.get_backend('statevector_simulator')
job = execute(qc, backend)
qc_state = job.result().get_statevector(qc)
qc_state
state_fidelity(desired_vector,qc_state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.optimizers import SLSQP
from qiskit.circuit.library import TwoLocal
num_qubits = 2
ansatz = TwoLocal(num_qubits, "ry", "cz")
optimizer = SLSQP(maxiter=1000)
ansatz.decompose().draw("mpl", style="iqx")
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit.algorithms.minimum_eigensolvers import VQE
vqe = VQE(estimator, ansatz, optimizer)
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list([
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156)
])
result = vqe.compute_minimum_eigenvalue(H2_op)
print(result)
from qiskit.algorithms.optimizers import SPSA
estimator = Estimator(options={"shots": 1000})
vqe.estimator = estimator
vqe.optimizer = SPSA(maxiter=100)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/epelaaez/QuantumLibrary
|
epelaaez
|
# To clean enviroment variables
%reset
import numpy as np
import pandas as pd
import folium
import matplotlib.pyplot as plt
try:
import cplex
from cplex.exceptions import CplexError
except:
print("Warning: Cplex not found.")
import math
from qiskit.utils import algorithm_globals
from qiskit_algorithms import SamplingVQE
from qiskit_algorithms.optimizers import SPSA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
df = pd.read_csv("uscities.csv")
columnsNeeded = ["city", "lat", "lng"]
# Inicialization of variables
locationsNumber = 15 # OJO que en local me crashea si sobrepaso 5
coordenatesDf = df[columnsNeeded].iloc[:locationsNumber]
n = coordenatesDf.shape[0] # number of nodes + depot (n+1)
K = 3 # number of vehicles
print(coordenatesDf)
# Initialize instance values by calculate the squared Euclidean distances between a set of coordinates
# represented in the dataframe.
def generate_instance(coordenatesDf):
n = coordenatesDf.shape[0]
xc = coordenatesDf["lat"]
yc = coordenatesDf["lng"]
loc = coordenatesDf["city"]
instance = np.zeros([n, n])
for ii in range(0, n):
for jj in range(ii + 1, n):
instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2
instance[jj, ii] = instance[ii, jj]
return xc, yc, instance, loc
# Initialize the problem by randomly generating the instance
lat, lng, instance, loc = generate_instance(coordenatesDf)
print(lat, lng, loc, instance)
#print(instance)
class ClassicalOptimizer:
def __init__(self, instance, n, K):
self.instance = instance
self.n = n # number of nodes
self.K = K # number of vehicles
def compute_allowed_combinations(self):
f = math.factorial
return f(self.n) / f(self.K) / f(self.n - self.K)
def cplex_solution(self):
# refactoring
instance = self.instance
n = self.n
K = self.K
my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)]
my_ub = [1 for x in range(0, n**2 + n - 1)]
my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)]
my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join(
["C" for x in range(0, n - 1)]
)
my_rhs = (
2 * ([K] + [1 for x in range(0, n - 1)])
+ [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))]
+ [0 for x in range(0, n)]
)
my_sense = (
"".join(["E" for x in range(0, 2 * n)])
+ "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))])
+ "".join(["E" for x in range(0, n)])
)
try:
my_prob = cplex.Cplex()
self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs)
my_prob.solve()
except CplexError as exc:
print(exc)
return
x = my_prob.solution.get_values()
x = np.array(x)
cost = my_prob.solution.get_objective_value()
return x, cost
def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs):
n = self.n
prob.objective.set_sense(prob.objective.sense.minimize)
prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype)
prob.set_log_stream(None)
prob.set_error_stream(None)
prob.set_warning_stream(None)
prob.set_results_stream(None)
rows = []
for ii in range(0, n):
col = [x for x in range(0 + n * ii, n + n * ii)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [x for x in range(0 + ii, n**2, n)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
# Sub-tour elimination constraints:
for ii in range(0, n):
for jj in range(0, n):
if (ii != jj) and (ii * jj > 0):
col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1]
coef = [1, 1, -1]
rows.append([col, coef])
for ii in range(0, n):
col = [(ii) * (n + 1)]
coef = [1]
rows.append([col, coef])
prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs)
# Instantiate the classical optimizer class
classical_optimizer = ClassicalOptimizer(instance, n, K)
# Print number of feasible solutions
print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations()))
# Solve the problem in a classical fashion via CPLEX
x = None
z = None
try:
x, classical_cost = classical_optimizer.cplex_solution()
# Put the solution in the z variable
z = [x[ii] for ii in range(n**2) if ii // n != ii % n]
# Print the solution
print(z)
except:
print("CPLEX may be missing.")
m = folium.Map(location=[39.487660, -97.594333], zoom_start=0)
marker_icon1 = folium.Icon(color = "red")
for i in range(len(lat)):
if (i == 0):
folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m)
else:
folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m)
for ii in range(0, n**2):
if x[ii] > 0:
ix = ii // n
iy = ii % n
folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m)
m
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
class QuantumOptimizer:
def __init__(self, instance, n, K):
self.instance = instance
self.n = n
self.K = K
def binary_representation(self, x_sol=0):
instance = self.instance
n = self.n
K = self.K
A = np.max(instance) * 100 # A parameter of cost function
# Determine the weights w
instance_vec = instance.reshape(n**2)
w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0]
w = np.zeros(n * (n - 1))
for ii in range(len(w_list)):
w[ii] = w_list[ii]
# Some variables I will use
Id_n = np.eye(n)
Im_n_1 = np.ones([n - 1, n - 1])
Iv_n_1 = np.ones(n)
Iv_n_1[0] = 0
Iv_n = np.ones(n - 1)
neg_Iv_n_1 = np.ones(n) - Iv_n_1
v = np.zeros([n, n * (n - 1)])
for ii in range(n):
count = ii - 1
for jj in range(n * (n - 1)):
if jj // (n - 1) == ii:
count = ii
if jj // (n - 1) != ii and jj % (n - 1) == count:
v[ii][jj] = 1.0
vn = np.sum(v[1:], axis=0)
# Q defines the interactions between variables
Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v))
# g defines the contribution from the individual variables
g = (
w
- 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T)
- 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T)
)
# c is the constant offset
c = 2 * A * (n - 1) + 2 * A * (K**2)
try:
max(x_sol)
# Evaluates the cost distance from a binary representation of a path
fun = (
lambda x: np.dot(np.around(x), np.dot(Q, np.around(x)))
+ np.dot(g, np.around(x))
+ c
)
cost = fun(x_sol)
except:
cost = 0
return Q, g, c, cost
def construct_problem(self, Q, g, c) -> QuadraticProgram:
qp = QuadraticProgram()
for i in range(n * (n - 1)):
qp.binary_var(str(i))
qp.objective.quadratic = Q
qp.objective.linear = g
qp.objective.constant = c
return qp
def solve_problem(self, qp):
algorithm_globals.random_seed = 10598
#vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes())
#optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe)
meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver())
result = meo.solve(qp)
# compute cost of the obtained result
_, _, _, level = self.binary_representation(x_sol=result.x)
return result.x, level
# Instantiate the quantum optimizer class with parameters:
quantum_optimizer = QuantumOptimizer(instance, n, K)
# Check if the binary representation is correct
try:
if z is not None:
Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z)
print("Binary cost:", binary_cost, "classical cost:", classical_cost)
if np.abs(binary_cost - classical_cost) < 0.01:
print("Binary formulation is correct")
else:
print("Error in the binary formulation")
else:
print("Could not verify the correctness, due to CPLEX solution being unavailable.")
Q, g, c, binary_cost = quantum_optimizer.binary_representation()
print("Binary cost:", binary_cost)
except NameError as e:
print("Warning: Please run the cells above first.")
print(e)
qp = quantum_optimizer.construct_problem(Q, g, c)
print(qp)
#quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp)
quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp)
print(quantum_solution, quantum_cost)
print(classical_cost)
m = folium.Map(location=[39.487660, -97.594333], zoom_start=0)
marker_icon1 = folium.Icon(color = "red")
for i in range(len(lat)):
if (i == 0):
folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m)
else:
folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m)
for ii in range(0, n**2):
if x[ii] > 0:
ix = ii // n
iy = ii % n
folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m)
m
print(quantum_cost)
x_quantum = np.zeros(n**2)
kk = 0
for ii in range(n**2):
if ii // n != ii % n:
x_quantum[ii] = quantum_solution[kk]
kk += 1
m = folium.Map(location=[39.487660, -97.594333], zoom_start=0)
marker_icon1 = folium.Icon(color = "red")
for i in range(len(lat)):
if (i == 0):
folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m)
else:
folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m)
for ii in range(0, n**2):
if x_quantum[ii] > 0:
ix = ii // n
iy = ii % n
folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m)
m
algorithms = ("Classic", "Quantum")
data = {
'K = 1': (2249.2068134000006, 1706.2245994000696),
'k = 2': (2771.940853740001, 1845.127222779207),
'K = 3': (3981.1556002800016, 3981.155600280501),
}
x = np.arange(len(algorithms)) # the label locations
width = 0.25 # the width of the bars
multiplier = 0
fig, ax = plt.subplots(layout='constrained')
for attribute, measurement in data.items():
offset = width * multiplier
rects = ax.bar(x + offset, measurement, width, label=attribute)
ax.bar_label(rects, padding=3)
multiplier += 1
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Length (mm)')
ax.set_title('Comparision of Quantum and Classical Cost')
ax.set_xticks(x + width, algorithms)
ax.legend(loc='upper left', ncols=3)
ax.set_ylim(0, 5000)
plt.show()
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
import qiskit
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from tsp_qaoa import marina_solution
G=nx.Graph()
i=1
G.add_node(i,pos=(i,i))
G.add_node(2,pos=(2,2))
G.add_node(3,pos=(1,0))
G.add_edge(1,2,weight=20.5)
G.add_edge(1,3,weight=9.8)
pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
def append_zz_term(qc,q1,q2,gamma):
qc.cx(q1,q2)
qc.rz(2*gamma,q2)
qc.cx(q1,q2)
def get_cost_circuit(G,gamma):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for i,j in G.edges():
append_zz_term(qc,i,j,gamma)
return qc
#print(get_cost_circuit(G,0.5))
def append_x_term(qc,q1,beta):
qc.rx(2*beta,q1)
def get_mixer_operator(G,beta):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for n in G.nodes():
append_x_term(qc,n,beta)
return qc
#print(get_mixer_operator(G,0.5))
def get_QAOA_circuit(G,beta,gamma):
assert(len(beta)==len(gamma))
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
qc.h(range(N))
p=len(beta)
#aplicamos las p rotaciones
for i in range(p):
qc=qc.compose(get_cost_circuit(G,gamma[i]))
qc=qc.compose(get_mixer_operator(G,beta[i]))
qc.barrier(range(N))
qc.measure(range(N),range(N))
return qc
print(get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6]))
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
qc=get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6])
backend=Aer.get_backend('qasm_simulator')
job=execute(qc,backend)
result=job.result()
print(invert_counts(result.get_counts()))
def maxcut_obj(x,G):
cut=0
for i,j in G.edges():
if x[i]!=x[j]:
cut = cut-1
return cut
print(maxcut_obj("00011",G))
def compute_maxcut_energy(counts,G):
energy=0
get_counts=0
total_counts=0
for meas, meas_count in counts.items():
obj_for_meas=maxcut_obj(meas,G)
energy+=obj_for_meas*meas_count
total_counts+=meas_count
return energy/total_counts
def get_black_box_objective(G,p):
backend=Aer.get_backend('qasm_simulator')
def f(theta):
beta=theta[:p]
gamma=theta[p:]
qc=get_QAOA_circuit(G,beta,gamma)
counts=execute(qc,backend,seed_simulator=10).result().get_counts()
return compute_maxcut_energy(invert_counts(counts),G)
return f
p=5
obj=get_black_box_objective(G,p)
init_point=np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1])#([2,2,1,1,1,1,1,1,1,1])
res_sample=minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
res_sample
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
cantidad_ciudades = 4
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
pos=nx.spring_layout(G)
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
G
pos=nx.get_node_attributes(G,'weight')
pos
labels = nx.get_edge_attributes(G,'weight')
labels
def funcion_costo(multiplicador_lagrange, cantidad_ciudades, pesos, conexiones ):
N = G.number_of_nodes()
N_square = N^2
# restriccion 1
for i in range(cantidad_ciudades):
cur = sI(N_square)
for j in range(num_cities):
cur -= D(i, j)
ret += cur**2
# retorna el indice de qubit por conversion al problema
def quibit_indice(i, l, N):
return i * N + l
from qiskit.quantum_info.operators import Operator, Pauli
# Create an operator
XX = Operator(Pauli(label='XX'))
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(XX, [0, 1])
circ.measure([0,1], [0,1])
circ.draw('mpl')
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(a, [0])
#circ.measure([0,1], [0,1])
circ.draw('mpl')
a = I - ( 0.5*(I+ Z))**2
a = Operator(a)
a.is_unitary()
print(I @ Z)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import GaussianForcesDriver
# if you ran Gaussian elsewhere and already have the output file
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
# if you want to run the Gaussian job from Qiskit
# driver = GaussianForcesDriver(
# ['#p B3LYP/6-31g Freq=(Anharm) Int=Ultrafine SCF=VeryTight',
# '',
# 'CO2 geometry optimization B3LYP/6-31g',
# '',
# '0 1',
# 'C -0.848629 2.067624 0.160992',
# 'O 0.098816 2.655801 -0.159738',
# 'O -1.796073 1.479446 0.481721',
# '',
# ''
from qiskit_nature.second_q.problems import HarmonicBasis
basis = HarmonicBasis([2, 2, 2, 2])
from qiskit_nature.second_q.problems import VibrationalStructureProblem
from qiskit_nature.second_q.mappers import DirectMapper
vibrational_problem = driver.run(basis=basis)
vibrational_problem.hamiltonian.truncation_order = 2
main_op, aux_ops = vibrational_problem.second_q_ops()
print(main_op)
qubit_mapper = DirectMapper()
qubit_op = qubit_mapper.map(main_op)
print(qubit_op)
basis = HarmonicBasis([3, 3, 3, 3])
vibrational_problem = driver.run(basis=basis)
vibrational_problem.hamiltonian.truncation_order = 2
main_op, aux_ops = vibrational_problem.second_q_ops()
qubit_mapper = DirectMapper()
qubit_op = qubit_mapper.map(main_op)
print(qubit_op)
# for simplicity, we will use the smaller basis again
vibrational_problem = driver.run(basis=HarmonicBasis([2, 2, 2, 2]))
vibrational_problem.hamiltonian.truncation_order = 2
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
solver = GroundStateEigensolver(
qubit_mapper,
NumPyMinimumEigensolver(filter_criterion=vibrational_problem.get_default_filter_criterion()),
)
result = solver.solve(vibrational_problem)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-aqt-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright Alpine Quantum Technologies 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.
import base64
import io
import typing
from pathlib import Path
from typing import Any, Optional, Union
import platformdirs
import pydantic as pdt
from pydantic import ConfigDict, GetCoreSchemaHandler
from pydantic_core import CoreSchema, core_schema
from qiskit import qpy
from qiskit.circuit import QuantumCircuit
from typing_extensions import Self
from qiskit_aqt_provider.api_models import ResourceId
from qiskit_aqt_provider.aqt_options import AQTOptions
from qiskit_aqt_provider.utils import map_exceptions
from qiskit_aqt_provider.versions import QISKIT_AQT_PROVIDER_VERSION
class JobNotFoundError(Exception):
"""A job was not found in persistent storage."""
class Circuits:
"""Custom Pydantic type to persist and restore lists of Qiskit circuits.
Serialization of :class:`QuantumCircuit <qiskit.circuit.QuantumCircuit>` instances is
provided by :mod:`qiskit.qpy`.
"""
def __init__(self, circuits: list[QuantumCircuit]) -> None:
"""Initialize a container filled with the given circuits."""
self.circuits = circuits
@classmethod
def __get_pydantic_core_schema__(
cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
"""Setup custom validator, to turn this class into a pydantic model."""
return core_schema.no_info_plain_validator_function(function=cls.validate)
@classmethod
def validate(cls, value: Union[Self, str]) -> Self:
"""Parse the base64-encoded :mod:`qiskit.qpy` representation of a list of quantum circuits.
Because initializing a Pydantic model also triggers validation, this parser accepts
already formed instances of this class and returns them unvalidated.
"""
if isinstance(value, Circuits): # self bypass
return typing.cast(Self, value)
if not isinstance(value, str):
raise ValueError(f"Expected string, received {type(value)}")
data = base64.b64decode(value.encode("ascii"))
buf = io.BytesIO(data)
obj = qpy.load(buf)
if not isinstance(obj, list):
obj = [obj]
for n, qc in enumerate(obj):
if not isinstance(qc, QuantumCircuit):
raise ValueError(f"Object at position {n} is not a QuantumCircuit: {type(qc)}")
return cls(circuits=obj)
@classmethod
def json_encoder(cls, value: Self) -> str:
"""Return a base64-encoded QPY representation of the held list of circuits."""
buf = io.BytesIO()
qpy.dump(value.circuits, buf)
return base64.b64encode(buf.getvalue()).decode("ascii")
class Job(pdt.BaseModel):
"""Model for job persistence in local storage."""
model_config = ConfigDict(frozen=True, json_encoders={Circuits: Circuits.json_encoder})
resource: ResourceId
circuits: Circuits
options: AQTOptions
@classmethod
@map_exceptions(JobNotFoundError, source_exc=(FileNotFoundError,))
def restore(cls, job_id: str, store_path: Path) -> Self:
"""Load data for a job by ID from local storage.
Args:
job_id: identifier of the job to restore.
store_path: path to the local storage directory.
Raises:
JobNotFoundError: no job with the given identifier is stored in the local storage.
"""
data = cls.filepath(job_id, store_path).read_text("utf-8")
return cls.model_validate_json(data)
def persist(self, job_id: str, store_path: Path) -> Path:
"""Persist the job data to the local storage.
Args:
job_id: storage key for this job data.
store_path: path to the local storage directory.
Returns:
The path of the persisted data file.
"""
filepath = self.filepath(job_id, store_path)
filepath.write_text(self.model_dump_json(), "utf-8")
return filepath
@classmethod
def remove_from_store(cls, job_id: str, store_path: Path) -> None:
"""Remove persisted job data from the local storage.
This function also succeeds if there is no data under `job_id`.
Args:
job_id: storage key for the data to delete.
store_path: path to the local storage directory.
"""
cls.filepath(job_id, store_path).unlink(missing_ok=True)
@classmethod
def filepath(cls, job_id: str, store_path: Path) -> Path:
"""Path of the file to store data under a given key in local storage.
Args:
job_id: storage key for the data.
store_path: path to the local storage directory.
"""
return store_path / job_id
def get_store_path(override: Optional[Path] = None) -> Path:
"""Resolve the local persistence store path.
By default, this is the user cache directory for this package.
Different cache directories are used for different package versions.
Args:
override: if given, return this override instead of the default path.
Returns:
Path for the persistence store. Ensured to exist.
"""
if override is not None:
override.mkdir(parents=True, exist_ok=True)
return override
return Path(
platformdirs.user_cache_dir(
"qiskit_aqt_provider",
version=QISKIT_AQT_PROVIDER_VERSION,
ensure_exists=True,
)
)
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
import qiskit.quantum_info as qi
from qiskit.circuit.library import FourierChecking #FourierChecking is an algorithm circuit built into the circuit library
from qiskit.visualization import plot_histogram
#these both are functions, among which, we find the corelativity
f=[1,-1,-1,-1]
g=[1,1,-1,-1]
circ = FourierChecking(f=f, g=g)
circ.draw()
zero = qi.Statevector.from_label('00')
sv = zero.evolve(circ)
probs = sv.probabilities_dict()
plot_histogram(probs) #only intersted in 00 probability
|
https://github.com/stevvwen/QAlgoImplementation
|
stevvwen
|
# initialization
import numpy as np
import matplotlib
# importing Qiskit
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer, assemble, transpile
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += balanced_oracle
dj_circuit.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += balanced_oracle
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw(output='mpl', style=style)
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(dj_circuit, aer_sim)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
print(b)
print(str(n))
b=7
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
print(b_str)
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw(output='mpl', style=style)
transpiled_dj_circuit = transpile(dj_circuit, aer_sim)
qobj = assemble(transpiled_dj_circuit)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
# Since the import is nearly entirely delegated to an external package, most of the testing is done
# there. Here we need to test our wrapping behaviour for base functionality and exceptions. We
# don't want to get into a situation where updates to `qiskit_qasm3_import` breaks Terra's test
# suite due to too specific tests on the Terra side.
import os
import tempfile
import unittest
from qiskit import qasm3
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
class TestQASM3Import(QiskitTestCase):
@unittest.skipUnless(
optionals.HAS_QASM3_IMPORT, "need qiskit-qasm3-import for OpenQASM 3 imports"
)
def test_import_errors_converted(self):
with self.assertRaises(qasm3.QASM3ImporterError):
qasm3.loads("OPENQASM 3.0; qubit[2.5] q;")
@unittest.skipUnless(
optionals.HAS_QASM3_IMPORT, "need qiskit-qasm3-import for OpenQASM 3 imports"
)
def test_loads_can_succeed(self):
program = """
OPENQASM 3.0;
include "stdgates.inc";
qubit[2] qr;
bit[2] cr;
h qr[0];
cx qr[0], qr[1];
cr[0] = measure qr[0];
cr[1] = measure qr[1];
"""
parsed = qasm3.loads(program)
expected = QuantumCircuit(QuantumRegister(2, "qr"), ClassicalRegister(2, "cr"))
expected.h(0)
expected.cx(0, 1)
expected.measure(0, 0)
expected.measure(1, 1)
self.assertEqual(parsed, expected)
@unittest.skipUnless(
optionals.HAS_QASM3_IMPORT, "need qiskit-qasm3-import for OpenQASM 3 imports"
)
def test_load_can_succeed(self):
program = """
OPENQASM 3.0;
include "stdgates.inc";
qubit[2] qr;
bit[2] cr;
h qr[0];
cx qr[0], qr[1];
cr[0] = measure qr[0];
cr[1] = measure qr[1];
"""
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = os.path.join(tmp_dir, "bell.qasm")
with open(tmp_path, "w") as fptr:
fptr.write(program)
parsed = qasm3.load(tmp_path)
expected = QuantumCircuit(QuantumRegister(2, "qr"), ClassicalRegister(2, "cr"))
expected.h(0)
expected.cx(0, 1)
expected.measure(0, 0)
expected.measure(1, 1)
self.assertEqual(parsed, expected)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
https://github.com/pedroripper/qiskit_tutoriais
|
pedroripper
|
# Importando módulos
from qiskit import *
from qiskit.tools.visualization import plot_histogram
# Inicializando o circuito
nQubits = 2
nBits = 2
circuitoQuantico = QuantumCircuit(nQubits, nBits)
# Para aplicar uma porta no circuito devemos seguir o seguinte exemplo onde aplicamos uma Hadamard Gate
circuitoQuantico.h(0)
# Nesse exemplo h() é a função que usamos para aplicar uma Hadamard Gate e o argumento é o índice do qubit
# onde se deseja aplica a porta
# Podemos ver ao chamar draw() que a Hadamard Gate fica no qubit desejado
circuitoQuantico.draw(output = 'mpl')
# Podemos aplicar também portas que envolvem mais de um qubit, como a CNOT(Controlled NOT) Gate
circuitoQuantico.cx(0,1)
# Visualização do circuito após chamar a CNOT Gate
circuitoQuantico.draw(output = 'mpl')
# Agora podemos medir esses qubits após as operações chamando measure()
circuitoQuantico.measure(0,0)
circuitoQuantico.measure(1,1)
# Visualização do circuito após chamar measure()
circuitoQuantico.draw(output = 'mpl')
# Para simular um circuito quântico usamos um elemento do Qiskit chamado Aer, que tem como
# uma de suas funções a simulação de circuitos
simulador = Aer.get_backend('qasm_simulator')
# Para executar o circuito chamamos execute() que leva como argumento o circuito a ser executado e o
# backend(aonde o circuito vai ser executado) que nesse caso é no simulador do Aer
resultado = execute(circuitoQuantico, backend = simulador).result()
# Usamos a variável resultado para guardar os dados do resultado
# Para exibir os resultados chamamos plot_histogram()
plot_histogram(resultado.get_counts(circuitoQuantico))
# Antes de tudo é necessário imp
|
https://github.com/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
|
Keerthiraj-Nagaraj
|
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute
from qiskit.visualization import plot_bloch_multivector
# If you run this code outside IBM Quantum Experience,
# run the following commands to store your API token locally.
# Please refer https://qiskit.org/documentation/install.html#access-ibm-quantum-systems
# IBMQ.save_account('MY_API_TOKEN')
# Loading your IBM Q account(s)
IBMQ.load_account()
# Let's do an X-gate on a |0> qubit
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.x(q[0])
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result().get_statevector(qc, decimals=3)
plot_bloch_multivector(result)
# Let's do an H-gate on a |0> qubit
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q[0])
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result().get_statevector(qc, decimals=3)
plot_bloch_multivector(result)
# Let's do an Z-gate on |+>
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q[0])
qc.z(q[0])
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result().get_statevector(qc, decimals=3)
print(result)
plot_bloch_multivector(result)
# Let's do an CX-gate on |00>
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cx(q[0],q[1])
qc.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result().get_statevector(qc, decimals=3)
print(result)
plot_bloch_multivector(result)
# Let's do an CZ-gate on |00>
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cz(q[0],q[1])
qc.draw(output='mpl')
# Let's make CZ-gate with CX-gate and H-gate
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.h(q[1])
qc.cx(q[0],q[1])
qc.h(q[1])
qc.draw(output='mpl')
# Let's do an CCX-gate on |00>
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.ccx(q[0],q[1],q[2])
qc.draw(output='mpl')
# Create a Quantum Circuit with 1 quantum register and 1 classical register
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.x(q[0])
qc.measure(q[0], c[0]) # Map the quantum measurement to the classical bits
qc.draw(output='mpl')
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.ccx(q[0], q[1], q[2])
qc.measure(q[2], c[0])
qc.draw(output='mpl')
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.ccx(q[0], q[1], q[2])
qc.x(q[2])
qc.measure(q[2], c[0])
qc.draw(output='mpl')
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.cx(q[1], q[2])
qc.cx(q[0], q[2])
qc.ccx(q[0], q[1], q[2])
qc.measure(q[2], c[0])
qc.draw(output='mpl')
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.cx(q[1], q[2])
qc.cx(q[0], q[2])
qc.measure(q[2], c[0])
qc.draw(output='mpl')
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
qc.cx(q[1], q[2])
qc.cx(q[0], q[2])
qc.ccx(q[0], q[1], q[2])
qc.x(q[2])
qc.measure(q[2], c[0])
qc.draw(output='mpl')
#Define registers and a quantum circuit
q = QuantumRegister(4)
c = ClassicalRegister(2)
qc = QuantumCircuit(q,c)
#XOR
qc.cx(q[1], q[2])
qc.cx(q[0], q[2])
qc.barrier()
#AND
qc.ccx(q[0], q[1], q[3])
qc.barrier()
#Sum
qc.measure(q[2], c[0])
#Carry out
qc.measure(q[3], c[1])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
result = job.result()
count =result.get_counts()
print(count)
qc.draw(output='mpl')
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer, execute
from qiskit.quantum_info import Pauli, state_fidelity, process_fidelity
q = QuantumRegister(4, 'q0')
c = ClassicalRegister(1, 'c0')
qc = QuantumCircuit(q, c)
qc.ccx(q[0], q[1], q[2])
qc.cx(q[3], q[1])
qc.h(q[3])
qc.ccx(q[3], q[2], q[1])
qc.measure(q[3],c[0])
qc.draw(output='mpl')
qc.count_ops()
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
pass_ = Unroller(['u3', 'cx'])
pm = PassManager(pass_)
new_circuit = pm.run(qc)
new_circuit.draw(output='mpl')
new_circuit.count_ops()
q = QuantumRegister(3, 'q0')
c = ClassicalRegister(1, 'c0')
qc = QuantumCircuit(q, c)
qc.ccx(q[0], q[1], q[2])
qc.draw(output='mpl')
pass_ = Unroller(['u3', 'cx'])
pm = PassManager(pass_)
new_circuit = pm.run(qc)
new_circuit.draw(output='mpl')
new_circuit.count_ops()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute
##### build your quantum circuit here
q = QuantumRegister(8, 'q')
c = ClassicalRegister(2, 'c')
qc = QuantumCircuit(q,c)
qc.x(q[0]) #input 1
#qc.x(q[1]) #input 1
qc.x(q[2]) #input 1
qc.cx(q[2],q[3])
qc.cx(q[1], q[3]) # B XOR X
qc.cx(q[3], q[4])
qc.cx(q[0], q[4]) #4 will be my sum - B XOR X XOR A
qc.ccx(q[0], q[3], q[5]) # A AND (B XOR X)
qc.ccx(q[1], q[2], q[6]) # BX
qc.cx(q[6], q[7])
qc.cx(q[5], q[7])
qc.ccx(q[5], q[6], q[7]) # BX AND A(B XOR X)
qc.measure(q[4],c[0]) # SUM - B XOR X XOR A
qc.measure(q[7],c[1]) # Carry Out - BX OR A(B XOR X)
# execute the circuit by qasm_simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
result = job.result()
count =result.get_counts()
print(count)
qc.draw(output='mpl')
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute
##### build your quantum circuit here
q = QuantumRegister(6, 'q')
c = ClassicalRegister(2, 'c')
qc = QuantumCircuit(q,c)
qc.x(q[0]) #input 1
#qc.x(q[1]) #input 1
qc.x(q[2]) #input 1
qc.ccx(q[1], q[2],q[3]) # BX
qc.cx(q[1], q[2]) # B XOR X
qc.ccx(q[0], q[2], q[4]) # A(B XOR X)
qc.cx(q[0], q[2]) #2 will be my sum - B XOR X XOR A
qc.cx(q[4], q[5])
qc.cx(q[3], q[5])
qc.ccx(q[3], q[4], q[5]) # BX OR A(B XOR X)
qc.measure(q[2],c[0]) # SUM - B XOR X XOR A
qc.measure(q[5],c[1]) # Carry Out - BX OR A(B XOR X)
# execute the circuit by qasm_simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
result = job.result()
count =result.get_counts()
print(count)
qc.draw(output='mpl')
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute
##### build your quantum circuit here
q = QuantumRegister(6, 'q')
c = ClassicalRegister(2, 'c')
qc = QuantumCircuit(q,c)
qc.x(q[0]) #input 1
#qc.x(q[1]) #input 1
qc.x(q[2]) #input 1
qc.ccx(q[1], q[2],q[3]) # BX
qc.cx(q[1], q[2]) # B XOR X
qc.ccx(q[0], q[2], q[4]) # A(B XOR X)
qc.cx(q[0], q[2]) #2 will be my sum - B XOR X XOR A
qc.measure(q[2],c[0]) # SUM - B XOR X XOR A
qc.x(q[3])
qc.x(q[4])
qc.ccx(q[3], q[4], q[5])
qc.x(q[5])# BX OR A(B XOR X)
qc.measure(q[5],c[1]) # Carry Out - BX OR A(B XOR X)
# execute the circuit by qasm_simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
result = job.result()
count =result.get_counts()
print(count)
qc.draw(output='mpl')
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute
##### build your quantum circuit here
q = QuantumRegister(4, 'q')
c = ClassicalRegister(2, 'c')
qc = QuantumCircuit(q,c)
qc.x(q[0]) #input 1
#qc.x(q[1]) #input 1
qc.x(q[2]) #input 1
qc.ccx(q[1], q[2],q[3]) # BX
qc.cx(q[1], q[2]) # B XOR X
qc.ccx(q[0], q[2], q[3]) # A(B XOR X)
qc.cx(q[0], q[2]) #2 will be my sum - A XOR B XOR X
qc.measure(q[2],c[0]) # SUM - B XOR X XOR A
qc.measure(q[3],c[1]) # Carry Out - BX OR A(B XOR X)
# execute the circuit by qasm_simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
result = job.result()
count =result.get_counts()
print(count)
qc.draw(output='mpl')
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
pass_ = Unroller(['u3', 'cx'])
pm = PassManager(pass_)
new_circuit = pm.run(qc)
#new_circuit.draw(output='mpl')
new_circuit.count_ops()
# Check your answer using following code
from qc_grader import grade_ex1a
grade_ex1a(qc)
# Submit your answer. You can re-submit at any time.
from qc_grader import submit_ex1a
submit_ex1a(qc)
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
secret_unitary = 'hz'
# make the imports that are necessary for our work
import qiskit as qk
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute, Aer
from qiskit import IBMQ
from qiskit.tools.visualization import plot_histogram
# simple function that applies a series of unitary gates from a given string
def apply_secret_unitary(secret_unitary, qubit, quantum_circuit, dagger):
functionmap = {
'x':quantum_circuit.x,
'y':quantum_circuit.y,
'z':quantum_circuit.z,
'h':quantum_circuit.h,
't':quantum_circuit.t,
}
if dagger: functionmap['t'] = quantum_circuit.tdg
if dagger:
[functionmap[unitary](qubit) for unitary in secret_unitary]
else:
[functionmap[unitary](qubit) for unitary in secret_unitary[::-1]]
# Create the quantum circuit
q = QuantumRegister(3)
c = ClassicalRegister(3)
qc = QuantumCircuit(q, c)
''' Qubit ordering as follows (classical registers will just contain measured values of the corresponding qubits):
q[0]: qubit to be teleported (Alice's first qubit. It was given to her after the application of a secret unitary
which she doesn't know)
q[1]: Alice's second qubit
q[2]: Bob's qubit, which will be the destination for the teleportation
'''
# Apply the secret unitary that we are using to generate the state to teleport. You can change it to any unitary
apply_secret_unitary(secret_unitary, q[0], qc, dagger = 0)
qc.barrier()
# Next, generate the entangled pair between Alice and Bob (Remember: Hadamard followed by CX generates a Bell pair)
qc.h(q[1])
qc.cx(q[1], q[2])
qc.barrier()
# Next, apply the teleportation protocol.
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
qc.cx(q[1], q[2])
qc.cz(q[0], q[2])
qc.barrier()
'''
In principle, if the teleportation protocol worked, we have q[2] = secret_unitary|0>
As a result, we should be able to recover q[2] = |0> by applying the reverse of secret_unitary
since for a unitary u, u^dagger u = I.
'''
apply_secret_unitary(secret_unitary, q[2], qc, dagger=1)
qc.measure(q[2], c[2])
qc.draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend, shots=1024)
sim_result = job_sim.result()
measurement_result = sim_result.get_counts(qc)
print(measurement_result)
plot_histogram(measurement_result)
# First, see what devices we are allowed to use by loading our saved accounts
IBMQ.load_account()
IBMQ.get_provider(hub='ibm-q')
provider.backends()
# get the least-busy backend at IBM and run the quantum circuit there
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(simulator=False))
job_exp = execute(qc, backend=backend, shots=8192)
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(qc)
print(exp_measurement_result)
plot_histogram(exp_measurement_result)
error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \
* 100./ sum(list(exp_measurement_result.values()))
print("The experimental error rate : ", error_rate_percent, "%")
|
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/BryceFuller/qiskit_camp
|
BryceFuller
|
%matplotlib inline
import sys
sys.path.append("..")
import compress
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
import numpy as np
from functools import partial
from qiskit.aqua.components.optimizers import SPSA
from multideterminant_prep import PrepareMultiDeterminantState as pmds
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('pylab', 'inline')
pylab.rcParams['figure.figsize'] = (12, 6)
pylab.rcParams.update({'font.size': 10})
in_strings = ["101", "011", "110"]
in_weights = [4, 7, 2]
circuit = pmds(in_weights, in_strings)
circuit.draw(scale=0.5, style={'fold':100}, output='mpl')
# Configuration
n_shots = 1000
n_trials = 300
n_layers = 3
n_params = circuit.width() * n_layers * 3
# Build variable bounds
variable_bounds_single = (0., 2*np.pi)
variable_bounds = [variable_bounds_single] * n_params
initial_point = np.random.uniform(low=variable_bounds_single[0],
high=variable_bounds_single[1],
size=(n_params,)).tolist()
circuit.draw(scale=0.5, style={'fold':100}, output='mpl')
print("Circuit has a depth of: {}".format(circuit.depth()))
final_circuit = compress.swap_test_with_compression_model(circuit, initial_point)
final_circuit.draw(scale=0.5, style={'fold':100}, output='mpl')
results = compress.cross_validate_qnn_depth(circuit, n_shots, n_trials, n_layers, run=0)
results
sns.lineplot(x='iteration', y='fidelity', data=results.fidelity.to_dataframe().reset_index())
plt.title("Fidelity improvement with optimiser iterations")
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
from qiskit import *
from qiskit.quantum_info import Statevector
from parser import QSerializer
from SocketChannel import SocketChannel
class Channel:
def __init__(self):
#self._is_master = is_master
self._master_qargs_list = None
self._master_cargs_list = None
self._slave_qargs_list = None
self._slave_cargs_list = None
self._circuit = None
def receive(self,circuit):
print('Wait to receive')
channel = SocketChannel(port=5005, listen=True)
data = channel.receive()
print("received data:", data)
channel.close()
#From Marc
ser2 = parser.QSerializer()
ser2.decode(data)
recieve_channel = ser2.get_element('channel_class')
self._slave_offset = recieve_channel._slave_offset
if(recieve_channel._master):
self._master = False
self._offset = self._slave_offset
new_circuit = QuantumCircuit(len(recieve_channel._state_vector.dims()))
new_circuit.initialize(recieve_channel._state_vector.data, range(len(recieve_channel._state_vector.dims())))
new_circuit = transpile(new_circuit, basis_gates=self._basis_gates)
return new_circuit, self._offset
def append(self, is_master instruction, qargs=None, cargs=None):
if is_master:
for restricted_qarg in self._slave_qargs_list:
if restricted_qarg is in qargs:
print("Master is trying to access Slave's qarg: %d".format(restricted_qarg))
return -1
for restricted_carg in self._slave_cargs_list:
if restricted_carg is in cargs:
print("Master is trying to access Slave's carg: %d".format(restricted_carg))
return -1
else: ## is_slave
for restricted_qarg in self._master_qargs_list:
if restricted_qarg is in qargs:
print("Slave is trying to access Master's qarg: %d".format(restricted_qarg))
return -1
for restricted_carg in self._master_cargs_list:
if restricted_carg is in cargs:
print("Slave is trying to access Master's carg: %d".format(restricted_carg))
return -1
## Allowed access
return self._circuit.append(instruction, qargs, cargs)
def
# self._state_vector = None
# self._arr_qubits = None
# self._basis_gates = ['u1', 'u2', 'u3', 'cx','x','y','H','z']
# self._master = True
# self._offset = 0
# self._slave_offset = slave_offset
def send(self,circuit,arr_qubits):
self._state_vector = Statevector.from_instruction(circuit)
self._arr_qubits = arr_qubits
#From Marc
ser = QSerializer()
ser.add_element('channel_class', self)
str_to_send = ser.encode()
#print(str_to_send.type())
#From Luca
message = str_to_send
TCP_IP = '127.0.0.1'
channel = SocketChannel()
channel.connect(TCP_IP, 5005)
channel.send(message)
channel.close()
## TODO: TCP THINGS
return self
def receive(self,circuit):#,recieve_channel): ## TODO: remove recieve as an input
#TODO: TCP things
#recieve_channel = TCP_STUFF
#From Luca
print('Wait to receive')
channel = SocketChannel(port=5005, listen=True)
data = channel.receive()
print("received data:", data)
channel.close()
#From Marc
ser2 = QSerializer()
ser2.decode(data)
recieve_channel = ser2.get_element('channel_class')
self._slave_offset = recieve_channel._slave_offset
if(recieve_channel._master):
self._master = False
self._offset = self._slave_offset
new_circuit = QuantumCircuit(len(recieve_channel._state_vector.dims()))
new_circuit.initialize(recieve_channel._state_vector.data, range(len(recieve_channel._state_vector.dims())))
new_circuit = transpile(new_circuit, basis_gates=self._basis_gates)
return new_circuit, self._offset
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from qiskit.algorithms.optimizers import SLSQP
from qiskit.circuit.library import TwoLocal
from qiskit.extensions import UnitaryGate
from weylchamber import canonical_gate
gate = UnitaryGate(canonical_gate(0.5, 0.25, 0.25).full())
# gate ='cx'
num_qubits = 2
ansatz = TwoLocal(num_qubits, ["ry", "rz"], gate)
optimizer = SLSQP(maxiter=1000)
ansatz.decompose().draw("mpl", style="iqx")
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit.algorithms.minimum_eigensolvers import VQE
vqe = VQE(estimator, ansatz, optimizer)
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
result = vqe.compute_minimum_eigenvalue(H2_op)
print(result)
|
https://github.com/electricalgorithm/BernsteinVaziraniAlgorithm
|
electricalgorithm
|
"""
This module implements the Bernstein-Vazirani Algorithm.
"""
from qiskit import Aer
from qiskit import QuantumCircuit, assemble, transpile
from qiskit.circuit.instruction import Instruction
class BVAlgorithm:
"""This class implements the Bernstein-Vazirani Algorithm."""
@staticmethod
def create_oracle_from_number(number: int) -> Instruction:
"""This method returns a Oracle block which will be used in
the Bernstein-Vazirani Algorithm.
Parameters
----------
number_str : str
The number in binary form as string.
Returns
-------
Instruction
Oracle block to be fed into the algorithm.
"""
# Convert the integer into binary string.
number_str = format(number, "b")
inputs_count = len(number_str)
# Create a quantum circuit with the number of input qubits + 1 output qubit.
oracle = QuantumCircuit(inputs_count + 1, inputs_count)
# Apply the CNOTs to the inputs as "1"s.
for index, qubit in enumerate(reversed(number_str)):
if qubit == "1":
oracle.cx(index, inputs_count)
inst = oracle.to_instruction()
inst.name = "SecretNumberOracle"
return inst
@staticmethod
def simulate(secret_number_oracle: Instruction) -> dict:
"""_summary_
Parameters
----------
secret_no_oracle : Instruction
The secret number to look for with the algoritm.
Returns
-------
dict
A dictionary with result attribute which is the found number.
"""
# Create the circuit.
circuit = BVAlgorithm._construct_the_circuit(secret_number_oracle)
# Run the simulation.
aer_sim = Aer.get_backend("aer_simulator")
transpiled_dj_circuit = transpile(circuit, aer_sim)
qobj = assemble(transpiled_dj_circuit)
results = aer_sim.run(qobj).result()
# Get the answer.
answer = results.get_counts()
answer_as_list = list(answer.keys())
answer_int = int(answer_as_list[0], 2)
return {"result": answer_int}
@staticmethod
def _construct_the_circuit(function_block: QuantumCircuit) -> QuantumCircuit:
"""It creates the circuit for the Bernstein-Vazirani Algorithm.
Parameters
----------
function_block : QuantumCircuit
The secret number block to check with the Bernstein-Vazirani Algorithm.
Returns
-------
QuantumCircuit
The circuit for the Bernstein-Vazirani Algorithm.
"""
# Get the number of input qubits.
input_length = function_block.num_qubits - 1
_circuit = QuantumCircuit(input_length + 1, input_length)
# Apply Hadamard gates to all input qubits.
for qubit in range(input_length):
_circuit.h(qubit)
# Convert the last qubit to |-) state.
_circuit.x(input_length)
_circuit.h(input_length)
_circuit.barrier()
# Apply the oracle block.
_circuit.append(
function_block,
range(function_block.num_qubits),
range(function_block.num_clbits),
)
_circuit.barrier()
# Apply Hadamard gates to all input qubits.
for qubit in range(input_length):
_circuit.h(qubit)
_circuit.barrier()
# Measure all input qubits and put them to classical bits.
for qubit in range(input_length):
_circuit.measure(qubit, qubit)
return _circuit
if __name__ == "__main__":
print("========================================")
print("Bernstein-Vazirani Algorithm Simulation")
print("========================================")
# Get the number of input qubits.
secret_number = int(input("> Enter the secret number to search for: "))
# Get the oracle block.
block_to_test = BVAlgorithm.create_oracle_from_number(secret_number)
# Run the algorithm.
result = BVAlgorithm.simulate(block_to_test)
print(f"Result: {result['result']}")
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import itertools
import math
import sys
import ddt
import qiskit.qasm2
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestSimple(QiskitTestCase):
def test_unary_constants(self):
program = "qreg q[1]; U(-(0.5 + 0.5), +(+1 - 2), -+-+2) q[0];"
parsed = qiskit.qasm2.loads(program)
expected = [-1.0, -1.0, 2.0]
self.assertEqual(list(parsed.data[0].operation.params), expected)
def test_unary_symbolic(self):
program = """
gate u(a, b, c) q {
U(-(a + a), +(+b - c), -+-+c) q;
}
qreg q[1];
u(0.5, 1.0, 2.0) q[0];
"""
parsed = qiskit.qasm2.loads(program)
expected = [-1.0, -1.0, 2.0]
actual = [float(x) for x in parsed.data[0].operation.definition.data[0].operation.params]
self.assertEqual(list(actual), expected)
@ddt.data(
("+", lambda a, b: a + b),
("-", lambda a, b: a - b),
("*", lambda a, b: a * b),
("/", lambda a, b: a / b),
("^", lambda a, b: a**b),
)
@ddt.unpack
def test_binary_constants(self, str_op, py_op):
program = f"qreg q[1]; U(0.25{str_op}0.5, 1.0{str_op}0.5, 3.2{str_op}-0.8) q[0];"
parsed = qiskit.qasm2.loads(program)
expected = [py_op(0.25, 0.5), py_op(1.0, 0.5), py_op(3.2, -0.8)]
# These should be bit-for-bit exact.
self.assertEqual(list(parsed.data[0].operation.params), expected)
@ddt.data(
("+", lambda a, b: a + b),
("-", lambda a, b: a - b),
("*", lambda a, b: a * b),
("/", lambda a, b: a / b),
("^", lambda a, b: a**b),
)
@ddt.unpack
def test_binary_symbolic(self, str_op, py_op):
program = f"""
gate u(a, b, c) q {{
U(a {str_op} b, a {str_op} (b {str_op} c), 0.0) q;
}}
qreg q[1];
u(1.0, 2.0, 3.0) q[0];
"""
parsed = qiskit.qasm2.loads(program)
outer = [1.0, 2.0, 3.0]
abstract_op = parsed.data[0].operation
self.assertEqual(list(abstract_op.params), outer)
expected = [py_op(1.0, 2.0), py_op(1.0, py_op(2.0, 3.0)), 0.0]
actual = [float(x) for x in abstract_op.definition.data[0].operation.params]
self.assertEqual(list(actual), expected)
@ddt.data(
("cos", math.cos),
("exp", math.exp),
("ln", math.log),
("sin", math.sin),
("sqrt", math.sqrt),
("tan", math.tan),
)
@ddt.unpack
def test_function_constants(self, function_str, function_py):
program = f"qreg q[1]; U({function_str}(0.5),{function_str}(1.0),{function_str}(pi)) q[0];"
parsed = qiskit.qasm2.loads(program)
expected = [function_py(0.5), function_py(1.0), function_py(math.pi)]
# These should be bit-for-bit exact.
self.assertEqual(list(parsed.data[0].operation.params), expected)
@ddt.data(
("cos", math.cos),
("exp", math.exp),
("ln", math.log),
("sin", math.sin),
("sqrt", math.sqrt),
("tan", math.tan),
)
@ddt.unpack
def test_function_symbolic(self, function_str, function_py):
program = f"""
gate u(a, b, c) q {{
U({function_str}(a), {function_str}(b), {function_str}(c)) q;
}}
qreg q[1];
u(0.5, 1.0, pi) q[0];
"""
parsed = qiskit.qasm2.loads(program)
outer = [0.5, 1.0, math.pi]
abstract_op = parsed.data[0].operation
self.assertEqual(list(abstract_op.params), outer)
expected = [function_py(x) for x in outer]
actual = [float(x) for x in abstract_op.definition.data[0].operation.params]
self.assertEqual(list(actual), expected)
class TestPrecedenceAssociativity(QiskitTestCase):
def test_precedence(self):
# OQ3's precedence rules are the same as Python's, so we can effectively just eval.
expr = " 1.0 + 2.0 * -3.0 ^ 1.5 - 0.5 / +0.25"
expected = 1.0 + 2.0 * -(3.0**1.5) - 0.5 / +0.25
program = f"qreg q[1]; U({expr}, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(parsed.data[0].operation.params[0], expected)
def test_addition_left(self):
# `eps` is the smallest floating-point value such that `1 + eps != 1`. That means that if
# addition is correctly parsed and resolved as left-associative, then the first parameter
# should first calculate `1 + (eps / 2)`, which will be 1, and then the same again, whereas
# the second will do `(eps / 2) + (eps / 2) = eps`, then `eps + 1` will be different.
eps = sys.float_info.epsilon
program = f"qreg q[1]; U(1 + {eps / 2} + {eps / 2}, {eps / 2} + {eps / 2} + 1, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertNotEqual(1.0 + eps, 1.0) # Sanity check for the test.
self.assertEqual(list(parsed.data[0].operation.params), [1.0, 1.0 + eps, 0.0])
def test_multiplication_left(self):
# A similar principle to the epsilon test for addition; if multiplication associates right,
# then `(0.5 * 2.0 * fmax)` is `inf`, otherwise it's `fmax`.
fmax = sys.float_info.max
program = f"qreg q[1]; U({fmax} * 0.5 * 2.0, 2.0 * 0.5 * {fmax}, 2.0 * {fmax} * 0.5) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [fmax, fmax, math.inf])
def test_subtraction_left(self):
# If subtraction associated right, we'd accidentally get 2.
program = "qreg q[1]; U(2.0 - 1.0 - 1.0, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [0.0, 0.0, 0.0])
def test_division_left(self):
# If division associated right, we'd accidentally get 4.
program = "qreg q[1]; U(4.0 / 2.0 / 2.0, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [1.0, 0.0, 0.0])
def test_power_right(self):
# If the power operator associated left, we'd accidentally get 64 instead.
program = "qreg q[1]; U(2.0 ^ 3.0 ^ 2.0, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [512.0, 0.0, 0.0])
class TestCustomClassical(QiskitTestCase):
def test_evaluation_order(self):
"""We should be evaluating all functions, including custom user ones the exact number of
times we expect, and left-to-right in parameter lists."""
# pylint: disable=invalid-name
order = itertools.count()
def f():
return next(order)
program = """
qreg q[1];
U(f(), 2 * f() + f(), atan2(f(), f()) - f()) q[0];
"""
parsed = qiskit.qasm2.loads(
program,
custom_classical=[
qiskit.qasm2.CustomClassical("f", 0, f),
qiskit.qasm2.CustomClassical("atan2", 2, math.atan2),
],
)
self.assertEqual(
list(parsed.data[0].operation.params), [0, 2 * 1 + 2, math.atan2(3, 4) - 5]
)
self.assertEqual(next(order), 6)
@ddt.ddt
class TestErrors(QiskitTestCase):
@ddt.data("0.0", "(1.0 - 1.0)")
def test_refuses_to_divide_by_zero(self, denom):
program = f"qreg q[1]; U(2.0 / {denom}, 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"):
qiskit.qasm2.loads(program)
program = f"gate rx(a) q {{ U(a / {denom}, 0.0, 0.0) q; }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"):
qiskit.qasm2.loads(program)
@ddt.data("0.0", "1.0 - 1.0", "-2.0", "2.0 - 3.0")
def test_refuses_to_ln_non_positive(self, operand):
program = f"qreg q[1]; U(ln({operand}), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"):
qiskit.qasm2.loads(program)
program = f"gate rx(a) q {{ U(a + ln({operand}), 0.0, 0.0) q; }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"):
qiskit.qasm2.loads(program)
@ddt.data("-2.0", "2.0 - 3.0")
def test_refuses_to_sqrt_negative(self, operand):
program = f"qreg q[1]; U(sqrt({operand}), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"):
qiskit.qasm2.loads(program)
program = f"gate rx(a) q {{ U(a + sqrt({operand}), 0.0, 0.0) q; }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"):
qiskit.qasm2.loads(program)
@ddt.data("*", "/", "^")
def test_cannot_use_nonunary_operators_in_unary_position(self, operator):
program = f"qreg q[1]; U({operator}1.0, 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not a valid unary operator"):
qiskit.qasm2.loads(program)
@ddt.data("+", "-", "*", "/", "^")
def test_missing_binary_operand_errors(self, operator):
program = f"qreg q[1]; U(1.0 {operator}, 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"):
qiskit.qasm2.loads(program)
program = f"qreg q[1]; U((1.0 {operator}), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"):
qiskit.qasm2.loads(program)
def test_parenthesis_must_be_closed(self):
program = "qreg q[1]; U((1 + 1 2), 3, 2) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed a closing parenthesis"):
qiskit.qasm2.loads(program)
def test_premature_right_parenthesis(self):
program = "qreg q[1]; U(sin(), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "did not find an .* expression"):
qiskit.qasm2.loads(program)
|
https://github.com/qiskit-community/prototype-quantum-kernel-training
|
qiskit-community
|
# pylint: disable=import-error, wrong-import-position, too-few-public-methods, no-self-use, function-redefined
from functools import partial
from typing import Sequence
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
# Import Qiskit packages
from qiskit.circuit.library import ZZFeatureMap
from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel
from qiskit_machine_learning.utils.loss_functions import KernelLoss
feature_map = ZZFeatureMap(3)
user_params = [feature_map.parameters[1]]
qkernel = TrainableFidelityQuantumKernel(
feature_map=feature_map,
training_parameters=user_params,
)
X_train = [[0.6, 0.2], [0.5, 0.3], [0.3, 0.7], [0.1, 0.5]]
y_train = np.array([0, 0, 1, 1])
class CustomKernelLoss(KernelLoss):
"""Example Kernel Loss class"""
def __init__(self, **kwargs):
self.kwargs = kwargs
# Evaluate the Loss of a trainable quantum kernel
# at a particular setting of user_param_values on
# a particular dataset.
def evaluate(
self,
parameter_values: Sequence[float],
quantum_kernel: TrainableFidelityQuantumKernel,
data: np.ndarray,
labels: np.ndarray,
):
# Bind the user parameter values
quantum_kernel.assign_training_parameters(parameter_values)
kernel_matrix = quantum_kernel.evaluate(data)
return labels.T @ kernel_matrix @ labels
# Wrap our evaluate method so to produce a callable
# which maps user_param_values to loss scores.
def get_variational_callable(
self,
quantum_kernel: TrainableFidelityQuantumKernel,
data: np.ndarray,
labels: np.ndarray,
):
return partial(
self.evaluate, quantum_kernel=quantum_kernel, data=data, labels=labels
)
kernel_loss = CustomKernelLoss().get_variational_callable(qkernel, X_train, y_train)
print(kernel_loss([0.75]))
NUM_GRID_POINTS = 100
loss_values = [kernel_loss([val]) for val in np.linspace(0, 2 * np.pi, NUM_GRID_POINTS)]
plt.rcParams["font.size"] = 15
plt.figure(figsize=(8, 4))
plt.plot(np.linspace(0, 2 * np.pi, NUM_GRID_POINTS), loss_values)
plt.xlabel("θ")
plt.ylabel("Kernel Loss")
plt.show()
def kernel_loss_full(training_param_values, kernel, data, labels):
kernel.assign_training_parameters(training_param_values)
kernel_matrix = kernel.evaluate(data)
return labels.T @ kernel_matrix @ labels
kernel_loss = partial(kernel_loss_full, kernel=qkernel, data=X_train, labels=y_train)
print(kernel_loss([0.75]))
#import qiskit.tools.jupyter
#
#%qiskit_version_table
#%qiskit_copyright
|
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
|
ronitd2002
|
# please create a 3 qubit GHZ circuit
# please create a 2 qubit ch gate with only cx and ry gate
# Enter your prompt here - Delete this line
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer
from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram, plot_state_qsphere
from qiskit.quantum_info import Statevector, partial_trace
import random
import numpy as np
import matplotlib
backend_statevector = BasicAer.get_backend('statevector_simulator')# This backend executes a single shot of a Qiskit QuantumCircuit and returns the final quantum statevector of the simulation.
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
backend_qasm = BasicAer.get_backend('qasm_simulator')# This backend is designed to mimic an actual device.
#It executes a Qiskit QuantumCircuit and returns a count dictionary containing the final values of any classical registers in the circuit.
shots = 1024 #Number of individual shots
qreg = QuantumRegister(2)
registerBell = ClassicalRegister(2)
qBell = QuantumCircuit(qreg,registerBell )
qBell.h(0)
qBell.cx(0,1)
qBell.draw(output='mpl', style=style)
out_vectorBell = execute(qBell, backend_statevector).result().get_statevector()
plot_state_qsphere(out_vectorBell)
qBell.measure(qreg[0],registerBell [0])
qBell.measure(qreg[1],registerBell [1])
qBell.draw(output='mpl', style=style)
results = execute(qBell, backend=backend_qasm, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
def gate_errorX():
############################################################
# This function will return ['X'] with a probability 0.2 #
# ['Z'] with a probability 0.2 #
# and ['I'] with a probability 0.6 #
##########################################################
random_gate = random.choices(population= ['Z', 'X', 'I'],weights=[0.2,0.2, 0.6],k=1)
return(random_gate)
def noise(qcirc):
if gate_errorX() == ['X']:
### Bit-flip in the qubit 0 #####
qcirc.x(0)
elif gate_errorX() == ['Z']:
### phase-flip in the qubit 0 #####
qcirc.z(0)
else:
qcirc.i(0)
if gate_errorX() == ['X']:
### Bit-flip in the qubit 1 #####
qcirc.x(1)
elif gate_errorX() == ['Z']:
### phase-flip in the qubit 0 #####
qcirc.z(1)
else:
qcirc.i(1)
return qcirc
qregNoise = QuantumRegister(2)
registerBellNoise = ClassicalRegister(2)
qBellNoise = QuantumCircuit(qregNoise,registerBellNoise )
qBellNoise.h(0)
qBellNoise.barrier()
noise(qBellNoise)
#qBellNoise.z(0)
qBellNoise.barrier()
qBellNoise.cx(0,1)
qBellNoise.draw(output='mpl', style=style)
out_vectorBellNoise = execute(qBellNoise, backend_statevector).result().get_statevector()
plot_state_qsphere(out_vectorBellNoise)
plot_state_qsphere(out_vectorBell)
qBellNoise.measure(qregNoise[0],registerBellNoise[0])
qBellNoise.measure(qregNoise[1],registerBellNoise[1])
qBellNoise.draw(output='mpl', style=style)
resultsNoise = execute(qBellNoise, backend=backend_qasm, shots=shots).result()
answerNoise = resultsNoise.get_counts()
plot_histogram(answerNoise)
qreg_X1_Noise = QuantumRegister(2)
registerBell_X1_Noise = ClassicalRegister(2)
qBell_X1_Noise = QuantumCircuit(qreg_X1_Noise,registerBell_X1_Noise )
qBell_X1_Noise.h(0)
qBell_X1_Noise.barrier()
#noise(qBellNoise)
qBell_X1_Noise.x(1)
qBell_X1_Noise.barrier()
qBell_X1_Noise.cx(0,1)
qBell_X1_Noise.draw(output='mpl', style=style)
out_vectorBell_X1_Noise = execute(qBell_X1_Noise, backend_statevector).result().get_statevector()
plot_state_qsphere(out_vectorBell_X1_Noise)
Qreg1 = QuantumRegister(1)
Qreg2 = QuantumRegister(2)
qc_bit_flip = QuantumCircuit(Qreg1,Qreg2)
state_to_protect = [np.sqrt(0.2),np.sqrt(0.8)]
qc_bit_flip.initialize(state_to_protect,0) # Apply initialisation operation to the 0th qubit
qc_bit_flip.barrier()
Initial_state = Statevector.from_instruction(qc_bit_flip)
plot_bloch_multivector(Initial_state, title='Initial state')
qc_bit_flip.cx(0,1)
qc_bit_flip.cx(0,2)
qc_bit_flip.draw(output='mpl', style=style)
qc_bit_flip.barrier()
qc_bit_flip.x(0)
qc_bit_flip.barrier()
qc_bit_flip.cx(0,2)
qc_bit_flip.cx(0,1)
qc_bit_flip.barrier()
qc_bit_flip.ccx(2,1,0)
qc_bit_flip.draw(output='mpl', style=style)
out_vector = execute(qc_bit_flip, backend_statevector).result().get_statevector()
plot_bloch_multivector(out_vector, title='Final state')
plot_bloch_multivector(Initial_state, title='Initial state')
qregister1 = QuantumRegister(1)
qregister2 = QuantumRegister(2)
cregister = ClassicalRegister(2, 'c')
qc_bit_flip_measurements = QuantumCircuit(qregister1,qregister2,cregister)
qc_bit_flip_measurements.initialize(state_to_protect,0) # Apply initialisation operation to the 0th qubit
Initial_state1 = Statevector.from_instruction(qc_bit_flip_measurements)
plot_bloch_multivector(Initial_state1, title='Initial state')
### Perfmoing the encoding #####
qc_bit_flip_measurements.barrier()
qc_bit_flip_measurements.cx(0,1)
qc_bit_flip_measurements.cx(0,2)
### Apply some noise #####
qc_bit_flip_measurements.barrier()
#noise(qc)
qc_bit_flip_measurements.x(0)
### Aplying the inverse of the encoding procedure ###
qc_bit_flip_measurements.barrier()
qc_bit_flip_measurements.cx(0,2)
qc_bit_flip_measurements.cx(0,1)
qc_bit_flip_measurements.barrier()
qc_bit_flip_measurements.measure(qregister2,cregister)
qc_bit_flip_measurements.x(0).c_if(cregister, 3)
qc_bit_flip_measurements.draw(output='mpl', style=style)
out_vector1 = execute(qc_bit_flip_measurements, backend_statevector).result().get_statevector()
plot_bloch_multivector(out_vector1, title='Final state')
plot_bloch_multivector(Initial_state1, title='Initial state')
qEncoding = QuantumRegister(3)
qAncillas = QuantumRegister(2, 'ancilla')
AncillasRegister = ClassicalRegister(2, 'c')
qc_bit_flip_ancillas_measuremnts = QuantumCircuit(qEncoding,qAncillas,AncillasRegister)
qc_bit_flip_ancillas_measuremnts.initialize(state_to_protect,0) # Apply initialisation operation to the 0th qubit
Initial_state2 = Statevector.from_instruction(qc_bit_flip_ancillas_measuremnts)
plot_bloch_multivector(Initial_state2, title='Initial state')
### Perfmoing the encoding #####
qc_bit_flip_ancillas_measuremnts.barrier()
qc_bit_flip_ancillas_measuremnts.cx(0,1)
qc_bit_flip_ancillas_measuremnts.cx(0,2)
### Apply some noise #####
qc_bit_flip_ancillas_measuremnts.barrier()
#noise(qc)
qc_bit_flip_ancillas_measuremnts.x(0)
qc_bit_flip_ancillas_measuremnts.barrier()
qc_bit_flip_ancillas_measuremnts.cx(0,4)
qc_bit_flip_ancillas_measuremnts.cx(1,4)
qc_bit_flip_ancillas_measuremnts.barrier()
qc_bit_flip_ancillas_measuremnts.cx(1,3)
qc_bit_flip_ancillas_measuremnts.cx(2,3)
qc_bit_flip_ancillas_measuremnts.barrier()
qc_bit_flip_ancillas_measuremnts.measure(qAncillas,AncillasRegister)
qc_bit_flip_ancillas_measuremnts.x(0).c_if(AncillasRegister, 2)
qc_bit_flip_ancillas_measuremnts.x(1).c_if(AncillasRegister, 3)
qc_bit_flip_ancillas_measuremnts.x(2).c_if(AncillasRegister, 1)
qc_bit_flip_ancillas_measuremnts.barrier()
qc_bit_flip_ancillas_measuremnts.cx(0,2)
qc_bit_flip_ancillas_measuremnts.cx(0,1)
qc_bit_flip_ancillas_measuremnts.draw(output='mpl', style=style)
out_vector2 = execute(qc_bit_flip_ancillas_measuremnts,backend_statevector).result().get_statevector()
plot_bloch_multivector(out_vector2, title='Final state')
plot_bloch_multivector(Initial_state2, title='Initial state')
qregister_to_protect = QuantumRegister(1)
qregister = QuantumRegister(2)
creg = ClassicalRegister(2, 'c')
qc_phase_flip = QuantumCircuit(qregister_to_protect,qregister,creg)
qc_phase_flip.initialize(state_to_protect,0) # Apply initialisation operation to the 0th qubit
Initial_state3 = Statevector.from_instruction(qc_phase_flip)
plot_bloch_multivector(Initial_state3, title='Initial state')
### Perfmoing the encoding #####
qc_phase_flip.barrier()
qc_phase_flip.cx(0,1)
qc_phase_flip.cx(0,2)
### Apply thje hadamard gates #####
qc_phase_flip.barrier()
qc_phase_flip.h(0)
qc_phase_flip.h(1)
qc_phase_flip.h(2)
### Apply some noise #####
qc_phase_flip.barrier()
#noise(qc)
qc_phase_flip.z(0)
qc_phase_flip.barrier()
### Apply thje hadamard gates #####
qc_phase_flip.h(0)
qc_phase_flip.h(1)
qc_phase_flip.h(2)
### Aplying the inverse of the encoding procedure ###
qc_phase_flip.barrier()
qc_phase_flip.cx(0,2)
qc_phase_flip.cx(0,1)
qc_phase_flip.barrier()
qc_phase_flip.measure(qregister,creg)
qc_phase_flip.x(0).c_if(cregister, 3)
qc_phase_flip.draw(output='mpl', style=style)
out_vector4 = execute(qc_phase_flip, backend_statevector).result().get_statevector()
plot_bloch_multivector(out_vector4)
plot_bloch_multivector(Initial_state3, title='Initial state')
qregA = QuantumRegister(1)
qr1 = QuantumRegister(2)
qregB = QuantumRegister(1)
qr2 = QuantumRegister(2)
qregC = QuantumRegister(1)
qr3 = QuantumRegister(2)
r1 = ClassicalRegister(2, 'c1')
r2 = ClassicalRegister(2, 'c2')
r3 = ClassicalRegister(2, 'c3')
registerBC = ClassicalRegister(2, 'c')
qc_shor_code = QuantumCircuit(qregA, qr1,qregB, qr2,qregC,qr3,r1,r2,r3,registerBC)
qc_shor_code.initialize(state_to_protect,0) # Apply initialisation operation to the 0th qubit
qc_shor_code.barrier()
Initial_state4 = Statevector.from_instruction(qc_shor_code)
plot_bloch_multivector(Initial_state4, title='Initial state')
qc_shor_code.cx(0,3)
qc_shor_code.cx(0,6)
qc_shor_code.h(0)
qc_shor_code.h(3)
qc_shor_code.h(6)
qc_shor_code.barrier()
qc_shor_code.cx(0,1)
qc_shor_code.cx(0,2)
qc_shor_code.cx(3,4)
qc_shor_code.cx(3,5)
qc_shor_code.cx(6,7)
qc_shor_code.cx(6,8)
qc_shor_code.draw(output='mpl', style=style)
### Apply some gate error, in this case X y Z gate ###
qc_shor_code.barrier()
qc_shor_code.x(0)
qc_shor_code.z(6)
## This is the saame as the bit-flip code with measurements (Part 3.2) repeated 3 times ##
qc_shor_code.barrier()
qc_shor_code.cx(0,2)
qc_shor_code.cx(0,1)
qc_shor_code.cx(3,5)
qc_shor_code.cx(3,4)
qc_shor_code.cx(6,8)
qc_shor_code.cx(6,7)
qc_shor_code.barrier()
qc_shor_code.measure(qr1,r1)
qc_shor_code.measure(qr2,r2)
qc_shor_code.measure(qr3,r3)
qc_shor_code.x(qregA).c_if(r1, 3)
qc_shor_code.x(qregB).c_if(r2, 3)
qc_shor_code.x(qregC).c_if(r3, 3)
### Aplying the inverse of the encoding procedure ###
qc_shor_code.barrier()
qc_shor_code.h(0)
qc_shor_code.h(3)
qc_shor_code.h(6)
qc_shor_code.cx(0,6)
qc_shor_code.cx(0,3)
qc_shor_code.measure(qregB,registerBC[0])
qc_shor_code.measure(qregC,registerBC[1])
qc_shor_code.x(qregA).c_if(registerBC, 3)
qc_shor_code.draw(output='mpl', style=style, fold= 30)
out_vector5 = execute(qc_shor_code,backend_statevector).result().get_statevector()
plot_bloch_multivector(out_vector5)
reduced_state_shor_code = partial_trace(out_vector5 , [1,2,3,4,5,6,7,8])
plot_bloch_multivector(reduced_state_shor_code)
plot_bloch_multivector(Initial_state4, title='Initial state')
reduced_intial_state_shor_code = partial_trace(Initial_state4 , [1,2,3,4,5,6,7,8])
plot_bloch_multivector(reduced_intial_state_shor_code)
def shor_encoding(qc_shor_encode):
## Encoding for the shor code ##
################################
qc_shor_encode.cx(0,3)
qc_shor_encode.cx(0,6)
qc_shor_encode.h(0)
qc_shor_encode.h(3)
qc_shor_encode.h(6)
qc_shor_encode.barrier()
qc_shor_encode.cx(0,1)
qc_shor_encode.cx(0,2)
qc_shor_encode.cx(3,4)
qc_shor_encode.cx(3,5)
qc_shor_encode.cx(6,7)
qc_shor_encode.cx(6,8)
qc_shor_encode.barrier()
return(qc_shor_encode)
def shor_correct(qc_shor_code_correct,qCorrect_regA, qCorrect_r1,qCorrect_regB, qCorrect_r2,qCorrect_regC,qCorrect_r3,rCorrect1,rCorrect2,rCorrect3,registerCorrectBC ):
## Correction of the error in the shor code ##
##############################################
qc_shor_code_correct.barrier()
qc_shor_code_correct.cx(0,2)
qc_shor_code_correct.cx(0,1)
qc_shor_code_correct.cx(3,5)
qc_shor_code_correct.cx(3,4)
qc_shor_code_correct.cx(6,8)
qc_shor_code_correct.cx(6,7)
qc_shor_code_correct.barrier()
qc_shor_code_correct.measure(qCorrect_r1,rCorrect1)
qc_shor_code_correct.measure(qCorrect_r2,rCorrect2)
qc_shor_code_correct.measure(qCorrect_r3,rCorrect3)
qc_shor_code_correct.x(qCorrect_regA).c_if(rCorrect1, 3)
qc_shor_code_correct.x(qCorrect_regB).c_if(rCorrect2, 3)
qc_shor_code_correct.x(qCorrect_regC).c_if(rCorrect3, 3)
qc_shor_code_correct.barrier()
qc_shor_code_correct.h(0)
qc_shor_code_correct.h(3)
qc_shor_code_correct.h(6)
qc_shor_code_correct.cx(0,6)
qc_shor_code_correct.cx(0,3)
qc_shor_code_correct.measure(qCorrect_regB,registerCorrectBC[0])
qc_shor_code_correct.measure(qCorrect_regC,registerCorrectBC[1])
qc_shor_code_correct.x(qCorrect_regA).c_if(registerCorrectBC, 3)
return(qc_shor_code_correct)
### Ciruit to encode the state for the bit-flip code ####
q_Encoding_bit_flip_reg1 = QuantumRegister(1)
q_Encoding_bit_flip_reg2 = QuantumRegister(2)
qc_Encoding_bit_flip = QuantumCircuit(Qreg1,Qreg2)
qc_Encoding_bit_flip.cx(0,1)
qc_Encoding_bit_flip.cx(0,2)
### Ciruit to correct the state for the bit-flip code ####
qBit_flip_correct_register1 = QuantumRegister(1)
qBit_flip_correct_register2 = QuantumRegister(2)
cBit_flip_correct_register = ClassicalRegister(2, 'c')
qcBit_flip_correct = QuantumCircuit(qBit_flip_correct_register1,qBit_flip_correct_register2,cBit_flip_correct_register)
qcBit_flip_correct.barrier()
qcBit_flip_correct.cx(0,2)
qcBit_flip_correct.cx(0,1)
qcBit_flip_correct.barrier()
qcBit_flip_correct.measure(qBit_flip_correct_register2,cBit_flip_correct_register)
qcBit_flip_correct.x(0).c_if(cBit_flip_correct_register, 3)
qcBit_flip_correct.barrier()
q_To_Protect1 = QuantumRegister(1, name = 'state_to_protect1')
qCorrect_r1 = QuantumRegister(2)
qCorrect_regB = QuantumRegister(1)
qCorrect_r2 = QuantumRegister(2)
qCorrect_regC = QuantumRegister(1)
qCorrect_r3 = QuantumRegister(2)
rCorrect1 = ClassicalRegister(2, 'c1')
rCorrect2 = ClassicalRegister(2, 'c2')
rCorrect3 = ClassicalRegister(2, 'c3')
registerCorrectBC = ClassicalRegister(2, 'c')
q_To_Protect2 = QuantumRegister(1, name = 'state_to_protect2')
qregister_test2 = QuantumRegister(2)
qbell_test = QuantumCircuit(q_To_Protect1, qCorrect_r1,qCorrect_regB, qCorrect_r2,qCorrect_regC,qCorrect_r3,rCorrect1,rCorrect2,rCorrect3,registerCorrectBC, q_To_Protect2, qregister_test2)
qbell_test.h(0)
qbell_test.barrier()
qbell_test.draw(output='mpl', style=style)
shor_encoding(qbell_test)
new_qc1 = qbell_test.compose(qc_Encoding_bit_flip,[9,10,11])
new_qc1.draw(output='mpl', style=style)
new_qc1.barrier()
new_qc1.x(0)
new_qc1.z(9)
new_qc2 = new_qc1.compose(qcBit_flip_correct,[9,10,11])
shor_correct(new_qc2,q_To_Protect1, qCorrect_r1,qCorrect_regB, qCorrect_r2,qCorrect_regC,qCorrect_r3,rCorrect1,rCorrect2,rCorrect3,registerCorrectBC)
new_qc2.barrier()
new_qc2.cx(0,9)
new_qc2.draw(output='mpl', style=style, fold= 42)
out_vector8 = execute(new_qc2,backend_statevector).result().get_statevector()
reduced_state1 = partial_trace(out_vector8 , [1,2,3,4,5,6,7,8,10,11])
plot_state_qsphere(reduced_state1)
q_To_Protect1_ZX = QuantumRegister(1, name = 'state_to_protect1')
qCorrect_r1_ZX = QuantumRegister(2)
qCorrect_regB_ZX = QuantumRegister(1)
qCorrect_r2_ZX = QuantumRegister(2)
qCorrect_regC_ZX = QuantumRegister(1)
qCorrect_r3_ZX = QuantumRegister(2)
rCorrect1_ZX = ClassicalRegister(2, 'c1')
rCorrect2_ZX = ClassicalRegister(2, 'c2')
rCorrect3_ZX = ClassicalRegister(2, 'c3')
registerCorrectBC_ZX = ClassicalRegister(2, 'c')
q_To_Protect2_ZX = QuantumRegister(1, name = 'state_to_protect2')
qregister_test2_ZX = QuantumRegister(2)
qbell_test_ZX = QuantumCircuit(q_To_Protect1_ZX, qCorrect_r1_ZX,qCorrect_regB_ZX, qCorrect_r2_ZX,qCorrect_regC_ZX,qCorrect_r3_ZX,rCorrect1_ZX,rCorrect2_ZX,rCorrect3_ZX,registerCorrectBC_ZX, q_To_Protect2_ZX, qregister_test2_ZX)
qbell_test_ZX.h(0)
qbell_test_ZX.barrier()
shor_encoding(qbell_test_ZX)
new_qc1_ZX = qbell_test_ZX.compose(qc_Encoding_bit_flip,[9,10,11])
#### Error gates ######
new_qc1_ZX.barrier()
new_qc1_ZX.z(0)
new_qc1_ZX.x(9)
new_qc2_ZX = new_qc1_ZX.compose(qcBit_flip_correct,[9,10,11])
shor_correct(new_qc2_ZX,q_To_Protect1_ZX , qCorrect_r1_ZX ,qCorrect_regB_ZX, qCorrect_r2_ZX,qCorrect_regC_ZX,qCorrect_r3_ZX,rCorrect1_ZX,rCorrect2_ZX,rCorrect3_ZX,registerCorrectBC_ZX)
new_qc2_ZX.barrier()
new_qc2_ZX.cx(0,9)
new_qc2_ZX.draw(output='mpl', style=style, fold= 42)
out_vector8 = execute(new_qc2,backend_statevector).result().get_statevector()
reduced_state1 = partial_trace(out_vector8 , [1,2,3,4,5,6,7,8,10,11])
plot_state_qsphere(reduced_state1)
q_To_Protect1_YX = QuantumRegister(1, name = 'state_to_protect1')
qCorrect_r1_YX = QuantumRegister(2)
qCorrect_regB_YX = QuantumRegister(1)
qCorrect_r2_YX = QuantumRegister(2)
qCorrect_regC_YX = QuantumRegister(1)
qCorrect_r3_YX = QuantumRegister(2)
rCorrect1_YX = ClassicalRegister(2, 'c1')
rCorrect2_YX = ClassicalRegister(2, 'c2')
rCorrect3_YX = ClassicalRegister(2, 'c3')
registerCorrectBC_YX = ClassicalRegister(2, 'c')
q_To_Protect2_YX = QuantumRegister(1, name = 'state_to_protect2')
qregister_test2_YX = QuantumRegister(2)
qbell_test_YX = QuantumCircuit(q_To_Protect1_YX, qCorrect_r1_YX,qCorrect_regB_YX, qCorrect_r2_YX,qCorrect_regC_YX,qCorrect_r3_YX,rCorrect1_YX,rCorrect2_YX,rCorrect3_YX,registerCorrectBC_YX, q_To_Protect2_YX, qregister_test2_YX)
qbell_test_YX.h(0)
qbell_test_YX.barrier()
qbell_test_YX.draw(output='mpl', style=style)
shor_encoding(qbell_test_YX)
new_qc1_YX = qbell_test_YX.compose(qc_Encoding_bit_flip,[9,10,11])
#### Error gates ######
new_qc1_YX.barrier()
new_qc1_YX.y(0)
new_qc1_YX.x(9)
new_qc2_YX = new_qc1_YX.compose(qcBit_flip_correct,[9,10,11])
shor_correct(new_qc2_YX,q_To_Protect1_YX , qCorrect_r1_YX ,qCorrect_regB_YX, qCorrect_r2_YX,qCorrect_regC_YX,qCorrect_r3_YX,rCorrect1_YX,rCorrect2_YX,rCorrect3_YX,registerCorrectBC_YX)
new_qc2_YX.barrier()
new_qc2_YX.cx(0,9)
new_qc2_YX.draw(output='mpl', style=style, fold= 42)
out_vector9 = execute(new_qc2_YX,backend_statevector).result().get_statevector()
reduced_state2 = partial_trace(out_vector9 , [1,2,3,4,5,6,7,8,10,11])
plot_state_qsphere(reduced_state2)
def random_error_gate(qcirc):
if gate_errorX() == ['X']:
### Bit-flip in the qubit 0 #####
qcirc.x(0)
elif gate_errorX() == ['Z']:
### phase-flip in the qubit 0 #####
qcirc.z(0)
else:
qcirc.i(0)
if gate_errorX() == ['X']:
### Bit-flip in the qubit 9 #####
qcirc.x(9)
elif gate_errorX() == ['Z']:
### phase-flip in the qubit 9 #####
qcirc.z(9)
else:
qcirc.i(9)
return qcirc
q_To_Protect1_Random = QuantumRegister(1, name = 'state_to_protect1')
qCorrect_r1_Random = QuantumRegister(2)
qCorrect_regB_Random = QuantumRegister(1)
qCorrect_r2_Random = QuantumRegister(2)
qCorrect_regC_Random = QuantumRegister(1)
qCorrect_r3_Random = QuantumRegister(2)
rCorrect1_Random = ClassicalRegister(2, 'c1')
rCorrect2_Random = ClassicalRegister(2, 'c2')
rCorrect3_Random = ClassicalRegister(2, 'c3')
registerCorrectBC_Random = ClassicalRegister(2, 'c')
q_To_Protect2_Random = QuantumRegister(1, name = 'state_to_protect2')
qregister_test2_Random = QuantumRegister(2)
qbell_test_Random = QuantumCircuit(q_To_Protect1_Random, qCorrect_r1_Random,qCorrect_regB_Random, qCorrect_r2_Random,qCorrect_regC_Random,qCorrect_r3_Random,rCorrect1_Random,rCorrect2_Random,rCorrect3_Random,registerCorrectBC_Random, q_To_Protect2_Random, qregister_test2_Random)
qbell_test_Random.h(0)
qbell_test_Random.barrier()
shor_encoding(qbell_test_Random)
new_qc1_Random = qbell_test_Random.compose(qc_Encoding_bit_flip,[9,10,11])
#### Error gates ######
new_qc1_Random.barrier()
random_error_gate(new_qc1_Random)
################################
new_qc2_Random = new_qc1_Random.compose(qcBit_flip_correct,[9,10,11])
shor_correct(new_qc2_Random,q_To_Protect1_Random , qCorrect_r1_Random ,qCorrect_regB_Random, qCorrect_r2_Random,qCorrect_regC_Random,qCorrect_r3_Random,rCorrect1_Random,rCorrect2_Random,rCorrect3_Random,registerCorrectBC_Random)
new_qc2_Random.barrier()
new_qc2_Random.cx(0,9)
new_qc2_Random.draw(output='mpl', style=style, fold= 42)
out_vector10 = execute(new_qc2_Random,backend_statevector).result().get_statevector()
reduced_state3 = partial_trace(out_vector10 , [1,2,3,4,5,6,7,8,10,11])
plot_state_qsphere(reduced_state3)
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
# Importing QISKit
import math, sys
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
# Import basic plotting tools
from qiskit.tools.visualization import plot_histogram
# Import methods to connect with remote backends
from qiskit import available_backends, execute, register, get_backend
# Import token to use remote backends
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
except:
qx_config = {
"APItoken":"YOUR_TOKEN_HERE",
"url":"https://quantumexperience.ng.bluemix.net/api"}
#to enable sleep
import time
#connect to remote API to be able to use remote simulators and real devices
register(qx_config['APItoken'], qx_config['url'])
print("Available backends:", available_backends())
def input_state(circ, q, n):
"""n-qubit input state for QFT that produces output 1."""
for j in range(n):
circ.h(q[j])
circ.u1(math.pi/float(2**(j)), q[j]).inverse()
def qft(circ, q, n):
"""n-qubit QFT on q in circ."""
for j in range(n):
for k in range(j):
circ.cu1(math.pi/float(2**(j-k)), q[j], q[k])
circ.h(q[j])
q = QuantumRegister(3)
c = ClassicalRegister(3)
qft3 = QuantumCircuit(q, c)
input_state(qft3, q, 3)
qft(qft3, q, 3)
for i in range(3):
qft3.measure(q[i], c[i])
print(qft3.qasm())
simulate = execute(qft3, backend="local_qasm_simulator", shots=1024).result()
simulate.get_counts()
backend = "ibmqx4"
shots = 1024
if get_backend(backend).status["available"] is True:
job_exp = execute(qft3, backend=backend, shots=shots)
lapse = 0
interval = 10
while not job_exp.done:
print('Status @ {} seconds'.format(interval * lapse))
print(job_exp.status)
time.sleep(interval)
lapse += 1
print(job_exp.status)
results = job_exp.result()
plot_histogram(results.get_counts())
|
https://github.com/0tt3r/QuaC-qiskit
|
0tt3r
|
# -*- coding: utf-8 -*-
"""This module contains objective functions for optimizing noise models.
"""
from concurrent import futures
from typing import List
import numpy as np
from typing import Callable
from scipy import optimize
import nevergrad as ng
from qiskit import QuantumCircuit
from qiskit.providers import BaseBackend
from qiskit.result import Result
from quac_qiskit.models import QuacNoiseModel
def optimize_noise_model_ng(guess_noise_model: QuacNoiseModel, circuits: List[QuantumCircuit],
backend: BaseBackend, reference_result: Result,
loss_function: Callable[[np.array], float]) -> QuacNoiseModel:
"""Refines T1 and T2 noise parameters until the divergence between the probability distributions
of a provided list of circuits simulated with the plugin and run with the hardware is minimized
using the Nevergrad TwoPointsDE optimizer
:param guess_noise_model: a QuacNoiseModel object as an initial ideal guess
:param circuits: a list of QuantumCircuit objects for loss computation
:param backend: the backend simulator on which circuits should be run
:param reference_result: the Qiskit Result object from running circuits on real hardware
:param loss_function: the loss function that should be used for optimization (i.e., kl_objective_function)
:return: an optimized QuacNoiseModel object
"""
arr = ng.p.Array(init=guess_noise_model.to_array())
arr.set_bounds(0, float('inf'))
param = ng.p.Instrumentation(arr, circuits, backend, reference_result)
optimizer = ng.optimizers.TwoPointsDE(parametrization=param, budget=100, num_workers=5)
print(optimizer.num_workers)
with futures.ThreadPoolExecutor(max_workers=optimizer.num_workers) as executor:
result = optimizer.minimize(loss_function, executor=executor, batch_mode=True, verbosity=2)
print(result[0][0].value)
return QuacNoiseModel.from_array(result[0][0].value, backend.configuration().n_qubits)
def optimize_noise_model(guess_noise_model: QuacNoiseModel, circuits: List[QuantumCircuit],
backend: BaseBackend, reference_result: Result,
loss_function: Callable[[np.array], float]) -> QuacNoiseModel:
"""Refines T1 and T2 noise parameters until the divergence between the probability distributions
of a provided list of circuits simulated with the plugin and run with the hardware is minimized
:param guess_noise_model: a QuacNoiseModel object as an initial ideal guess
:param circuits: a list of QuantumCircuit objects for loss computation
:param backend: the backend simulator on which circuits should be run
:param reference_result: the Qiskit Result object from running circuits on real hardware
:param loss_function: the loss function that should be used for optimization (i.e., kl_objective_function)
:return: an optimized QuacNoiseModel object
"""
result = optimize.minimize(loss_function, guess_noise_model.to_array(),
args=(circuits, backend, reference_result), method="Nelder-Mead",
options={"disp": True, "adaptive": True})
return result.x
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Decorator for using with Qiskit unit tests."""
import functools
import os
import sys
import unittest
from .utils import Path
from .http_recorder import http_recorder
from .testing_options import get_test_options
def is_aer_provider_available():
"""Check if the C++ simulator can be instantiated.
Returns:
bool: True if simulator executable is available
"""
# TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC
if sys.platform == 'darwin':
return False
try:
import qiskit.providers.aer # pylint: disable=unused-import
except ImportError:
return False
return True
def requires_aer_provider(test_item):
"""Decorator that skips test if qiskit aer provider is not available
Args:
test_item (callable): function or class to be decorated.
Returns:
callable: the decorated function.
"""
reason = 'Aer provider not found, skipping test'
return unittest.skipIf(not is_aer_provider_available(), reason)(test_item)
def slow_test(func):
"""Decorator that signals that the test takes minutes to run.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(*args, **kwargs):
skip_slow = not TEST_OPTIONS['run_slow']
if skip_slow:
raise unittest.SkipTest('Skipping slow tests')
return func(*args, **kwargs)
return _wrapper
def _get_credentials(test_object, test_options):
"""Finds the credentials for a specific test and options.
Args:
test_object (QiskitTestCase): The test object asking for credentials
test_options (dict): Options after QISKIT_TESTS was parsed by
get_test_options.
Returns:
Credentials: set of credentials
Raises:
ImportError: if the
Exception: when the credential could not be set and they are needed
for that set of options
"""
try:
from qiskit.providers.ibmq.credentials import (Credentials,
discover_credentials)
except ImportError:
raise ImportError('qiskit-ibmq-provider could not be found, and is '
'required for mocking or executing online tests.')
dummy_credentials = Credentials(
'dummyapiusersloginWithTokenid01',
'https://quantumexperience.ng.bluemix.net/api')
if test_options['mock_online']:
return dummy_credentials
if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''):
# Special case: instead of using the standard credentials mechanism,
# load them from different environment variables. This assumes they
# will always be in place, as is used by the Travis setup.
return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL'))
else:
# Attempt to read the standard credentials.
discovered_credentials = discover_credentials()
if discovered_credentials:
# Decide which credentials to use for testing.
if len(discovered_credentials) > 1:
try:
# Attempt to use QE credentials.
return discovered_credentials[dummy_credentials.unique_id()]
except KeyError:
pass
# Use the first available credentials.
return list(discovered_credentials.values())[0]
# No user credentials were found.
if test_options['rec']:
raise Exception('Could not locate valid credentials. You need them for '
'recording tests against the remote API.')
test_object.log.warning('No user credentials were detected. '
'Running with mocked data.')
test_options['mock_online'] = True
return dummy_credentials
def requires_qe_access(func):
"""Decorator that signals that the test uses the online API:
It involves:
* determines if the test should be skipped by checking environment
variables.
* if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is
set, it reads the credentials from an alternative set of environment
variables.
* if the test is not skipped, it reads `qe_token` and `qe_url` from
`Qconfig.py`, environment variables or qiskitrc.
* if the test is not skipped, it appends `qe_token` and `qe_url` as
arguments to the test function.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if TEST_OPTIONS['skip_online']:
raise unittest.SkipTest('Skipping online tests')
credentials = _get_credentials(self, TEST_OPTIONS)
self.using_ibmq_credentials = credentials.is_ibmq()
kwargs.update({'qe_token': credentials.token,
'qe_url': credentials.url})
decorated_func = func
if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']:
# For recording or for replaying existing cassettes, the test
# should be decorated with @use_cassette.
vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none'
decorated_func = http_recorder(
vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func)
return decorated_func(self, *args, **kwargs)
return _wrapper
TEST_OPTIONS = get_test_options()
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
# Imports
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import available_backends, get_backend, execute, register, least_busy
from qiskit.tools.visualization import plot_histogram, circuit_drawer
# Connecting to the IBM Quantum Experience
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'])
device_shots = 1024
device_name = least_busy(available_backends({'simulator': False, 'local': False}))
device = get_backend(device_name)
device_coupling = device.configuration['coupling_map']
print("the best backend is " + device_name + " with coupling " + str(device_coupling))
# Creating registers
q = QuantumRegister(2)
c = ClassicalRegister(2)
# quantum circuit to make an entangled bell state
bell = QuantumCircuit(q, c)
bell.h(q[0])
bell.cx(q[0], q[1])
# quantum circuit to measure q in the standard basis
measureZZ = QuantumCircuit(q, c)
measureZZ.measure(q[0], c[0])
measureZZ.measure(q[1], c[1])
bellZZ = bell+measureZZ
# quantum circuit to measure q in the superposition basis
measureXX = QuantumCircuit(q, c)
measureXX.h(q[0])
measureXX.h(q[1])
measureXX.measure(q[0], c[0])
measureXX.measure(q[1], c[1])
bellXX = bell+measureXX
# quantum circuit to measure ZX
measureZX = QuantumCircuit(q, c)
measureZX.h(q[0])
measureZX.measure(q[0], c[0])
measureZX.measure(q[1], c[1])
bellZX = bell+measureZX
# quantum circuit to measure XZ
measureXZ = QuantumCircuit(q, c)
measureXZ.h(q[1])
measureXZ.measure(q[0], c[0])
measureXZ.measure(q[1], c[1])
bellXZ = bell+measureXZ
circuits = [bellZZ,bellXX,bellZX,bellXZ]
circuit_drawer(bellZZ)
circuit_drawer(bellXX)
circuit_drawer(bellZX)
circuit_drawer(bellXZ)
job = execute(circuits, backend=device_name, coupling_map=device_coupling, shots=device_shots)
result = job.result()
observable_first ={'00': 1, '01': -1, '10': 1, '11': -1}
observable_second ={'00': 1, '01': 1, '10': -1, '11': -1}
observable_correlated ={'00': 1, '01': -1, '10': -1, '11': 1}
print('IZ = ' + str(result.average_data(bellZZ,observable_first)))
print('ZI = ' + str(result.average_data(bellZZ,observable_second)))
print('ZZ = ' + str(result.average_data(bellZZ,observable_correlated)))
print('IX = ' + str(result.average_data(bellXX,observable_first)))
print('XI = ' + str(result.average_data(bellXX,observable_second)))
print('XX = ' + str(result.average_data(bellXX,observable_correlated)))
print('ZX = ' + str(result.average_data(bellZX,observable_correlated)))
print('XZ = ' + str(result.average_data(bellXZ,observable_correlated)))
CHSH = lambda x : x[0]+x[1]+x[2]-x[3]
measure = [measureZZ, measureZX, measureXX, measureXZ]
local_backend = 'local_qasm_simulator'
local_shots = 8192
sim_chsh_circuits = []
sim_x = []
sim_steps = 30
for step in range(sim_steps):
theta = 2.0*np.pi*step/30
bell_middle = QuantumCircuit(q,c)
bell_middle.ry(theta,q[0])
for m in measure:
sim_chsh_circuits.append(bell+bell_middle+m)
sim_x.append(theta)
job = execute(sim_chsh_circuits, backend=local_backend, shots=local_shots)
result = job.result()
sim_chsh = []
circ = 0
for x in range(len(sim_x)):
temp_chsh = []
for m in range(len(measure)):
temp_chsh.append(result.average_data(sim_chsh_circuits[circ].name,observable_correlated))
circ += 1
sim_chsh.append(CHSH(temp_chsh))
real_chsh_circuits = []
real_x = []
real_steps = 10
for step in range(real_steps):
theta = 2.0*np.pi*step/10
bell_middle = QuantumCircuit(q,c)
bell_middle.ry(theta,q[0])
for m in measure:
real_chsh_circuits.append(bell+bell_middle+m)
real_x.append(theta)
job = execute(real_chsh_circuits, backend=device_name, coupling_map=device_coupling, shots=device_shots)
result = job.result()
real_chsh = []
circ = 0
for x in range(len(real_x)):
temp_chsh = []
for m in range(len(measure)):
temp_chsh.append(result.average_data(real_chsh_circuits[circ].name,observable_correlated))
circ += 1
real_chsh.append(CHSH(temp_chsh))
plt.plot(sim_x, sim_chsh, 'r-', real_x, real_chsh, 'bo')
plt.plot([0, 2*np.pi], [2, 2], 'b-')
plt.plot([0, 2*np.pi], [-2, -2], 'b-')
plt.grid()
plt.ylabel('CHSH', fontsize=20)
plt.xlabel(r'$Y(\theta)$', fontsize=20)
plt.show()
print(real_chsh)
device_shots = 8192 # need more statistics for 3 and 4 qubit experiments
# 2 - qubits
# quantum circuit to make GHZ state
q2 = QuantumRegister(2)
c2 = ClassicalRegister(2)
ghz = QuantumCircuit(q2, c2)
ghz.h(q2[0])
ghz.cx(q2[0],q2[1])
# quantum circuit to measure q in standard basis
measureZZ = QuantumCircuit(q2, c2)
measureZZ.measure(q2[0], c2[0])
measureZZ.measure(q2[1], c2[1])
ghzZZ = ghz+measureZZ
measureXX = QuantumCircuit(q2, c2)
measureXX.h(q2[0])
measureXX.h(q2[1])
measureXX.measure(q2[0], c2[0])
measureXX.measure(q2[1], c2[1])
ghzXX = ghz+measureXX
circuits2 = [ghzZZ, ghzXX]
circuit_drawer(ghzZZ)
circuit_drawer(ghzXX)
job2 = execute(circuits2, backend=device_name, coupling_map=device_coupling, shots=device_shots)
result2 = job2.result()
plot_histogram(result2.get_counts(ghzZZ))
plot_histogram(result2.get_counts(ghzXX))
# 3 - qubits
# quantum circuit to make GHZ state
q3 = QuantumRegister(3)
c3 = ClassicalRegister(3)
ghz3 = QuantumCircuit(q3, c3)
ghz3.h(q3[0])
ghz3.cx(q3[0],q3[1])
ghz3.cx(q3[1],q3[2])
# quantum circuit to measure q in standard basis
measureZZZ = QuantumCircuit(q3, c3)
measureZZZ.measure(q3[0], c3[0])
measureZZZ.measure(q3[1], c3[1])
measureZZZ.measure(q3[2], c3[2])
ghzZZZ = ghz3+measureZZZ
measureXXX = QuantumCircuit(q3, c3)
measureXXX.h(q3[0])
measureXXX.h(q3[1])
measureXXX.h(q3[2])
measureXXX.measure(q3[0], c3[0])
measureXXX.measure(q3[1], c3[1])
measureXXX.measure(q3[2], c3[2])
ghzXXX = ghz3+measureXXX
circuits3 = [ghzZZZ, ghzXXX]
circuit_drawer(ghzZZZ)
circuit_drawer(ghzXXX)
job3 = execute(circuits3, backend=device_name, coupling_map=device_coupling, shots=device_shots)
result3 = job3.result()
plot_histogram(result3.get_counts(ghzZZZ))
plot_histogram(result3.get_counts(ghzXXX))
# 4 - qubits
# quantum circuit to make GHZ state
q4 = QuantumRegister(4)
c4 = ClassicalRegister(4)
ghz4 = QuantumCircuit(q4, c4)
ghz4.h(q4[0])
ghz4.cx(q4[0],q4[1])
ghz4.cx(q4[1],q4[2])
ghz4.h(q4[3])
ghz4.h(q4[2])
ghz4.cx(q4[3],q4[2])
ghz4.h(q4[3])
ghz4.h(q4[2])
# quantum circuit to measure q in standard basis
measureZZZZ = QuantumCircuit(q4, c4)
measureZZZZ.measure(q4[0], c4[0])
measureZZZZ.measure(q4[1], c4[1])
measureZZZZ.measure(q4[2], c4[2])
measureZZZZ.measure(q4[3], c4[3])
ghzZZZZ = ghz4+measureZZZZ
measureXXXX = QuantumCircuit(q4, c4)
measureXXXX.h(q4[0])
measureXXXX.h(q4[1])
measureXXXX.h(q4[2])
measureXXXX.h(q4[3])
measureXXXX.measure(q4[0], c4[0])
measureXXXX.measure(q4[1], c4[1])
measureXXXX.measure(q4[2], c4[2])
measureXXXX.measure(q4[3], c4[3])
ghzXXXX = ghz4+measureXXXX
circuits4 = [ghzZZZZ, ghzXXXX]
circuit_drawer(ghzZZZZ)
circuit_drawer(ghzXXXX)
job4 = execute(circuits4, backend=device_name, coupling_map=device_coupling, shots=device_shots)
result4 = job4.result()
plot_histogram(result4.get_counts(ghzZZZZ))
plot_histogram(result4.get_counts(ghzXXXX))
# quantum circuit to make GHZ state
q3 = QuantumRegister(3)
c3 = ClassicalRegister(3)
ghz3 = QuantumCircuit(q3, c3)
ghz3.h(q3[0])
ghz3.cx(q3[0],q3[1])
ghz3.cx(q3[0],q3[2])
# quantum circuit to measure q in standard basis
measureZZZ = QuantumCircuit(q3, c3)
measureZZZ.measure(q3[0], c3[0])
measureZZZ.measure(q3[1], c3[1])
measureZZZ.measure(q3[2], c3[2])
ghzZZZ = ghz3+measureZZZ
circuits5 = [ghzZZZ]
circuit_drawer(ghzZZZ)
job5 = execute(circuits5, backend=device_name, coupling_map=device_coupling, shots=device_shots)
result5 = job5.result()
plot_histogram(result5.get_counts(ghzZZZ))
MerminM = lambda x : x[0]*x[1]*x[2]*x[3]
observable ={'000': 1, '001': -1, '010': -1, '011': 1, '100': -1, '101': 1, '110': 1, '111': -1}
# quantum circuit to measure q XXX
measureXXX = QuantumCircuit(q3, c3)
measureXXX.h(q3[0])
measureXXX.h(q3[1])
measureXXX.h(q3[2])
measureXXX.measure(q3[0], c3[0])
measureXXX.measure(q3[1], c3[1])
measureXXX.measure(q3[2], c3[2])
ghzXXX = ghz3+measureXXX
# quantum circuit to measure q XYY
measureXYY = QuantumCircuit(q3, c3)
measureXYY.s(q3[1]).inverse()
measureXYY.s(q3[2]).inverse()
measureXYY.h(q3[0])
measureXYY.h(q3[1])
measureXYY.h(q3[2])
measureXYY.measure(q3[0], c3[0])
measureXYY.measure(q3[1], c3[1])
measureXYY.measure(q3[2], c3[2])
ghzXYY = ghz3+measureXYY
# quantum circuit to measure q YXY
measureYXY = QuantumCircuit(q3, c3)
measureYXY.s(q3[0]).inverse()
measureYXY.s(q3[2]).inverse()
measureYXY.h(q3[0])
measureYXY.h(q3[1])
measureYXY.h(q3[2])
measureYXY.measure(q3[0], c3[0])
measureYXY.measure(q3[1], c3[1])
measureYXY.measure(q3[2], c3[2])
ghzYXY = ghz3+measureYXY
# quantum circuit to measure q YYX
measureYYX = QuantumCircuit(q3, c3)
measureYYX.s(q3[0]).inverse()
measureYYX.s(q3[1]).inverse()
measureYYX.h(q3[0])
measureYYX.h(q3[1])
measureYYX.h(q3[2])
measureYYX.measure(q3[0], c3[0])
measureYYX.measure(q3[1], c3[1])
measureYYX.measure(q3[2], c3[2])
ghzYYX = ghz3+measureYYX
circuits6 = [ghzXXX, ghzYYX, ghzYXY, ghzXYY]
circuit_drawer(ghzXXX)
circuit_drawer(ghzYYX)
circuit_drawer(ghzYXY)
circuit_drawer(ghzXYY)
job6 = execute(circuits6, backend=device_name, coupling_map=device_coupling, shots=device_shots)
result6 = job6.result()
temp=[]
temp.append(result6.average_data(ghzXXX,observable))
temp.append(result6.average_data(ghzYYX,observable))
temp.append(result6.average_data(ghzYXY,observable))
temp.append(result6.average_data(ghzXYY,observable))
print(MerminM(temp))
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer import AerSimulator
from qiskit import Aer, transpile
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import EfficientSU2
from qiskit.visualization import plot_histogram
from qiskit_glassydynamics.helpers import ising
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
J_hamiltonian = ising.Ising1DHamiltonian(5)
Bz_hamiltonian = ising.FieldHamiltonian( 5 , 'Z')
Bx_hamiltonian = ising.FieldHamiltonian( 5 , 'X')
print("=== Z ===")
print(J_hamiltonian)
print()
print("=== Bz ===")
print(Bz_hamiltonian)
print()
print("=== Bx ===")
print(Bx_hamiltonian)
H = - 1. * J_hamiltonian + 1. * Bz_hamiltonian - 1. * Bx_hamiltonian
print()
print("=== H ===")
print(H)
# 1D Ising Simulation
# you can swap this for a real quantum device and keep the rest of the code the same!
backend = QasmSimulator()
# COBYLA usually works well for small problems like this one
optimizer = COBYLA(maxiter=200)
# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library
ansatz = EfficientSU2(5, reps=1)
# set the algorithm
vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)
# run it with the Hamiltonian we defined above
result = vqe.compute_minimum_eigenvalue(H)
print(result)
plot_histogram(result.eigenstate)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
# Create a circuit with a register of three qubits
circ = QuantumCircuit(3)
# H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
circ.h(0)
# A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state.
circ.cx(0, 1)
# CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state.
circ.cx(0, 2)
# Draw the circuit
circ.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit import QuantumCircuit, execute, transpile, Aer
from qiskit.extensions import UnitaryGate,Initialize
from qiskit.quantum_info import Statevector
from qiskit.tools.visualization import plot_bloch_vector
from qiskit.tools.visualization import plot_histogram,plot_bloch_multivector
import numpy as np
import os
from time import sleep
import sys
sys.path.append("..")
from scipy.stats import unitary_group
import matplotlib.pyplot as plt
%matplotlib inline
os.makedirs(name = "Plots/1-qubit/",exist_ok=True)
from Modules.vanilla_qpe import QPE
from Modules.iterative_qpe import IQPE
from Modules.normal_SPEA import SPEA
from Modules.kitaev_qpe import KQPE
# x gate
u1 = QuantumCircuit(1)
u1.x(0)
u1.draw('mpl')
# x gate
u2 = QuantumCircuit(1)
u2.p(2*np.pi*(1/6),0)
u2.draw('mpl')
backend = Aer.get_backend('qasm_simulator')
os.makedirs(name = "Plots/1-qubit/x_gate/",exist_ok=True)
x_path = "Plots/1-qubit/x_gate/"
estimates = []
for precision in range(1,9):
qpe = QPE(precision=precision,unitary = u1)
qpe_circ = qpe.get_QPE(show = False)
qc = QuantumCircuit(precision+1,precision)
qc.x(precision)
qc.h(precision)
qc.append(qpe_circ, qargs = list(range(precision+1)))
qc.measure(list(range(precision)),list(range(precision)))
# display(qc.draw('mpl'))
counts = execute(qc,backend=backend,shots = 2**10).result().get_counts()
m = -1
for i,j in counts.items():
if j > m:
m = j
phase = i
factor = 0.5
ans = 0.0
for i in range(precision):
ans+= int(phase[i])*factor
factor/=2
estimates.append(ans)
plt.title("Phase by basic QPE for the unitary X",fontsize = 16)
plt.plot([i for i in range(1,9)],estimates,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(x_path+"basic_qpe.JPG",dpi = 200)
estimates = []
for precision in range(1,9):
qpe = IQPE(precision=precision,unitary = u1,unknown=True)
qc = QuantumCircuit(precision+1,precision)
qc.x(1)
qc.h(1)
phase = qpe.get_circuit_phase(qc, qubits = [1], ancilla = 0,clbits = list(range(precision)),show = False)
# display(qc.draw('mpl'))
estimates.append(phase[1])
plt.title("Phase by iterative QPE for the unitary X",fontsize = 16)
plt.plot([i for i in range(1,9)],estimates,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(x_path+"iqpe.JPG",dpi = 200)
estimates = []
for resolution in range(10,40,5):
qpe = SPEA(resolution = resolution,unitary = u1, error =3)
result = qpe.get_eigen_pair(backend = backend)
# display(qc.draw('mpl'))
print("Result : ",result)
estimates.append(result['theta'])
plt.title("Phase by SQPE for the unitary X",fontsize = 16)
plt.plot([i for i in range(10,40,5)],estimates,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates')
plt.plot([5,50],[0.5,0.5],color = 'black')
plt.plot([5,50],[0,0],color = 'black')
plt.plot([5,50],[1,1],color = 'black',label = 'Correct')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(x_path+"stat_qpe.JPG",dpi = 200)
estimates = []
for precision in range(5,16):
kqpe = KQPE(precision=precision,unitary = u1)
kqpe_circ = kqpe.get_circuit()
qc = QuantumCircuit(2+1,2)
qc.x(2)
qc.h(2)
qc.append(kqpe_circ,qargs = [0,1,2])
phase = kqpe.get_phase(qc,backend = backend, ancilla = [0,1],clbits = [0,1],show = False)
print("Precision :",precision)
print("Phase:",phase)
estimates.append(phase[0])
plt.title("Phase by Kitaev's Algorithm for the X gate",fontsize = 16)
plt.plot([i for i in range(5,16)],estimates,color = 'magenta',alpha = 0.6,linewidth = 2,marker = 's',label = 'Estimates')
plt.plot([5,17],[0.5,0.5],color = 'black')
plt.plot([5,17],[-0.5,-0.5],color = 'black')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(x_path+"kitaev_qpe.JPG",dpi = 200)
os.makedirs(name = "Plots/1-qubit/phase_gate/",exist_ok=True)
phase_path = "Plots/1-qubit/phase_gate/"
estimates = []
for precision in range(1,9):
qpe = QPE(precision=precision,unitary = u2)
qpe_circ = qpe.get_QPE(show = False)
qc = QuantumCircuit(precision+1,precision)
qc.x(precision)
qc.append(qpe_circ, qargs = list(range(precision+1)))
qc.measure(list(range(precision)),list(range(precision)))
# display(qc.draw('mpl'))
counts = execute(qc,backend=backend,shots = 2**10).result().get_counts()
m = -1
for i,j in counts.items():
if j > m:
m = j
phase = i
factor = 0.5
ans = 0.0
for i in range(precision):
ans+= int(phase[i])*factor
factor/=2
estimates.append(ans)
plt.title("Phase by basic QPE for the unitary with phase(1/6)",fontsize = 16)
plt.plot([i for i in range(1,9)],estimates,color = 'red',alpha = 0.8, linewidth = 2,marker = 'o',label = 'Estimates')
plt.plot([0,10],[0.1667,0.1667], color = 'black')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(phase_path+"basic_qpe.JPG",dpi = 200)
estimates = []
for precision in range(1,9):
qpe = IQPE(precision=precision,unitary = u2,unknown=True)
qc = QuantumCircuit(1+1,precision)
qc.x(1)
phase = qpe.get_circuit_phase(qc, qubits = [1], ancilla = 0,clbits = list(range(precision)),show = False)
# display(qc.draw('mpl'))
estimates.append(phase[1])
plt.title("Phase by iterative QPE for the unitary with phase(1/6)",fontsize = 16)
plt.plot([i for i in range(1,9)],estimates,color = 'orange',alpha = 0.7,linewidth = 2,marker = 'o',label = 'Estimates')
plt.plot([0,10],[0.1667,0.1667], color = 'black')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(phase_path+"iqpe.JPG",dpi = 200)
estimates = []
for resolution in range(10,40,5):
qpe = SPEA(resolution = resolution,unitary = u2, error =4)
result = qpe.get_eigen_pair(backend = backend)
print("Result : ",result)
estimates.append(result['theta'])
plt.title("Phase by SQPE for the unitary with phase(1/6)",fontsize = 16)
plt.plot([i for i in range(10,40,5)],estimates,color = 'g',alpha = 0.7,linewidth = 2,marker = 'o',label = 'Estimates')
plt.plot([5,50],[0.1667,0.1667],color = 'black')
plt.plot([5,50],[0,0],color = 'black')
plt.plot([5,50],[1,1],color = 'black',label = 'Correct')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(phase_path+"stat_qpe.JPG",dpi = 200)
estimates = []
for precision in range(5,16):
kqpe = KQPE(precision=precision,unitary = u2)
kqpe_circ = kqpe.get_circuit()
qc = QuantumCircuit(2+1,2)
qc.x(2)
qc.append(kqpe_circ,qargs = [0,1,2])
phase = kqpe.get_phase(qc,backend = backend, ancilla = [0,1],clbits = [0,1],show = False)
# display(qc.draw('mpl'))
print("Precision :",precision)
print("Phase:",phase)
estimates.append(phase[0])
plt.title("Phase by Kitaev's Algorithm for the unitary with phase(1/6)",fontsize = 16)
plt.plot([i for i in range(5,16)],estimates,color = 'magenta',alpha = 0.6,linewidth = 2,marker = 's',label = 'Estimates')
plt.plot([5,17],[0.1667,0.1667],color = 'black')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(phase_path+"kitaev_qpe.JPG",dpi = 200)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
# Apply X gate to change the input or target
qc.x(0)
qc.x(1)
#Applying the CNOT gate
qc.cx(0,1)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/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/Spintronic6889/Introduction-of-Quantum-walk-its-application-on-search-and-decision-making
|
Spintronic6889
|
%matplotlib inline
import matplotlib as mpl
from random import randrange
import numpy as np
import matplotlib.pyplot as plt
from random import randrange
pose=[]
for i in range(400):
pose.append([])
#print(pose)
#pose[-1]=1
#print(pose[-1])
pose[0]=200
for k in range(200):
rand = randrange(0,2)
if rand==0:
#print(rand)
pose[k+1]=pose[k]+1
if rand==1:
pose[k+1]=pose[k]-1
#print(pose)
yc=[]
for e in range(400):
yc.append([])
for q in range(400):
yc[q]=0
for h in range(400):
if pose[h]==q:
yc[q]=yc[q]+1
#print((yc))
#print(len(yc))
xc = np.arange(0, 400, 1)
plt.plot(yc)
plt.xlim(150, 250)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
# Construct quantum circuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure([0,1], [0,1])
# Select the AerSimulator from the Aer provider
simulator = AerSimulator(method='matrix_product_state')
# Run and get counts, using the matrix_product_state method
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
counts = result.get_counts(0)
counts
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
# Define a snapshot that shows the current state vector
circ.save_statevector(label='my_sv')
circ.save_matrix_product_state(label='my_mps')
circ.measure([0,1], [0,1])
# Execute and get saved data
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
data = result.data(0)
#print the result data
data
num_qubits = 50
circ = QuantumCircuit(num_qubits, num_qubits)
# Create EPR state
circ.h(0)
for i in range (0, num_qubits-1):
circ.cx(i, i+1)
# Measure
circ.measure(range(num_qubits), range(num_qubits))
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
print("Time taken: {} sec".format(result.time_taken))
result.get_counts()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Unit tests for OpenQASM 3 conversions
"""
import braket.circuits
import numpy as np
import qiskit
from qbraid.interface import circuits_allclose
from qbraid.transpiler.converter import transpile
def test_one_qubit_qiskit_to_braket():
"""Test converting qiskit to braket for one qubit circuit."""
qiskit_circuit = qiskit.QuantumCircuit(1)
qiskit_circuit.h(0)
qiskit_circuit.ry(np.pi / 2, 0)
qasm3_program = transpile(qiskit_circuit, "qasm3")
braket_circuit = transpile(qasm3_program, "braket")
circuits_allclose(qiskit_circuit, braket_circuit, strict_gphase=True)
def test_one_qubit_braket_to_qiskit():
"""Test converting braket to qiskit for one qubit circuit."""
braket_circuit = braket.circuits.Circuit().h(0).ry(0, np.pi / 2)
qasm3_program = transpile(braket_circuit, "qasm3")
qiskit_circuit = transpile(qasm3_program, "qiskit")
assert circuits_allclose(braket_circuit, qiskit_circuit, strict_gphase=True)
def test_two_qubit_braket_to_qiskit():
"""Test converting braket to qiskit for two qubit circuit."""
braket_circuit = braket.circuits.Circuit().h(0).cnot(0, 1)
qasm3_program = transpile(braket_circuit, "qasm3")
qiskit_circuit = transpile(qasm3_program, "qiskit")
assert circuits_allclose(braket_circuit, qiskit_circuit, strict_gphase=True)
def test_braket_to_qiskit_stdgates():
"""Test converting braket to qiskit for standard gates."""
circuit = braket.circuits.Circuit()
circuit.h([0, 1, 2, 3])
circuit.x([0, 1])
circuit.y(2)
circuit.z(3)
circuit.s(0)
circuit.si(1)
circuit.t(2)
circuit.ti(3)
circuit.rx(0, np.pi / 4)
circuit.ry(1, np.pi / 2)
circuit.rz(2, 3 * np.pi / 4)
circuit.phaseshift(3, np.pi / 8)
circuit.v(0)
# circuit.vi(1)
circuit.iswap(2, 3)
circuit.swap(0, 2)
circuit.swap(1, 3)
circuit.cnot(0, 1)
circuit.cphaseshift(2, 3, np.pi / 4)
cirq_circuit = transpile(circuit, "cirq")
qasm3_program = transpile(circuit, "qasm3")
qasm2_program = transpile(cirq_circuit, "qasm2")
qiskit_circuit_1 = transpile(qasm3_program, "qiskit")
qiskit_circuit_2 = transpile(qasm2_program, "qiskit")
assert circuits_allclose(circuit, qiskit_circuit_1, strict_gphase=True)
assert circuits_allclose(circuit, qiskit_circuit_2, strict_gphase=False)
def test_braket_to_qiskit_vi_sxdg():
"""Test converting braket to qiskit with vi/sxdg gate with
non-strict global phase comparison."""
circuit = braket.circuits.Circuit().vi(0)
qasm3_program = transpile(circuit, "qasm3")
qiskit_circuit = transpile(qasm3_program, "qiskit")
assert circuits_allclose(circuit, qiskit_circuit, strict_gphase=False)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
from qiskit.utils import algorithm_globals
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler
from qiskit_machine_learning.algorithms.classifiers import VQC
from IPython.display import clear_output
algorithm_globals.random_seed = 42
sampler1 = Sampler()
sampler2 = Sampler()
num_samples = 40
num_features = 2
features = 2 * algorithm_globals.random.random([num_samples, num_features]) - 1
labels = 1 * (np.sum(features, axis=1) >= 0) # in { 0, 1}
features = MinMaxScaler().fit_transform(features)
features.shape
features[0:5, :]
labels = OneHotEncoder(sparse=False).fit_transform(labels.reshape(-1, 1))
labels.shape
labels[0:5, :]
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=30, random_state=algorithm_globals.random_seed
)
train_features.shape
def plot_dataset():
plt.scatter(
train_features[np.where(train_labels[:, 0] == 0), 0],
train_features[np.where(train_labels[:, 0] == 0), 1],
marker="o",
color="b",
label="Label 0 train",
)
plt.scatter(
train_features[np.where(train_labels[:, 0] == 1), 0],
train_features[np.where(train_labels[:, 0] == 1), 1],
marker="o",
color="g",
label="Label 1 train",
)
plt.scatter(
test_features[np.where(test_labels[:, 0] == 0), 0],
test_features[np.where(test_labels[:, 0] == 0), 1],
marker="o",
facecolors="w",
edgecolors="b",
label="Label 0 test",
)
plt.scatter(
test_features[np.where(test_labels[:, 0] == 1), 0],
test_features[np.where(test_labels[:, 0] == 1), 1],
marker="o",
facecolors="w",
edgecolors="g",
label="Label 1 test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.plot([1, 0], [0, 1], "--", color="black")
plot_dataset()
plt.show()
maxiter = 20
objective_values = []
# callback function that draws a live plot when the .fit() method is called
def callback_graph(_, objective_value):
clear_output(wait=True)
objective_values.append(objective_value)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
stage1_len = np.min((len(objective_values), maxiter))
stage1_x = np.linspace(1, stage1_len, stage1_len)
stage1_y = objective_values[:stage1_len]
stage2_len = np.max((0, len(objective_values) - maxiter))
stage2_x = np.linspace(maxiter, maxiter + stage2_len - 1, stage2_len)
stage2_y = objective_values[maxiter : maxiter + stage2_len]
plt.plot(stage1_x, stage1_y, color="orange")
plt.plot(stage2_x, stage2_y, color="purple")
plt.show()
plt.rcParams["figure.figsize"] = (12, 6)
original_optimizer = COBYLA(maxiter=maxiter)
ansatz = RealAmplitudes(num_features)
initial_point = np.asarray([0.5] * ansatz.num_parameters)
original_classifier = VQC(
ansatz=ansatz, optimizer=original_optimizer, callback=callback_graph, sampler=sampler1
)
original_classifier.fit(train_features, train_labels)
print("Train score", original_classifier.score(train_features, train_labels))
print("Test score ", original_classifier.score(test_features, test_labels))
original_classifier.save("vqc_classifier.model")
loaded_classifier = VQC.load("vqc_classifier.model")
loaded_classifier.warm_start = True
loaded_classifier.neural_network.sampler = sampler2
loaded_classifier.optimizer = COBYLA(maxiter=80)
loaded_classifier.fit(train_features, train_labels)
print("Train score", loaded_classifier.score(train_features, train_labels))
print("Test score", loaded_classifier.score(test_features, test_labels))
train_predicts = loaded_classifier.predict(train_features)
test_predicts = loaded_classifier.predict(test_features)
# return plot to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
plot_dataset()
# plot misclassified data points
plt.scatter(
train_features[np.all(train_labels != train_predicts, axis=1), 0],
train_features[np.all(train_labels != train_predicts, axis=1), 1],
s=200,
facecolors="none",
edgecolors="r",
linewidths=2,
)
plt.scatter(
test_features[np.all(test_labels != test_predicts, axis=1), 0],
test_features[np.all(test_labels != test_predicts, axis=1), 1],
s=200,
facecolors="none",
edgecolors="r",
linewidths=2,
)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
from matplotlib.pyplot import bar
labels = []
elements = []
for i in range(8):
labels = labels + [i+1]
elements = elements + [1]
# visualize the values of elements in the list
bar(labels,elements)
#
# 1st step - query
#
# change the sign of the marked element, i.e., multiply it by -1
# visualize the values of elements in the list
bar(labels,elements)
#
# 1st step - inversion
#
# calculate the mean of all values
# then reflect each element over the mean, e.g.:
# if the mean is 0, then the reflection of 3 is -3
# if the mean is 1, then the reflection of 3 is -1
# if the mean is -1, then the reflection of 3 is -5
# visualize the values of elements in the list
bar(labels,elements)
#
# 2nd step - query
#
# visualize the values of elements in the list
bar(labels,elements)
#
# 2nd step - inversion
#
# visualize the values of elements in the list
bar(labels,elements)
#
# your code is here
#
from matplotlib.pyplot import bar
labels = []
elements = []
for i in range(8):
labels = labels + [i+1]
elements = elements + [1]
# visualize the values of elements in the list
bar(labels,elements)
# visualize the values of elements in the list
bar(labels,elements)
#
# 1st step - query
#
# flip the sign of the marked element
elements[3] = -1 * elements[3]
# visualize the values of elements in the list
bar(labels,elements)
#
# 1st step - inversion
#
# summation of all values
sum = 0
for i in range(len(elements)):
sum += elements[i]
# mean of all values
mean = sum / len(elements)
# reflection over the mean
for i in range(len(elements)):
value = elements[i]
new_value = mean - (elements[i]-mean)
elements[i] = new_value
# visualize the values of elements in the list
bar(labels,elements)
#
# 2nd step - query
#
# flip the sign of the marked element
elements[3] = -1 * elements[3]
# visualize the values of elements in the list
bar(labels,elements)
#
# 2nd step - inversion
#
# summation of all values
sum = 0
for i in range(len(elements)):
sum += elements[i]
# mean of all values
mean = sum / len(elements)
# reflection over mean
for i in range(len(elements)):
value = elements[i]
new_value = mean - (elements[i]-mean)
elements[i] = new_value
# visualize the values of elements in the list
bar(labels,elements)
for i in range(3):
# flip the sign of the marked element
elements[3] = -1 * elements[3]
# summation of all values
sum = 0
for i in range(len(elements)):
sum += elements[i]
# mean of all values
mean = sum / len(elements)
# reflection over mean
for i in range(len(elements)):
value = elements[i]
new_value = mean - (elements[i]-mean)
elements[i] = new_value
# visualize the values of elements in the list
bar(labels,elements)
def query(elements=[1],marked_elements=[0]):
for i in marked_elements:
elements[i] = -1 * elements[i]
return elements
def inversion (elements=[1]):
# summation of all values
summation = 0
for i in range(len(elements)):
summation += elements[i]
# mean of all values
mean = summation / len(elements)
# reflection over mean
for i in range(len(elements)):
value = elements[i]
new_value = mean - (elements[i]-mean)
elements[i] = new_value
return elements
from matplotlib.pyplot import bar
# define the list of size 8 on which each element has value of 1
elements = []
for i in range(8):
elements = elements + [1]
# index of the marked element
marked_elements = [3]
# define the list of iterations
iterations = []
# the list storing the values of the 4th element after each step
L = []
# the first values
iterations.append(0)
L.append(elements[marked_elements[0]])
for step in range(20):
# store the iteration
iterations.append(step+1)
# flip the sign of the marked element
elements = query(elements,marked_elements)
elements = inversion(elements)
# store the new value of the 4th element
L.append(elements[marked_elements[0]])
# visualize the values of the 4th elements after each iteration
bar(iterations,L)
print(iterations)
print(L)
def query(elements=[1],marked_elements=[0]):
for i in marked_elements:
elements[i] = -1 * elements[i]
return elements
def inversion (elements=[1]):
# summation of all values
summation = 0
for i in range(len(elements)):
summation += elements[i]
# mean of all values
mean = summation / len(elements)
# reflection over mean
for i in range(len(elements)):
value = elements[i]
new_value = mean - (elements[i]-mean)
elements[i] = new_value
return elements
from matplotlib.pyplot import bar
# define the list of size 8 on which each element has value of 1
elements = []
for i in range(16):
elements = elements + [1]
# index of the marked element
marked_elements = [10]
# define the list of iterations
iterations = []
# the list storing the values of the marked element after each step
L = []
# the first values
iterations.append(0)
L.append(elements[marked_elements[0]])
for step in range(20):
# store the iteration
iterations.append(step+1)
# flip the sign of the marked element
elements = query(elements,marked_elements)
elements = inversion(elements)
# store the new value of the 4th element
L.append(elements[marked_elements[0]])
# visualize the values of the marked elements after each iteration
bar(iterations,L)
print(iterations)
print(L)
def query(elements=[1],marked_elements=[0]):
for i in marked_elements:
elements[i] = -1 * elements[i]
return elements
def inversion (elements=[1]):
# summation of all values
summation = 0
for i in range(len(elements)):
summation += elements[i]
# mean of all values
mean = summation / len(elements)
# reflection over mean
for i in range(len(elements)):
value = elements[i]
new_value = mean - (elements[i]-mean)
elements[i] = new_value
return elements
from matplotlib.pyplot import bar
# define the list of size 8 on which each element has value of 1
elements = []
for i in range(16):
elements = elements + [1]
# index of the marked element
marked_elements = [4,7,9]
# define the list of iterations
iterations = []
# the list storing the values of the first element after each step
L = []
# the first values
iterations.append(0)
L.append(elements[marked_elements[0]])
for step in range(20):
# store the iteration
iterations.append(step+1)
# flip the sign of the marked element
elements = query(elements,marked_elements)
elements = inversion(elements)
# store the new value of the first marked element
L.append(elements[marked_elements[0]])
# visualizing the values of the first marked elements after each iteration
bar(iterations,L)
print(iterations)
print(L)
def query(elements=[1],marked_elements=[0]):
for i in marked_elements:
elements[i] = -1 * elements[i]
return elements
def inversion (elements=[1]):
# summation of all values
summation = 0
for i in range(len(elements)):
summation += elements[i]
# mean of all values
mean = summation / len(elements)
# reflection over mean
for i in range(len(elements)):
value = elements[i]
new_value = mean - (elements[i]-mean)
elements[i] = new_value
return elements
def length_of_list (elements=[1]):
summation = 0
for el in elements:
summation = summation + el**2
return round(summation**0.5,3)
# define the list of size 8 on which each element has value of 1
elements = []
for i in range(16):
elements = elements + [1]
# index of the marked element
marked_elements = [0,1,2,3]
print("the initial length",length_of_list(elements))
for step in range(20):
# store the iteration
iterations.append(step+1)
# flip the sign of the marked element
elements = query(elements,marked_elements)
print("step",step,"the length after query is ",length_of_list(elements))
elements = inversion(elements)
print("step",step,"the length after inversion is ",length_of_list(elements))
def query(elements=[1],marked_elements=[0]):
for i in marked_elements:
elements[i] = -1 * elements[i]
return elements
def inversion (elements=[1]):
# summation of all values
summation = 0
for i in range(len(elements)):
summation += elements[i]
# mean of all values
mean = summation / len(elements)
# reflection over mean
for i in range(len(elements)):
value = elements[i]
new_value = mean - (elements[i]-mean)
elements[i] = new_value
return elements
def length_of_list (elements=[1]):
summation = 0
for el in elements:
summation = summation + el**2
return round(summation**0.5,3)
# define the list of size 10 on which each element has value of 1
elements = []
for i in range(10):
elements = elements + [1]
# index of the marked element
marked_elements = [9]
print("the initial length",length_of_list(elements))
for step in range(20):
# store the iteration
iterations.append(step+1)
# flip the sign of the marked element
elements = query(elements,marked_elements)
print("step",step,"the length after query is ",length_of_list(elements))
elements = inversion(elements)
print("step",step,"the length after inversion is ",length_of_list(elements))
def query(elements=[1],marked_elements=[0]):
for i in marked_elements:
elements[i] = -1 * elements[i]
return elements
def inversion (elements=[1]):
# summation of all values
summation = 0
for i in range(len(elements)):
summation += elements[i]
# mean of all values
mean = summation / len(elements)
# reflection over mean
for i in range(len(elements)):
value = elements[i]
new_value = mean - (elements[i]-mean)
elements[i] = new_value
return elements
def length_of_list (elements=[1]):
summation = 0
for el in elements:
summation = summation + el**2
return round(summation**0.5,3)
# print the elements of a given list with a given precision
def print_list(L,precision):
output = ""
for i in range(len(L)):
output = output + str(round(L[i],precision))+" "
print(output)
# define the list of size 8 on which each element has value of 1
elements = []
for i in range(8):
elements = elements + [1/(8**0.5)]
# index of the marked element
marked_elements = [1]
print("step 0")
print("the list of elements is")
print_list(elements,3)
print("the initial length",length_of_list(elements))
for step in range(20):
# store the iteration
iterations.append(step+1)
# flip the sign of the marked element
elements = query(elements,marked_elements)
elements = inversion(elements)
print()
print("after step",step+1)
print("the list of elements is")
print_list(elements,3)
print("the length after iteration is ",length_of_list(elements))
def query(elements=[1],marked_elements=[0]):
for i in marked_elements:
elements[i] = -1 * elements[i]
return elements
def inversion (elements=[1]):
# summation of all values
summation = 0
for i in range(len(elements)):
summation += elements[i]
# mean of all values
mean = summation / len(elements)
# reflection over mean
for i in range(len(elements)):
value = elements[i]
new_value = mean - (elements[i]-mean)
elements[i] = new_value
return elements
def length_of_list (elements=[1]):
summation = 0
for el in elements:
summation = summation + el**2
return round(summation**0.5,3)
# print the elements of a given list with a given precision
def print_list(L,precision):
output = ""
for i in range(len(L)):
output = output + str(round(L[i],precision))+" "
print(output)
# define the list of size 8 on which each element has value of 1
elements = []
for i in range(16):
elements = elements + [1/(16**0.5)]
# index of the marked element
marked_elements = range(12)
print("step 0")
print("the list of elements is")
print_list(elements,3)
print("the initial length",length_of_list(elements))
for step in range(20):
# store the iteration
iterations.append(step+1)
# flip the sign of the marked element
elements = query(elements,marked_elements)
elements = inversion(elements)
print()
print("after step",step+1)
print("the list of elements is")
print_list(elements,3)
print("the length after iteration is ",length_of_list(elements))
|
https://github.com/Ben-Foxman/Quantum-Exploration
|
Ben-Foxman
|
# Superdense Coding Implementation Ben Foxman
import matplotlib.pyplot as plt
import numpy as np
from qiskit import *
bits = input("Enter 2 bits.") # the 2 bits to encode/decode
assert bits in ['00', '01', '10', '11']
# p1 encodes by creating map from each of the 4 bell states to each of the 4 2-bit codes
def encode(target):
bell = QuantumCircuit(2, 2, name="bell")
bell.h([0, 1]) # this entangles p1 and p2's qubit (on measurement, they both evaluate to 0 or 1)
if target == '01':
bell.x([0, 1])
elif target == '10':
bell.z(0)
elif target == '11':
bell.z(0)
bell.x([0, 1])
# '00'= identity, keep the initial bell states bell state
return bell
# now, p2 decodes the circuit
def decode(circuit):
# step 1: cnot it
circuit.cx(0, 1)
#step 2: h-gate and measure
circuit.h(0)
circuit.measure([0, 1], [0, 1])
return circuit
backend = Aer.get_backend('statevector_simulator')
# encode bits
circ = encode(bits)
# decode bits
message = decode(circ)
job = execute(message, backend)
result = job.result()
# print out the statevector. There should be a 1 at index n, where n (base 10) is the code
print(np.round(result.get_statevector(), 2))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Qiskit's QuantumCircuit class for multiple registers."""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.circuit.exceptions import CircuitError
class TestCircuitMultiRegs(QiskitTestCase):
"""QuantumCircuit Qasm tests."""
def test_circuit_multi(self):
"""Test circuit multi regs declared at start."""
qreg0 = QuantumRegister(2, "q0")
creg0 = ClassicalRegister(2, "c0")
qreg1 = QuantumRegister(2, "q1")
creg1 = ClassicalRegister(2, "c1")
circ = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circ.x(qreg0[1])
circ.x(qreg1[0])
meas = QuantumCircuit(qreg0, qreg1, creg0, creg1)
meas.measure(qreg0, creg0)
meas.measure(qreg1, creg1)
qc = circ.compose(meas)
circ2 = QuantumCircuit()
circ2.add_register(qreg0)
circ2.add_register(qreg1)
circ2.add_register(creg0)
circ2.add_register(creg1)
circ2.x(qreg0[1])
circ2.x(qreg1[0])
meas2 = QuantumCircuit()
meas2.add_register(qreg0)
meas2.add_register(qreg1)
meas2.add_register(creg0)
meas2.add_register(creg1)
meas2.measure(qreg0, creg0)
meas2.measure(qreg1, creg1)
qc2 = circ2.compose(meas2)
dag_qc = circuit_to_dag(qc)
dag_qc2 = circuit_to_dag(qc2)
dag_circ2 = circuit_to_dag(circ2)
dag_circ = circuit_to_dag(circ)
self.assertEqual(dag_qc, dag_qc2)
self.assertEqual(dag_circ, dag_circ2)
def test_circuit_multi_name_collision(self):
"""Test circuit multi regs, with name collision."""
qreg0 = QuantumRegister(2, "q")
qreg1 = QuantumRegister(3, "q")
self.assertRaises(CircuitError, QuantumCircuit, qreg0, qreg1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import 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/sebasmos/QuantumVE
|
sebasmos
|
!pip install tensorflow==2.4.1
!pip install tensorflow-quantum
import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import numpy as np
# visualization tools
%matplotlib inline
import matplotlib.pyplot as plt
from cirq.contrib.svg import SVGCircuit
a, b = sympy.symbols('a b')
# Create two qubits
q0, q1 = cirq.GridQubit.rect(1, 2)
# Create a circuit on these qubits using the parameters you created above.
circuit = cirq.Circuit(
cirq.rx(a).on(q0),
cirq.ry(b).on(q1), cirq.CNOT(control=q0, target=q1))
SVGCircuit(circuit)
# Calculate a state vector with a=0.5 and b=-0.5.
resolver = cirq.ParamResolver({a: 0.5, b: -0.5})
output_state_vector = cirq.Simulator().simulate(circuit, resolver).final_state_vector
output_state_vector
z0 = cirq.Z(q0)
qubit_map={q0: 0, q1: 1}
z0.expectation_from_state_vector(output_state_vector, qubit_map).real
z0x1 = 0.5 * z0 + cirq.X(q1)
z0x1.expectation_from_state_vector(output_state_vector, qubit_map).real
# Rank 1 tensor containing 1 circuit.
circuit_tensor = tfq.convert_to_tensor([circuit])
print(circuit_tensor.shape)
print(circuit_tensor.dtype)
# Rank 1 tensor containing 2 Pauli operators.
pauli_tensor = tfq.convert_to_tensor([z0, z0x1])
pauli_tensor.shape
batch_vals = np.array(np.random.uniform(0, 2 * np.pi, (5, 2)), dtype=np.float32)
cirq_results = []
cirq_simulator = cirq.Simulator()
for vals in batch_vals:
resolver = cirq.ParamResolver({a: vals[0], b: vals[1]})
final_state_vector = cirq_simulator.simulate(circuit, resolver).final_state_vector
cirq_results.append(
[z0.expectation_from_state_vector(final_state_vector, {
q0: 0,
q1: 1
}).real])
print('cirq batch results: \n {}'.format(np.array(cirq_results)))
tfq.layers.Expectation()(circuit,
symbol_names=[a, b],
symbol_values=batch_vals,
operators=z0)
# Parameters that the classical NN will feed values into.
control_params = sympy.symbols('theta_1 theta_2 theta_3')
# Create the parameterized circuit.
qubit = cirq.GridQubit(0, 0)
model_circuit = cirq.Circuit(
cirq.rz(control_params[0])(qubit),
cirq.ry(control_params[1])(qubit),
cirq.rx(control_params[2])(qubit))
SVGCircuit(model_circuit)
# The classical neural network layers.
controller = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='elu'),
tf.keras.layers.Dense(3)
])
controller(tf.constant([[0.0],[1.0]])).numpy()
# This input is the simulated miscalibration that the model will learn to correct.
circuits_input = tf.keras.Input(shape=(),
# The circuit-tensor has dtype `tf.string`
dtype=tf.string,
name='circuits_input')
# Commands will be either `0` or `1`, specifying the state to set the qubit to.
commands_input = tf.keras.Input(shape=(1,),
dtype=tf.dtypes.float32,
name='commands_input')
dense_2 = controller(commands_input)
# TFQ layer for classically controlled circuits.
expectation_layer = tfq.layers.ControlledPQC(model_circuit,
# Observe Z
operators = cirq.Z(qubit))
expectation = expectation_layer([circuits_input, dense_2])
# The full Keras model is built from our layers.
model = tf.keras.Model(inputs=[circuits_input, commands_input],
outputs=expectation)
#https://stackoverflow.com/questions/47605558/importerror-failed-to-import-pydot-you-must-install-pydot-and-graphviz-for-py
!pip install pydot
!pip install pydotplus
!pip install graphviz
tf.keras.utils.plot_model(model, show_shapes=True, dpi=70)
# The command input values to the classical NN.
commands = np.array([[0], [1]], dtype=np.float32)
# The desired Z expectation value at output of quantum circuit.
expected_outputs = np.array([[1], [-1]], dtype=np.float32)
random_rotations = np.random.uniform(0, 2 * np.pi, 3)
noisy_preparation = cirq.Circuit(
cirq.rx(random_rotations[0])(qubit),
cirq.ry(random_rotations[1])(qubit),
cirq.rz(random_rotations[2])(qubit)
)
datapoint_circuits = tfq.convert_to_tensor([
noisy_preparation
] * 2) # Make two copied of this circuit
datapoint_circuits.shape
model([datapoint_circuits, commands]).numpy()
optimizer = tf.keras.optimizers.Adam(learning_rate=0.05)
loss = tf.keras.losses.MeanSquaredError()
model.compile(optimizer=optimizer, loss=loss)
history = model.fit(x=[datapoint_circuits, commands],
y=expected_outputs,
epochs=30,
verbose=0)
plt.plot(history.history['loss'])
plt.title("Learning to Control a Qubit")
plt.xlabel("Iterations")
plt.ylabel("Error in Control")
plt.show()
def check_error(command_values, desired_values):
"""Based on the value in `command_value` see how well you could prepare
the full circuit to have `desired_value` when taking expectation w.r.t. Z."""
params_to_prepare_output = controller(command_values).numpy()
full_circuit = noisy_preparation + model_circuit
# Test how well you can prepare a state to get expectation the expectation
# value in `desired_values`
for index in [0, 1]:
state = cirq_simulator.simulate(
full_circuit,
{s:v for (s,v) in zip(control_params, params_to_prepare_output[index])}
).final_state_vector
expt = cirq.Z(qubit).expectation_from_state_vector(state, {qubit: 0}).real
print(f'For a desired output (expectation) of {desired_values[index]} with'
f' noisy preparation, the controller\nnetwork found the following '
f'values for theta: {params_to_prepare_output[index]}\nWhich gives an'
f' actual expectation of: {expt}\n')
check_error(commands, expected_outputs)
model([datapoint_circuits, commands])
# Define inputs.
commands_input = tf.keras.layers.Input(shape=(1),
dtype=tf.dtypes.float32,
name='commands_input')
circuits_input = tf.keras.Input(shape=(),
# The circuit-tensor has dtype `tf.string`
dtype=tf.dtypes.string,
name='circuits_input')
operators_input = tf.keras.Input(shape=(1,),
dtype=tf.dtypes.string,
name='operators_input')
# Define classical NN.
controller = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='elu'),
tf.keras.layers.Dense(3)
])
dense_2 = controller(commands_input)
# Since you aren't using a PQC or ControlledPQC you must append
# your model circuit onto the datapoint circuit tensor manually.
full_circuit = tfq.layers.AddCircuit()(circuits_input, append=model_circuit)
expectation_output = tfq.layers.Expectation()(full_circuit,
symbol_names=control_params,
symbol_values=dense_2,
operators=operators_input)
# Contruct your Keras model.
two_axis_control_model = tf.keras.Model(
inputs=[circuits_input, commands_input, operators_input],
outputs=[expectation_output])
# The operators to measure, for each command.
operator_data = tfq.convert_to_tensor([[cirq.X(qubit)], [cirq.Z(qubit)]])
# The command input values to the classical NN.
commands = np.array([[0], [1]], dtype=np.float32)
# The desired expectation value at output of quantum circuit.
expected_outputs = np.array([[1], [-1]], dtype=np.float32)
optimizer = tf.keras.optimizers.Adam(learning_rate=0.05)
loss = tf.keras.losses.MeanSquaredError()
two_axis_control_model.compile(optimizer=optimizer, loss=loss)
history = two_axis_control_model.fit(
x=[datapoint_circuits, commands, operator_data],
y=expected_outputs,
epochs=30,
validation_split=0.2,
verbose=2)
plt.plot(history.history['loss'])
plt.title("Learning to Control a Qubit")
plt.xlabel("Iterations")
plt.ylabel("Error in Control")
plt.show()
controller.predict(np.array([0,1]))
# Define inputs.
commands_input = tf.keras.layers.Input(shape=(1),
dtype=tf.dtypes.float32,
name='commands_input')
circuits_input = tf.keras.Input(shape=(),
# The circuit-tensor has dtype `tf.string`
dtype=tf.dtypes.string,
name='circuits_input')
operators_input = tf.keras.Input(shape=(1,),
dtype=tf.dtypes.string,
name='operators_input')
# Define classical NN.
controller = tf.keras.Sequential([
tf.keras.layers.Dense(100, activation='relu'),
tf.keras.layers.Dense(200, activation='relu'),
tf.keras.layers.Dense(2000, activation='relu'),
tf.keras.layers.Dense(3)
])
dense_2 = controller(commands_input)
# Since you aren't using a PQC or ControlledPQC you must append
# your model circuit onto the datapoint circuit tensor manually.
full_circuit = tfq.layers.AddCircuit()(circuits_input, append=model_circuit)
expectation_output = tfq.layers.Expectation()(full_circuit,
symbol_names=control_params,
symbol_values=dense_2,
operators=operators_input)
# Contruct your Keras model.
two_axis_control_model = tf.keras.Model(
inputs=[circuits_input, commands_input, operators_input],
outputs=[expectation_output])
# The operators to measure, for each command.
operator_data = tfq.convert_to_tensor([[cirq.X(qubit)], [cirq.Z(qubit)]])
# The command input values to the classical NN.
commands = np.array([[0], [1]], dtype=np.float32)
# The desired expectation value at output of quantum circuit.
expected_outputs = np.array([[1], [-1]], dtype=np.float32)
optimizer = tf.keras.optimizers.Adam(learning_rate=0.05)
loss = tf.keras.losses.MeanSquaredError()
two_axis_control_model.compile(optimizer=optimizer, loss=loss)
history = two_axis_control_model.fit(
x=[datapoint_circuits, commands, operator_data],
y=expected_outputs,
epochs=30,
validation_split=0.2,
verbose=2)
plt.plot(history.history['loss'])
plt.title("Learning to Control a Qubit")
plt.xlabel("Iterations")
plt.ylabel("Error in Control")
plt.show()
controller.predict(np.array([0,1]))
|
https://github.com/riddheshMarkandeya/shors-algorithm-quantum
|
riddheshMarkandeya
|
import math
import numpy as np
from qiskit import QuantumCircuit, Aer, transpile, execute
from qiskit.visualization import plot_histogram, circuit_drawer
from math import gcd
from fractions import Fraction
# Constants
N = 15
x = 7
n_count = 9 # number of counting qubits
# Controlled Unitary Operation
def c_amod15(a, power):
"""Controlled multiplication by a mod 15"""
U = QuantumCircuit(4)
for _ in range(power):
if a in [2, 13]:
U.swap(2, 3)
U.swap(1, 2)
U.swap(0, 1)
if a in [7, 8]:
U.swap(0, 1)
U.swap(1, 2)
U.swap(2, 3)
if a in [4, 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 = f"{'U'}^{power}"
c_U = U.control()
return c_U
# Inverse Quantum Fourier Transform
def qft_dagger(n):
"""n-qubit QFTdagger the first n qubits in circ"""
qc = QuantumCircuit(n)
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-math.pi/float(2**(j-m)), m, j)
qc.h(j)
qc.name = "IQFT"
return qc
# Quantum Phase Estimation Circuit
qc = QuantumCircuit(n_count + 4, n_count)
qc.x(3 + n_count)
for q in range(n_count):
qc.h(q)
for q in range(n_count):
qc.append(c_amod15(x, 2**q), [q] + [i + n_count for i in range(4)])
qc.append(qft_dagger(n_count), range(n_count))
qc.measure(range(n_count), range(n_count))
# Visualize the Circuit
circuit_drawer(qc, output='mpl', scale=0.7, fold=-1)
# Simulate the Circuit
simulator = Aer.get_backend('aer_simulator')
transpiled_qc = transpile(qc, simulator)
result = simulator.run(transpiled_qc, shots=1024).result()
counts = result.get_counts(qc)
# Plot histogram
plot_histogram(counts)
# Determine the order r
def determine_order(counts):
measured_str = max(counts, key=counts.get)
measured = int(measured_str, 2)
phase = measured / (2**n_count)
frac = Fraction(phase).limit_denominator(N)
return frac.denominator
r = determine_order(counts)
print(f"Order r: {r}")
# Classical post-processing to factorize N
factor_found = False
if r % 2 == 0:
plus = gcd(pow(x, r//2) + 1, N)
minus = gcd(pow(x, r//2) - 1, N)
if plus not in [1, N]:
print(f"One factor of {N} is {plus}")
factor_found = True
if minus not in [1, N]:
print(f"One factor of {N} is {minus}")
factor_found = True
if not factor_found:
print("No factors found. Try a different random x.")
|
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
%matplotlib inline
import sys
sys.path.append('./src')
# 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 *
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
import ClassicalHubbardEvolutionChain as chc
import random as rand
import scipy.linalg as la
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters: x (int), n (int, number of digits)"""
binry = format(x, 'b').zfill(n)
sup = list( reversed( binry[0:int(len(binry)/2)] ) )
sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) )
return format(x, 'b').zfill(n)
#============ Run Classical Evolution ==============
#Define our basis states
#States for 3 electrons with net spin up
'''
states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]],
[[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]],
[[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ]
'''
#States for 2 electrons in singlet state
states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]],
[[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]],
[[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ]
#'''
#States for a single electron
#states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ]
#Possible initial wavefunctions
#wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state
wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state
#wfk = [0., 1., 0.] #1 electron initial state
#System parameters
t = 1.0
U = 2.
classical_time_step = 0.01
classical_total_time = 500*0.01
times = np.arange(0., classical_total_time, classical_time_step)
evolution, engs = chc.sys_evolve(states, wfk, t, U, classical_total_time, classical_time_step)
#print(evolution)
probs = [np.sum(x) for x in evolution]
#print(probs)
#print(np.sum(evolution[0]))
print(engs)
states_list = []
nsite = 3
for state in range(0, 2**(2*nsite)):
state_bin = get_bin(state, 2*nsite)
state_list = [[],[]]
for mode in range(0,nsite):
state_list[0].append(int(state_bin[mode]))
state_list[1].append(int(state_bin[mode+nsite]))
#print(state_list)
states_list.append(state_list)
#print(states_list[18])
#evolution2, engs2 = chc.sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step)
#System parameters
t = 1.0
U = 2.
classical_time_step = 0.01
classical_total_time = 500*0.01
times = np.arange(0., classical_total_time, classical_time_step)
#Create full Hamiltonian
wfk_full = np.zeros(len(states_list))
#wfk_full[18] = 1. #010010
wfk_full[21] = 1. #010101
#wfk_full[2] = 1. #000010
#evolution2, engs2 = chc.sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step)
def repel(l,state):
if state[0][l]==1 and state[1][l]==1:
return state
else:
return []
#Check if two states are different by a single hop
def hop(psii, psij, hopping):
#Check spin down
hopp = 0
if psii[0]==psij[0]:
#Create array of indices with nonzero values
'''
indi = np.nonzero(psii[1])[0]
indj = np.nonzero(psij[1])[0]
if len(indi) != len(indj):
return hopp
print('ind_i: ',indi,' ind_j: ',indj)
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -hopping
print('Hopping Found: ',psii,' with: ',psij)
return hopp
'''
hops = []
for site in range(len(psii[0])):
if psii[1][site] != psij[1][site]:
hops.append(site)
if len(hops)==2 and np.sum(psii[1]) == np.sum(psij[1]):
if hops[1]-hops[0]==1:
hopp = -hopping
return hopp
#Check spin up
if psii[1]==psij[1]:
'''
indi = np.nonzero(psii[0])[0]
indj = np.nonzero(psij[0])[0]
if len(indi) != len(indj):
return hopp
print('ind_i: ',indi,' ind_j: ',indj)
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -hopping
print('Hopping Found: ',psii,' with: ',psij)
return hopp
'''
hops = []
for site in range(len(psii[1])):
if psii[0][site] != psij[0][site]:
hops.append(site)
if len(hops)==2 and np.sum(psii[0])==np.sum(psij[0]):
if hops[1]-hops[0]==1:
hopp = -hopping
return hopp
return hopp
def get_hamiltonian(states, t, U):
H = np.zeros((len(states),len(states)) )
#Construct Hamiltonian matrix
for i in range(len(states)):
psi_i = states[i]
for j in range(i, len(states)):
psi_j = states[j]
if j==i:
for l in range(0,len(states[0][0])):
if psi_i == repel(l,psi_j):
H[i,j] = U
break
else:
#print('psi_i: ',psi_i,' psi_j: ',psi_j)
H[i,j] = hop(psi_i, psi_j, t)
H[j,i] = H[i,j]
return H
hamil = get_hamiltonian(states_list, t, U)
print(hamil)
print(states_list)
print()
print("Target state: ", states_list[21])
mapping = get_mapping(states_list)
print('Second mapping set')
print(mapping[1])
print(wfk_full)
mapped_wfk = np.zeros(6)
for i in range(len(mapping)):
if 21 in mapping[i]:
print("True for mapping set: ",i)
def get_mapping(states):
num_sites = len(states[0][0])
mode_list = []
for i in range(0,2*num_sites):
index_list = []
for state_index in range(0,len(states)):
state = states[state_index]
#Check spin-up modes
if i < num_sites:
if state[0][i]==1:
index_list.append(state_index)
#Check spin-down modes
else:
if state[1][i-num_sites]==1:
index_list.append(state_index)
if index_list:
mode_list.append(index_list)
return mode_list
def wfk_energy(wfk, hamil):
eng = np.dot(np.conj(wfk), np.dot(hamil, wfk))
return eng
def get_variance(wfk, h):
h_squared = np.matmul(h, h)
eng_squared = np.vdot(wfk, np.dot(h_squared, wfk))
squared_eng = np.vdot(wfk, np.dot(h, wfk))
var = np.sqrt(eng_squared - squared_eng)
return var
def sys_evolve(states, init_wfk, hopping, repulsion, total_time, dt):
hamiltonian = get_hamiltonian(states, hopping, repulsion)
t_operator = la.expm(-1j*hamiltonian*dt)
mapping = get_mapping(states)
print(mapping)
#Initalize system
tsteps = int(total_time/dt)
evolve = np.zeros([tsteps, len(init_wfk)])
mode_evolve = np.zeros([tsteps, len(mapping)])
wfk = init_wfk
energies = np.zeros(tsteps)
#Store first time step in mode_evolve
evolve[0] = np.multiply(np.conj(wfk), wfk)
for i in range(0, len(mapping)):
wfk_sum = 0.
norm = 0.
print("Mapping: ", mapping[i])
for j in mapping[i]:
print(evolve[0][j])
wfk_sum += evolve[0][j]
mode_evolve[0][i] = wfk_sum
energies[0] = wfk_energy(wfk, hamiltonian)
norm = np.sum(mode_evolve[0])
mode_evolve[0][:] = mode_evolve[0][:] / norm
#print('wfk_sum: ',wfk_sum,' norm: ',norm)
#print('Variance: ',get_variance(wfk, hamiltonian) )
#Now do time evolution
print(mode_evolve[0])
times = np.arange(0., total_time, dt)
for t in range(1, tsteps):
wfk = np.dot(t_operator, wfk)
evolve[t] = np.multiply(np.conj(wfk), wfk)
#print(evolve[t])
energies[t] = wfk_energy(wfk, hamiltonian)
for i in range(0, len(mapping)):
norm = 0.
wfk_sum = 0.
for j in mapping[i]:
wfk_sum += evolve[t][j]
mode_evolve[t][i] = wfk_sum
norm = np.sum(mode_evolve[t])
mode_evolve[t][:] = mode_evolve[t][:] / norm
#Return time evolution
return mode_evolve, energies
evolution2, engs2 = sys_evolve(states_list, wfk_full, t, U, classical_total_time, classical_time_step)
print(evolution2)
#print(engs2)
colors = list(mcolors.TABLEAU_COLORS.keys())
fig2, ax2 = plt.subplots(figsize=(20,10))
for i in range(3):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(times, evolution2[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
ax2.plot(times, evolution2[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
plt.legend()
#print(evolution[10])
#H = np.array([[0., -t, 0.],[-t, 0., -t],[0., -t, 0.]])
#print(np.dot(np.conj(evolution[10]), np.dot(H, evolution[10])))
print(engs[0])
plt.plot(times, engs)
plt.xlabel('Time')
plt.ylabel('Energy')
#Save data
import json
fname = './data/classical_010101.json'
data = {'times': list(times)}
for i in range(3):
key1 = 'site_'+str(i)+'_up'
key2 = 'site_'+str(i)+'_down'
data[key1] = list(evolution2[:,i])
data[key2] = list(evolution2[:,i+3])
with open(fname, 'w') as fp:
json.dump(data, fp, indent=4)
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
cos = np.cos(np.sqrt(2)*times)**2
sit1 = "Site "+str(1)+r'$\uparrow$'
sit2 = "Site "+str(2)+r'$\uparrow$'
sit3 = "Site "+str(3)+r'$\uparrow$'
#ax2.plot(times, evolution[:,0], marker='.', color='k', linewidth=2, label=sit1)
#ax2.plot(times, evolution[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2)
#ax2.plot(times, evolution[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3)
#ax2.plot(times, cos, label='cosdat')
#ax2.plot(times, np.zeros(len(times)))
for i in range(3):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(times, evolution[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
ax2.plot(times, evolution[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
#ax2.set_ylim(0, 1.)
ax2.set_xlim(0, classical_total_time)
#ax2.set_xlim(0, 1.)
ax2.set_xticks(np.arange(0,classical_total_time, 0.2))
#ax2.set_yticks(np.arange(0,1.1, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
#Try by constructing the matrix and finding the eigenvalues
N = 3
Nup = 2
Ndwn = N - Nup
t = 1.
U = 2.
#Check if two states are different by a single hop
def hop(psii, psij):
#Check spin down
hopp = 0
if psii[0]==psij[0]:
#Create array of indices with nonzero values
indi = np.nonzero(psii[1])[0]
indj = np.nonzero(psij[1])[0]
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -t
return hopp
#Check spin up
if psii[1]==psij[1]:
indi = np.nonzero(psii[0])[0]
indj = np.nonzero(psij[0])[0]
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -t
return hopp
return hopp
#On-site terms
def repel(l,state):
if state[0][l]==1 and state[1][l]==1:
return state
else:
return []
#States for 3 electrons with net spin up
states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]],
[[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]],
[[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ]
#States for 2 electrons in singlet state
#states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]],
# [[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]],
# [[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ]
#States for a single electron
states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ]
H = np.zeros((len(states),len(states)) )
#Construct Hamiltonian matrix
for i in range(len(states)):
psi_i = states[i]
for j in range(len(states)):
psi_j = states[j]
if j==i:
for l in range(0,N):
if psi_i == repel(l,psi_j):
H[i,j] = U
break
else:
H[i,j] = hop(psi_i, psi_j)
print(H)
results = la.eig(H)
print()
for i in range(len(results[0])):
print('Eigenvalue: ',results[0][i])
print('Eigenvector: \n',results[1][i])
print('Norm: ', np.linalg.norm(results[1][i]))
print('Density Matrix: ')
print(np.outer(results[1][i],results[1][i]))
print()
dens_ops = []
eigs = []
for vec in results[1]:
dens_ops.append(np.outer(results[1][i],results[1][i]))
eigs.append(results[0][i])
print(dens_ops)
dt = 0.01
tsteps = 450
times = np.arange(0., tsteps*dt, dt)
t_op = la.expm(-1j*H*dt)
#print(np.subtract(np.identity(len(H)), dt*H*1j))
#print(t_op)
wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.]
wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state
evolve = np.zeros([tsteps, len(wfk)])
mode_evolve = np.zeros([tsteps, 6])
evolve[0] = wfk
#Figure out how to generalize this later
#'''[[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8]]
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2.
mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2.
mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2.
'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3.
mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3.
'''
print(mode_evolve[0])
#Define density matrices
for t in range(1, tsteps):
#t_op = la.expm(-1j*H*t)
wfk = np.dot(t_op, wfk)
evolve[t] = np.multiply(np.conj(wfk), wfk)
norm = np.sum(evolve[t])
#print(evolve[t])
#Store data in modes rather than basis defined in 'states' variable
#''' #Procedure for two electrons
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2)
mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2)
mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2)
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2)
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2)
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2)
'''
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3.
mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3.
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3.
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3.
print(mode_evolve[t])
'''
#print(np.linalg.norm(evolve[t]))
#print(len(evolve[:,0]) )
#print(len(times))
#print(evolve[:,0])
#print(min(evolve[:,0]))
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
cos = np.cos(np.sqrt(2)*times)**2
sit1 = "Site "+str(1)+r'$\uparrow$'
sit2 = "Site "+str(2)+r'$\uparrow$'
sit3 = "Site "+str(3)+r'$\uparrow$'
#ax2.plot(times, evolve[:,0], marker='.', color='k', linewidth=2, label=sit1)
#ax2.plot(times, evolve[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2)
#ax2.plot(times, evolve[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3)
#ax2.plot(times, cos, label='cosdat')
#ax2.plot(times, np.zeros(len(times)))
for i in range(3):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
#ax2.set_ylim(0, 1.)
ax2.set_xlim(0, tsteps*dt+dt/2.)
#ax2.set_xlim(0, 1.)
ax2.set_xticks(np.arange(0,tsteps*dt+dt, 0.2))
#ax2.set_yticks(np.arange(0,1.1, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
dt = 0.1
tsteps = 50
times = np.arange(0., tsteps*dt, dt)
t_op = la.expm(-1j*H*dt)
#print(np.subtract(np.identity(len(H)), dt*H*1j))
#print(t_op)
#wfk = [0., 1., 0., 0., .0, 0., 0., 0., 0.] #Half-filling initial state
wfk0 = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state
#wfk0 = [0., 1., 0.] #1 electron initial state
evolve = np.zeros([tsteps, len(wfk0)])
mode_evolve = np.zeros([tsteps, 6])
evolve[0] = wfk0
#Figure out how to generalize this later
#'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2.
mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2.
mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2.
'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3.
mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3.
#'''
#Define density matrices
for t in range(1, tsteps):
t_op = la.expm(-1j*H*t*dt)
wfk = np.dot(t_op, wfk0)
evolve[t] = np.multiply(np.conj(wfk), wfk)
norm = np.sum(evolve[t])
print(evolve[t])
#Store data in modes rather than basis defined in 'states' variable
#'''
#Procedure for two electrons
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2)
mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2)
mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2)
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2)
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2)
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2)
#Procedure for half-filling
'''
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3.
mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3.
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3.
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3.
#'''
#print(mode_evolve[t])
#print(np.linalg.norm(evolve[t]))
#print(len(evolve[:,0]) )
#print(len(times))
#print(evolve[:,0])
#print(min(evolve[:,0]))
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
cos = np.cos(np.sqrt(2)*times)**2
sit1 = "Site "+str(1)+r'$\uparrow$'
sit2 = "Site "+str(2)+r'$\uparrow$'
sit3 = "Site "+str(3)+r'$\uparrow$'
#ax2.plot(times, evolve[:,0], marker='.', color='k', linewidth=2, label=sit1)
#ax2.plot(times, evolve[:,1], marker='.', color=str(colors[0]), linewidth=2, label=sit2)
#ax2.plot(times, evolve[:,2], marker='.', color=str(colors[1]), linewidth=1.5, label=sit3)
#ax2.plot(times, cos, label='cosdat')
#ax2.plot(times, np.zeros(len(times)))
for i in range(3):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
#ax2.set_ylim(0, 1.)
ax2.set_xlim(0, tsteps*dt+dt/2.)
#ax2.set_xlim(0, 1.)
ax2.set_xticks(np.arange(0,tsteps*dt+dt, 0.2))
#ax2.set_yticks(np.arange(0,1.1, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
#Calculate total energy for 1D Hubbard model of N sites
#Number of sites in chain
N = 10
Ne = 10
#Filling factor
nu = Ne/N
#Hamiltonian parameters
t = 2.0 #Hopping
U = 4.0 #On-site repulsion
state = np.zeros(2*N)
#Add in space to populate array randomly, but do it by hand for now
#Populate Psi
n = 0
while n < Ne:
site = rand.randint(0,N-1)
spin = rand.randint(0,1)
if state[site+spin*N]==0:
state[site+spin*N] = 1
n+=1
print(state)
#Loop over state and gather energy
E = 0
############# ADD UP ENERGY FROM STATE #############
#Add hoppings at edges
if state[0]==1:
if state[1]==0:
E+=t/2.
if state[N-1]==0: #Periodic boundary
E+=t/2.
if state[N]==1:
if state[N+1]==0:
E+=t/2.
if state[-1]==0:
E+=t/2.
print('Ends of energy are: ',E)
for i in range(1,N-1):
print('i is: ',i)
#Check spin up sites if site is occupied and if electron can hop
if state[i]==1:
if state[i+1]==0:
E+=t/2.
if state[i-1]==0:
E+=t/2.
#Check spin down sites if site is occupied and if electron can hop
j = i+N
if state[j]==1:
if state[j+1]==0:
E+=t/2.
if state[j-1]==0:
E+=t/2.
#Check Hubbard repulsion terms
for i in range(0,N):
if state[i]==1 and state[i+N]==1:
E+=U/4.
print('Energy is: ',E)
print('State is: ',state)
#Try by constructing the matrix and finding the eigenvalues
N = 3
Nup = 2
Ndwn = N - Nup
t = 1.0
U = 2.5
#To generalize, try using permutations function but for now hard code this
#Store a list of 2d list of all the states where the 2d list stores the spin-up occupation
#and the spin down occupation
states = [ [1,1,0,1,0,0], [1,1,0,0,1,0], [1,1,0,0,0,1],
[1,0,1,1,0,0], [1,0,1,0,1,0], [1,0,1,0,0,1],
[0,1,1,1,0,0], [0,1,1,0,1,0], [0,1,1,0,0,1] ]
print(len(states))
H = np.zeros((len(states),len(states)) )
print(H[0,4])
print(states[0])
for i in range(len(states)):
psi_i = states[i]
for j in range(len(states)):
psi_j = states[j]
#Check over sites
#Check rest of state for hopping or double occupation
for l in range(1,N-1):
#Check edges
if psi_i[l]==1 and (psi_j[l+1]==1 and psi_i[l+1]==0) or (psi_j[l-1]==1 and psi_i[l-1]==0):
H[i,j] = -t/2.
break
if psi_i[l+N]==1 and (psi_j[l+1+N]==1 and psi_i[l+1+N]==0) or (psi_j[l-1+N]==1 and psi_i[l-1+N]==0):
H[i,j] = -t/2.
break
if psi_i==psi_j:
for l in range(N):
if psi_i[l]==1 and psi_j[l+N]==1:
H[i,j] = U/4.
break
print(H)
tst = [[0,1],[2,3]]
print(tst[1][1])
psi_i = [[1,1,0],[1,0,0]]
psi_j = [[1,1,0],[0,1,0]]
print(psi_j[0])
print(psi_j[1], ' 1st: ',psi_j[1][0], ' 2nd: ',psi_j[1][1], ' 3rd: ',psi_j[1][2])
for l in range(N):
print('l: ',l)
if psi_j[1][l]==0 and psi_j[1][l-1]==1:
psi_j[1][l]=1
psi_j[1][l-1]=0
print('1st')
print(psi_j)
break
if psi_j[1][l-1]==0 and psi_j[1][l]==1:
psi_j[1][l-1]=1
psi_j[1][l]=0
print('2nd')
print(psi_j)
break
if psi_j[1][l]==0 and psi_j[1][l+1]==1:
psi_j[1][l]=1
psi_j[1][l+1]=0
print('3rd: l=',l,' l+1=',l+1)
print(psi_j)
break
if psi_j[1][l+1]==0 and psi_j[1][l]==1:
psi_j[1][l+1]=1
psi_j[1][l]=0
print('4th')
print(psi_j)
break
def hoptst(l,m,spin,state):
#Spin is either 0 or 1 which corresponds to which array w/n state we're examining
if (state[spin][l]==0 and state[spin][m]==1):
state[spin][l]=1
state[spin][m]=0
return state
elif (state[spin][m]==0 and state[spin][l]==1):
state[spin][m]=1
state[spin][l]=0
return state
else:
return []
#Try using hoptst:
print(hoptst(0,1,1,psi_j))
### Function to permutate a given list
# Python function to print permutations of a given list
def permutation(lst):
# If lst is empty then there are no permutations
if len(lst) == 0:
return []
# If there is only one element in lst then, only
# one permuatation is possible
if len(lst) == 1:
return [lst]
# Find the permutations for lst if there are
# more than 1 characters
l = [] # empty list that will store current permutation
# Iterate the input(lst) and calculate the permutation
for i in range(len(lst)):
m = lst[i]
# Extract lst[i] or m from the list. remLst is
# remaining list
remLst = lst[:i] + lst[i+1:]
# Generating all permutations where m is first
# element
for p in permutation(remLst):
l.append([m] + p)
return l
# Driver program to test above function
data = list('1000')
for p in permutation(data):
print(p)
import itertools
items = [1,0,0]
perms = itertools.permutations
tst = 15.2
tst = np.full(3, tst)
print(tst)
H = np.array([[1, 1], [1, -1]])
H_2 = np.tensordot(H,H, 0)
print(H_2)
print('==============================')
M = np.array([[0,1,1,0],[1,1,0,0],[1,0,1,0],[0,0,0,1]])
print(M)
print(np.dot(np.conj(M.T),M))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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 unittest
import qiskit
from qiskit.circuit.library import TwoLocal
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
from qiskit.opflow import Z, I
from volta.vqd import VQD
from volta.utils import classical_solver
class TestVQDSWAP(unittest.TestCase):
def setUp(self):
optimizer = qiskit.algorithms.optimizers.COBYLA()
backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"),
shots=50000,
seed_simulator=42,
seed_transpiler=42,
)
hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z)
ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2)
self.Algo = VQD(
hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=1,
beta=1.0,
optimizer=optimizer,
backend=backend,
overlap_method="swap",
)
self.Algo.run(verbose=0)
self.eigenvalues, _ = classical_solver(hamiltonian)
def test_energies_0(self):
decimal_place = 1
want = self.eigenvalues[0]
got = self.Algo.energies[0]
message = (
"VQD with SWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))"
)
self.assertAlmostEqual(want, got, decimal_place, message)
def test_energies_1(self):
decimal_place = 1
want = self.eigenvalues[1]
got = self.Algo.energies[1]
message = "VQD with SWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))"
self.assertAlmostEqual(want, got, decimal_place, message)
class TestVQDDSWAP(unittest.TestCase):
def setUp(self):
optimizer = qiskit.algorithms.optimizers.COBYLA()
# backend = BasicAer.get_backend("qasm_simulator")
backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"),
shots=50000,
seed_simulator=42,
seed_transpiler=42,
)
hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z)
ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1)
self.Algo = VQD(
hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=1,
beta=1.0,
optimizer=optimizer,
backend=backend,
overlap_method="dswap",
)
self.Algo.run(verbose=0)
self.eigenvalues, _ = classical_solver(hamiltonian)
def test_energies_0(self):
decimal_place = 1
want = self.eigenvalues[0]
got = self.Algo.energies[0]
self.assertAlmostEqual(
want,
got,
decimal_place,
"VQD with DSWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))",
)
def test_energies_1(self):
decimal_place = 1
want = self.eigenvalues[1]
got = self.Algo.energies[1]
self.assertAlmostEqual(
want,
got,
decimal_place,
"VQD with DSWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))",
)
class TestVQDAmplitude(unittest.TestCase):
def setUp(self):
optimizer = qiskit.algorithms.optimizers.COBYLA()
backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"),
shots=50000,
seed_simulator=42,
seed_transpiler=42,
)
hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z)
ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1)
self.Algo = VQD(
hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=1,
beta=1.0,
optimizer=optimizer,
backend=backend,
overlap_method="amplitude",
)
self.Algo.run(verbose=0)
self.eigenvalues, _ = classical_solver(hamiltonian)
def test_energies_0(self):
decimal_place = 1
want = self.eigenvalues[0]
got = self.Algo.energies[0]
self.assertAlmostEqual(
want,
got,
decimal_place,
"VQD with Excitation Amplitude not working for the ground state of 1/2*((Z^I) + (Z^Z))",
)
def test_energies_1(self):
decimal_place = 1
want = self.eigenvalues[1]
got = self.Algo.energies[1]
self.assertAlmostEqual(
want,
got,
decimal_place,
"VQD with Excitation Amplitude not working for the first excited state of 1/2*((Z^I) + (Z^Z))",
)
class VQDRaiseError(unittest.TestCase):
def test_not_implemented_overlapping_method(self):
optimizer = qiskit.algorithms.optimizers.COBYLA()
backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"), shots=50000
)
hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z)
ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2)
with self.assertRaises(NotImplementedError):
VQD(
hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=1,
beta=1.0,
optimizer=optimizer,
backend=backend,
overlap_method="test",
),
if __name__ == "__main__":
unittest.main(argv=[""], verbosity=2, exit=False)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
from qiskit_cold_atom.spins import SpinSimulator
from qiskit import QuantumCircuit, QuantumRegister
backend = SpinSimulator()
qc = QuantumCircuit(4)
qc.measure_all()
# confirm that an empty circuit will return '0 0 0 0'
job = backend.run(qc, spin=3)
print(job.result().get_counts())
from qiskit_nature.second_q.operators import SpinOp
from qiskit_cold_atom.spins import SpinGate
import numpy as np
Hx = np.pi*SpinOp({"X_0": 1}) # generator of a rotation of angle pi around the x-axis
rx_spin = SpinGate(name="rx_spin", num_modes=1, generator=Hx)
qc = QuantumCircuit(QuantumRegister(1, "spin"))
qc.append(rx_spin, [0])
qc.measure_all()
qc.draw(output='mpl', style='clifford')
job = backend.run(qc, spin=10)
print(job.result().get_counts())
job = backend.run(qc, spin=6)
print(job.result().get_counts())
from qiskit_cold_atom.spins import RLXGate
qc = QuantumCircuit(QuantumRegister(1, "spin"))
qc.append(RLXGate(np.pi/2), [0])
qc.measure_all()
qc.draw(output='mpl', style="clifford")
# The same circuit can also be built by the following shorthand notation
# which is added to QuantumCircuit upon importing from qiskit_cold_atom.spins
qc = QuantumCircuit(QuantumRegister(1, "spin"))
qc.rlx(np.pi/2, 0)
qc.measure_all()
qc.draw(output='mpl', style="clifford")
from qiskit.visualization import plot_histogram
job = backend.run(qc, spin=10, shots=1000, seed=123)
counts = job.result().get_counts()
# convert counts to integers for better formatting
plot_histogram({int(k):v for k,v in counts.items()})
Hzz = SpinOp({"Z_0 Z_1": np.pi}, num_spins=2) # generating Hamiltonian acting on two spins
zz_gate = SpinGate(name="zz_spin", num_modes=2, generator=Hzz)
qc = QuantumCircuit(QuantumRegister(2, "spin"))
qc.rlx(np.pi/2, [0, 1])
qc.append(zz_gate, [0, 1])
qc.rlx(np.pi/2, [0, 1])
qc.measure_all()
qc.draw(output='mpl', style="clifford")
job = backend.run(qc, spin=1, shots=1000, seed=1234)
print("counts: ", job.result().get_counts())
plot_histogram(job.result().get_counts())
# access the statevector
print("\nstatevector :", job.result().get_statevector())
# accedd the unitary
print("\ncircuit unitary : \n", job.result().get_unitary())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
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/JessicaJohnBritto/Quantum-Computing-and-Information
|
JessicaJohnBritto
|
import pennylane as qml
from pennylane import numpy as np
# Basis State preparation
def state_preparation(basis_id, n_qubits):
bits = [int(x) for x in np.binary_repr(basis_id, width=n_qubits)]
return qml.BasisStatePreparation(bits, wires=range(n_qubits))
#Testing
state_preparation(3,5)
# Swappping of quantum circuits
def swap_bits(n_qubits):
"""A circuit that reverses the order of qubits, i.e.,
performs a SWAP such that [q1, q2, ..., qn] -> [qn, ... q2, q1].
Args:
n_qubits (int): An integer value identifying the number of qubits.
"""
for i in range(int(n_qubits/2)):
qml.SWAP(wires=[i,n_qubits-1-i])
# Conditional Rotation matrix
def qft_rotations(n_qubits):
"""A circuit performs the QFT rotations on the specified qubits.
Args:
n_qubits (int): An integer value identifying the number of qubits.
"""
n = n_qubits
for i in range(n):
qml.Hadamard(wires=i)
for jj in range(i+1,n,1):
qml.ControlledPhaseShift(np.pi/(2**(jj-i)), wires=[jj,i])
pass
def qft_node(basis_id, basis_id2, n_qubits):
''' A circuit performs addition of two numbers
Args:
basis_id (int): An integer value specifying the first number to be added.
basis_id2 (int): An integer value specifying the second number to be added.
n_qubits (int): An integer value identifying the number of qubits.
'''
# Prepare the basis state |basis_id>
bits = [int(x) for x in np.binary_repr(basis_id, width=n_qubits)]
qml.BasisStatePreparation(bits, wires=range(n_qubits))
bits2 = [int(x) for x in np.binary_repr(basis_id2, width=n_qubits)]
qml.BasisStatePreparation(bits2, wires=range(n_qubits, 2*(n_qubits),1))
qft_rotations(n_qubits)
for i in range(0,n_qubits,1):
k=0
for j in range(i+n_qubits,(2*n_qubits),1):
qml.ControlledPhaseShift((np.pi/(2**(k))), wires=[j,i])
k+=1
(qml.adjoint)(qft_rotations)(n_qubits)
return qml.sample(wires=[x for x in range(n_qubits)])
# basis_id stores a, basis_id2 stores b
basis_id = int(input("Enter number a: "))
basis_id2 = int(input("Enter number b: "))
if len(np.binary_repr(basis_id))>len(np.binary_repr(basis_id2)):
n_qubits = len(np.binary_repr(basis_id)) + 1
else:
n_qubits = len(np.binary_repr(basis_id2)) + 1
dev = qml.device('default.qubit', wires=(2*n_qubits), shots=10)
qnode = qml.QNode(qft_node, dev)
k = qnode(basis_id, basis_id2, n_qubits)
poww, summ = 0, 0
for l in reversed(k[0]):
summ = summ + (2**poww)*l
poww+=1
print(summ)
def multiplier(basis_id, basis_id2, n_qubits):
''' A circuit performs multiplication of two numbers
Args:
basis_id (int): An integer value specifying the first number to be multiplied.
basis_id2 (int): An integer value specifying the second number to be multiplied.
n_qubits (int): An integer value identifying the number of qubits.
'''
# Basis state preparation for 0, a, b respectively
bits1 = [int(x) for x in np.binary_repr(0, width=2*n_qubits)]
qml.BasisStatePreparation(bits1, wires=range(2*(n_qubits)))
bits2 = [int(x) for x in np.binary_repr(basis_id, width=n_qubits)]
qml.BasisStatePreparation(bits2, wires=range(2*n_qubits, 3*n_qubits))
bits3 = [int(x) for x in np.binary_repr(basis_id2, width=n_qubits)]
qml.BasisStatePreparation(bits3, wires=range(3*n_qubits, 4*(n_qubits),1))
# Applying QFT on first 2*n_qubits as they store the basis state for |0>
qft_rotations(2*n_qubits)
# Applying Conditional Rotation operator with controls a_j and b_m and target as |0>
for i in range(3*n_qubits, 4*n_qubits,1):
for j in range(2*n_qubits, 3*n_qubits,1):
for m in range(2*n_qubits):
qml.ctrl(qml.PhaseShift(np.pi/(2**(-(5*n_qubits)-m+j+i+1)), wires=m),control=[j,i])
# Applying inverse QFT 2*n_qubits
(qml.adjoint)(qft_rotations)(2*n_qubits)
return qml.sample(wires=[x for x in range(2*n_qubits)])
# basis_id stores a, basis_id2 stores b
basis_id = int(input("Enter number a: "))
basis_id2 = int(input("Enter number b: "))
# n_qubits takes the value of the number whose binary representation is the greatest among the two
if len(np.binary_repr(basis_id))>len(np.binary_repr(basis_id2)):
n_qubits = len(np.binary_repr(basis_id))
else:
n_qubits = len(np.binary_repr(basis_id2))
# Creating QNode
dev = qml.device('default.qubit', wires=(4*n_qubits), shots=10)
qnode = qml.QNode(multiplier, dev)
# Below code returns the sample containing measurements on the wires
# print(qnode(basis_id,basis_id2,n_qubits))
# Below prints quantum circuit
# print(qml.draw(qnode)(basis_id,basis_id2,n_qubits))
# k stores the sample of measurement values on each wire
k = qnode(basis_id, basis_id2, n_qubits)
# Converting k[0] to integer value
# Considering only k[0] as all elements of the sample are identical
poww, summ = 0, 0
for l in reversed(k[0]):
summ = summ + (2**poww)*l
poww+=1
print(summ)
|
https://github.com/donaldkaito/quantum-100knocks
|
donaldkaito
|
import numpy as np
from qiskit import QuantumCircuit, Aer
from qiskit.visualization import plot_bloch_multivector
from qiskit.quantum_info import Statevector
sim = Aer.get_backend("aer_simulator")
# 13の2進数表記
binary_13 = f"{13:05b}"
print(binary_13)
new_binary = binary_13[:2] + ("0" if binary_13[2] == "1" else "1") + binary_13[3:]
print(new_binary)
def flip_3rd_digid(integer):
binary = f"{integer:05b}"
new_binary = binary[:2] + ("0" if binary[2] == "1" else "1") + binary[3:]
return new_binary
qc = QuantumCircuit(4, 2) # A QuantumCircuit with 4 qubits and 2 classical bits``
# Xゲートを配置せよ
# <write your code>
qc.barrier()
# CNOTゲートを配置せよ
# <write your code>
qc.ccx(0, 1, 3)
qc.barrier()
qc.measure([2, 3], [0, 1])
qc.draw(output="mpl")
qc = QuantumCircuit(4, 2) # A QuantumCircuit with 4 qubits and 2 classical bits``
# Xゲートを配置せよ
qc.x([0, 1])
qc.barrier()
# CNOTゲートを配置せよ
qc.cx(0, 2)
qc.cx(1, 2)
qc.ccx(0, 1, 3)
qc.barrier()
qc.measure([2, 3], [0, 1])
qc.draw(output="mpl")
qc = QuantumCircuit(1) # A QuantumCircuit with 1 qubits
# 適切なゲートを配置せよ
# <write your code >
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
qc = QuantumCircuit(1) # A QuantumCircuit with 1 qubits
# 適切なゲートを配置せよ
qc.h(0)
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
for state_label in ["+", "-"]:
qc = QuantumCircuit(1,1)
if state_label == "+":
qc.initialize([1 / np.sqrt(2), 1 / np.sqrt(2)], 0)
elif state_label == "-":
qc.initialize([1 / np.sqrt(2), -1 / np.sqrt(2)], 0)
qc.barrier()
# 適切な測定基底をゲートを配置することで完成させよ
# <write your code>
qc.measure(0,0)
counts = sim.run(qc).result().get_counts()
print(f"|{state_label}> : ", "counts=",counts)
qc.draw(output="mpl")
for state_label in ["+", "-"]:
qc = QuantumCircuit(1,1)
if state_label == "+":
qc.initialize([1 / np.sqrt(2), 1 / np.sqrt(2)], 0)
elif state_label == "-":
qc.initialize([1 / np.sqrt(2), -1 / np.sqrt(2)], 0)
qc.barrier()
# 適切な測定基底をゲートを配置することで完成させよ
qc.h(0)
qc.measure(0,0)
counts = sim.run(qc).result().get_counts()
print(f"|{state_label}> : ", "counts=",counts)
qc.draw(output="mpl")
for state_label in ["0", "1", "+", "-"]:
for gate_label in ["X", "Z", "H", "ZH"]:
qc = QuantumCircuit(1, 1)
# 初期状態の設定
if state_label == "1":
qc.initialize([0, 1], 0)
elif state_label == "+":
qc.initialize([1 / np.sqrt(2), 1 / np.sqrt(2)], 0)
elif state_label == "-":
qc.initialize([1 / np.sqrt(2), -1 / np.sqrt(2)], 0)
# ゲートの配置
if gate_label =="X":
qc.x(0)
elif gate_label =="Z":
qc.z(0)
elif gate_label =="H":
qc.h(0)
elif gate_label =="ZH":
qc.h(0)
qc.z(0)
# Statevectorは測定前に取得する必要がある
state = Statevector.from_instruction(qc).data
qc.measure(0, 0)
counts = sim.run(qc).result().get_counts()
print(f"{gate_label} |{state_label}> : ", "state=", state.round(3), "counts=",counts)
print()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test permutation quantum circuits, permutation gates, and quantum circuits that
contain permutation gates."""
import io
import unittest
import numpy as np
from qiskit import QuantumRegister
from qiskit.test.base import QiskitTestCase
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit.library import Permutation, PermutationGate
from qiskit.quantum_info import Operator
from qiskit.qpy import dump, load
class TestPermutationLibrary(QiskitTestCase):
"""Test library of permutation logic quantum circuits."""
def test_permutation(self):
"""Test permutation circuit."""
circuit = Permutation(num_qubits=4, pattern=[1, 0, 3, 2])
expected = QuantumCircuit(4)
expected.swap(0, 1)
expected.swap(2, 3)
expected = Operator(expected)
simulated = Operator(circuit)
self.assertTrue(expected.equiv(simulated))
def test_permutation_bad(self):
"""Test that [0,..,n-1] permutation is required (no -1 for last element)."""
self.assertRaises(CircuitError, Permutation, 4, [1, 0, -1, 2])
class TestPermutationGate(QiskitTestCase):
"""Tests for the PermutationGate class."""
def test_permutation(self):
"""Test that Operator can be constructed."""
perm = PermutationGate(pattern=[1, 0, 3, 2])
expected = QuantumCircuit(4)
expected.swap(0, 1)
expected.swap(2, 3)
expected = Operator(expected)
simulated = Operator(perm)
self.assertTrue(expected.equiv(simulated))
def test_permutation_bad(self):
"""Test that [0,..,n-1] permutation is required (no -1 for last element)."""
self.assertRaises(CircuitError, PermutationGate, [1, 0, -1, 2])
def test_permutation_array(self):
"""Test correctness of the ``__array__`` method."""
perm = PermutationGate([1, 2, 0])
# The permutation pattern means q1->q0, q2->q1, q0->q2, or equivalently
# q0'=q1, q1'=q2, q2'=q0, where the primed values are the values after the
# permutation. The following matrix is the expected unitary matrix for this.
# As an example, the second column represents the result of applying
# the permutation to |001>, i.e. to q2=0, q1=0, q0=1. We should get
# q2'=q0=1, q1'=q2=0, q0'=q1=0, that is the state |100>. This corresponds
# to the "1" in the 5 row.
expected_op = np.array(
[
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
]
)
self.assertTrue(np.array_equal(perm.__array__(dtype=int), expected_op))
def test_pattern(self):
"""Test the ``pattern`` method."""
pattern = [1, 3, 5, 0, 4, 2]
perm = PermutationGate(pattern)
self.assertTrue(np.array_equal(perm.pattern, pattern))
def test_inverse(self):
"""Test correctness of the ``inverse`` method."""
perm = PermutationGate([1, 3, 5, 0, 4, 2])
# We have the permutation 1->0, 3->1, 5->2, 0->3, 4->4, 2->5.
# The inverse permutations is 0->1, 1->3, 2->5, 3->0, 4->4, 5->2, or
# after reordering 3->0, 0->1, 5->2, 1->3, 4->4, 2->5.
inverse_perm = perm.inverse()
expected_inverse_perm = PermutationGate([3, 0, 5, 1, 4, 2])
self.assertTrue(np.array_equal(inverse_perm.pattern, expected_inverse_perm.pattern))
class TestPermutationGatesOnCircuit(QiskitTestCase):
"""Tests for quantum circuits containing permutations."""
def test_append_to_circuit(self):
"""Test method for adding Permutations to quantum circuit."""
qc = QuantumCircuit(5)
qc.append(PermutationGate([1, 2, 0]), [0, 1, 2])
qc.append(PermutationGate([2, 3, 0, 1]), [1, 2, 3, 4])
self.assertIsInstance(qc.data[0].operation, PermutationGate)
self.assertIsInstance(qc.data[1].operation, PermutationGate)
def test_inverse(self):
"""Test inverse method for circuits with permutations."""
qc = QuantumCircuit(5)
qc.append(PermutationGate([1, 2, 3, 0]), [0, 4, 2, 1])
qci = qc.inverse()
qci_pattern = qci.data[0].operation.pattern
expected_pattern = [3, 0, 1, 2]
# The inverse permutations should be defined over the same qubits but with the
# inverse permutation pattern.
self.assertTrue(np.array_equal(qci_pattern, expected_pattern))
self.assertTrue(np.array_equal(qc.data[0].qubits, qci.data[0].qubits))
def test_reverse_ops(self):
"""Test reverse_ops method for circuits with permutations."""
qc = QuantumCircuit(5)
qc.append(PermutationGate([1, 2, 3, 0]), [0, 4, 2, 1])
qcr = qc.reverse_ops()
# The reversed circuit should have the permutation gate with the same pattern and over the
# same qubits.
self.assertTrue(np.array_equal(qc.data[0].operation.pattern, qcr.data[0].operation.pattern))
self.assertTrue(np.array_equal(qc.data[0].qubits, qcr.data[0].qubits))
def test_conditional(self):
"""Test adding conditional permutations."""
qc = QuantumCircuit(5, 1)
qc.append(PermutationGate([1, 2, 0]), [2, 3, 4]).c_if(0, 1)
self.assertIsNotNone(qc.data[0].operation.condition)
def test_qasm(self):
"""Test qasm for circuits with permutations."""
qr = QuantumRegister(5, "q0")
circuit = QuantumCircuit(qr)
pattern = [2, 4, 3, 0, 1]
permutation = PermutationGate(pattern)
circuit.append(permutation, [0, 1, 2, 3, 4])
circuit.h(qr[0])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate permutation__2_4_3_0_1_ q0,q1,q2,q3,q4 { swap q2,q3; swap q1,q4; swap q0,q3; }\n"
"qreg q0[5];\n"
"permutation__2_4_3_0_1_ q0[0],q0[1],q0[2],q0[3],q0[4];\n"
"h q0[0];\n"
)
self.assertEqual(expected_qasm, circuit.qasm())
def test_qpy(self):
"""Test qpy for circuits with permutations."""
circuit = QuantumCircuit(6, 1)
circuit.cx(0, 1)
circuit.append(PermutationGate([1, 2, 0]), [2, 4, 5])
circuit.h(4)
print(circuit)
qpy_file = io.BytesIO()
dump(circuit, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(circuit, new_circuit)
if __name__ == "__main__":
unittest.main()
|
https://github.com/arthurfaria/QC_basic_agorithms_qiskit
|
arthurfaria
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex
from qiskit.extensions import Initialize
from qiskit.ignis.verification import marginal_counts
from qiskit.quantum_info import random_statevector
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
## SETUP
# Protocol uses 3 qubits and 2 classical bits in 2 different registers
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical bits
crx = ClassicalRegister(1, name="crx") # in 2 different registers
teleportation_circuit = QuantumCircuit(qr, crz, crx)
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a,b)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, psi, a):
qc.cx(psi, a)
qc.h(psi)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
"""Measures qubits a & b and 'sends' the results to Bob"""
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
measure_and_send(teleportation_circuit, 0 ,1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1) # Apply gates if the registers
qc.z(qubit).c_if(crz, 1) # are in the state '1'
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
## STEP 3
measure_and_send(teleportation_circuit, 0, 1)
## STEP 4
teleportation_circuit.barrier() # Use barrier to separate steps
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
# Create random 1-qubit state
psi = random_statevector(2)
# Display it nicely
display(array_to_latex(psi, prefix="|\\psi\\rangle ="))
# Show it on a Bloch sphere
plot_bloch_multivector(psi)
init_gate = Initialize(psi)
init_gate.label = "init"
## SETUP
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical registers
crx = ClassicalRegister(1, name="crx")
qc = QuantumCircuit(qr, crz, crx)
## STEP 0
# First, let's initialize Alice's q0
qc.append(init_gate, [0])
qc.barrier()
## STEP 1
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
## STEP 2
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
## STEP 3
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
## STEP 4
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
# Display the circuit
qc.draw()
sim = Aer.get_backend('aer_simulator')
qc.save_statevector()
out_vector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(out_vector)
|
https://github.com/shell-raiser/Introduction-to-Quantum-Computing-Quantum-Algorithms-and-Qiskit
|
shell-raiser
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
#from ibm_quantum_widgets import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
from qiskit import assemble
import numpy as np
import matplotlib.pyplot as plt
n=4
grover_ckt = QuantumCircuit(n+1, n)
marked = [1,0,1,1] # 1101 element is marked (lsb to msb)=>13
def apply_oracle(n,marked,ckt):
control0 = [i for i in range(n) if not marked[i]]
ckt.x(control0)
ckt.mct(list(range(n)),n)
ckt.x(control0)
ckt.draw()
def reflect_uniform(ckt,n):
ckt.h(list(range(n)))
ckt.x(list(range(n)))
ckt.mct(list(range(n)),n)
ckt.x(list(range(n)))
ckt.h(list(range(n)))
ckt.x(n)
pass
grover_ckt.x(n)
grover_ckt.barrier()
grover_ckt.h(list(range(n)))
grover_ckt.draw()
svsim = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = svsim.run(qobj).result() # Do the simulation and return the result
statevector = result.data()['statevector']
statevector = statevector[:2**n]
marked = [1,0,1,1] # Corresponds to integer 1101 in binary => 13
ket_a = np.zeros(2**n)
ket_a[13] =1
ket_e = (np.ones(2**n) - ket_a)/np.sqrt(2**n -1)
def get_projection(psi,e,a ):
proj = [np.real(np.vdot(e,psi)), np.real(np.vdot(a,psi))]
return proj
def plt_vector(proj, axes =[0.0,1.0,0.0,1.0]):
x_pos = 0
y_pos = 0
x_direct = proj[0]
y_direct = proj[1]
# Creating plot
fig, ax = plt.subplots()
ax.quiver(x_pos, y_pos, x_direct, y_direct,scale=1.0)
ax.axis(axes)
# show plot
plt.show()
proj = get_projection(statevector, ket_e, ket_a)
plt_vector(proj)
#grover_ckt.append(oracle, list(range(n+1)))
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
grover_ckt.draw()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
grover_ckt.draw()
svsim = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = svsim.run(qobj).result() # Do the simulation and return the result
statevector = result.data()['statevector']
statevector = statevector[:2**n]
proj = get_projection(statevector, ket_e, ket_a)
plt_vector(proj)
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
grover_ckt.draw()
svsim = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = svsim.run(qobj).result() # Do the simulation and return the result
statevector = result.data()['statevector']
statevector = statevector[:2**n]
proj = get_projection(statevector, ket_e, ket_a)
plt_vector(proj)
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
grover_ckt.draw()
svsim = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = svsim.run(qobj).result() # Do the simulation and return the result
statevector = result.data()['statevector']
statevector = statevector[:2**n]
proj = get_projection(statevector, ket_e, ket_a)
plt_vector(proj, axes = [-1.0,1.0,-1.0,1.0])
from math import *
N = (math.sqrt(n**2))
theta0 = asin(1/N)
theta0
T = int((((3.14/2)/theta0)-1)/2)
T
n=4
grover_ckt = QuantumCircuit(n+1, n)
marked = [1,0,1,1] # 1101 element is marked (lsb to msb)=>13
grover_ckt.x(n)
grover_ckt.barrier()
grover_ckt.h(list(range(n+1)))
grover_ckt.barrier()
for _ in range(int(np.floor(T))):
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
for j in range(n):
grover_ckt.measure(j,j)
grover_ckt.draw()
sim = Aer.get_backend('qasm_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = sim.run(qobj).result() # Do the simulation and return the result
result
counts = result.get_counts(grover_ckt)
plot_histogram(counts)
|
https://github.com/Fabiha-Noshin/Quantum-Algorithms-with-Qiskit
|
Fabiha-Noshin
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, execute, assemble
from qiskit.providers.ibmq import least_busy
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
## Creating function for Equal Superposition states of two qubits:
def initialize(qc):
qc.h(0) # Applying H gates to both qubits
qc.h(1) # and initializing grover circuit
qc.barrier()
grover_circuit = QuantumCircuit(2)
initialize(grover_circuit)
grover_circuit.draw('mpl')
# Let's try to find the position of |11>:
def oracle_11(qc): # Apply a controlled Z gate
qc.cz(0,1)
qc.barrier()
oracle_11(grover_circuit)
grover_circuit.draw('mpl')
# Creating Grover's Diffusion operator:
def u_g(qc):
qc.h(0)
qc.h(1)
qc.x(0)
qc.x(1)
qc.h(1)
qc.cx(0,1)
qc.x(0)
qc.h(1)
qc.h(0)
qc.x(1)
qc.h(1)
qc.barrier()
u_g(grover_circuit) # temporary circuit just to see what U_s looks like
grover_circuit.draw('mpl')
# Finally we measure the circuit:
grover_circuit.measure_all()
grover_circuit.draw('mpl')
# Simulating the Circuit:
backend = Aer.get_backend('qasm_simulator')
job = execute(grover_circuit, backend, shots = 1024)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
# Experimenting with real device:
IBMQ.load_account()
# Getting the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
# Running the 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, backend, optimization_level=3)
qobj = assemble(transpiled_grover_circuit)
job = backend.run(qobj)
job_monitor(job, interval=2)
# Getting the results from the computation
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXDebugging())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import (
MinimumEigenOptimizer,
RecursiveMinimumEigenOptimizer,
SolutionSample,
OptimizationResultStatus,
)
from qiskit_optimization import QuadraticProgram
from qiskit.visualization import plot_histogram
from typing import List, Tuple
import numpy as np
# create a QUBO
qubo = QuadraticProgram()
qubo.binary_var("x")
qubo.binary_var("y")
qubo.binary_var("z")
qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2})
print(qubo.prettyprint())
op, offset = qubo.to_ising()
print("offset: {}".format(offset))
print("operator:")
print(op)
qp = QuadraticProgram()
qp.from_ising(op, offset, linear=True)
print(qp.prettyprint())
algorithm_globals.random_seed = 10598
qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 0.0])
exact_mes = NumPyMinimumEigensolver()
qaoa = MinimumEigenOptimizer(qaoa_mes) # using QAOA
exact = MinimumEigenOptimizer(exact_mes) # using the exact classical numpy minimum eigen solver
exact_result = exact.solve(qubo)
print(exact_result.prettyprint())
qaoa_result = qaoa.solve(qubo)
print(qaoa_result.prettyprint())
print("variable order:", [var.name for var in qaoa_result.variables])
for s in qaoa_result.samples:
print(s)
def get_filtered_samples(
samples: List[SolutionSample],
threshold: float = 0,
allowed_status: Tuple[OptimizationResultStatus] = (OptimizationResultStatus.SUCCESS,),
):
res = []
for s in samples:
if s.status in allowed_status and s.probability > threshold:
res.append(s)
return res
filtered_samples = get_filtered_samples(
qaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,)
)
for s in filtered_samples:
print(s)
fvals = [s.fval for s in qaoa_result.samples]
probabilities = [s.probability for s in qaoa_result.samples]
np.mean(fvals)
np.std(fvals)
samples_for_plot = {
" ".join(f"{qaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability
for s in filtered_samples
}
samples_for_plot
plot_histogram(samples_for_plot)
rqaoa = RecursiveMinimumEigenOptimizer(qaoa, min_num_vars=1, min_num_vars_optimizer=exact)
rqaoa_result = rqaoa.solve(qubo)
print(rqaoa_result.prettyprint())
filtered_samples = get_filtered_samples(
rqaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,)
)
samples_for_plot = {
" ".join(f"{rqaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability
for s in filtered_samples
}
samples_for_plot
plot_histogram(samples_for_plot)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/JavaFXpert/quantum-circuit-pygame
|
JavaFXpert
|
#
# 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 numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from model import circuit_node_types as node_types
class CircuitGridModel():
"""Grid-based model that is built when user interacts with circuit"""
def __init__(self, max_wires, max_columns):
self.max_wires = max_wires
self.max_columns = max_columns
self.nodes = np.empty((max_wires, max_columns),
dtype = CircuitGridNode)
def __str__(self):
retval = ''
for wire_num in range(self.max_wires):
retval += '\n'
for column_num in range(self.max_columns):
# retval += str(self.nodes[wire_num][column_num]) + ', '
retval += str(self.get_node_gate_part(wire_num, column_num)) + ', '
return 'CircuitGridModel: ' + retval
# def set_node(self, wire_num, column_num, node_type, radians=0, ctrl_a=-1, ctrl_b=-1, swap=-1):
def set_node(self, wire_num, column_num, circuit_grid_node):
self.nodes[wire_num][column_num] = \
CircuitGridNode(circuit_grid_node.node_type,
circuit_grid_node.radians,
circuit_grid_node.ctrl_a,
circuit_grid_node.ctrl_b,
circuit_grid_node.swap)
# TODO: Decide whether to protect as shown below
# if not self.nodes[wire_num][column_num]:
# self.nodes[wire_num][column_num] = CircuitGridNode(node_type, radians)
# else:
# print('Node ', wire_num, column_num, ' not empty')
def get_node(self, wire_num, column_num):
return self.nodes[wire_num][column_num]
def get_node_gate_part(self, wire_num, column_num):
requested_node = self.nodes[wire_num][column_num]
if requested_node and requested_node.node_type != node_types.EMPTY:
# Node is occupied so return its gate
return requested_node.node_type
else:
# Check for control nodes from gates in other nodes in this column
nodes_in_column = self.nodes[:, column_num]
for idx in range(self.max_wires):
if idx != wire_num:
other_node = nodes_in_column[idx]
if other_node:
if other_node.ctrl_a == wire_num or other_node.ctrl_b == wire_num:
return node_types.CTRL
elif other_node.swap == wire_num:
return node_types.SWAP
return node_types.EMPTY
def get_gate_wire_for_control_node(self, control_wire_num, column_num):
"""Get wire for gate that belongs to a control node on the given wire"""
gate_wire_num = -1
nodes_in_column = self.nodes[:, column_num]
for wire_idx in range(self.max_wires):
if wire_idx != control_wire_num:
other_node = nodes_in_column[wire_idx]
if other_node:
if other_node.ctrl_a == control_wire_num or \
other_node.ctrl_b == control_wire_num:
gate_wire_num = wire_idx
print("Found gate: ",
self.get_node_gate_part(gate_wire_num, column_num),
" on wire: " , gate_wire_num)
return gate_wire_num
# def avail_gate_parts_for_node(self, wire_num, column_num):
# retval = np.empty(0, dtype = np.int8)
# node_gate_part = self.get_node_gate_part(wire_num, column_num)
# if node_gate_part == node_types.EMPTY:
# # No gate part in this node
def compute_circuit(self):
qr = QuantumRegister(self.max_wires, 'q')
qc = QuantumCircuit(qr)
for column_num in range(self.max_columns):
for wire_num in range(self.max_wires):
node = self.nodes[wire_num][column_num]
if node:
if node.node_type == node_types.IDEN:
# Identity gate
qc.iden(qr[wire_num])
elif node.node_type == node_types.X:
if node.radians == 0:
if node.ctrl_a != -1:
if node.ctrl_b != -1:
# Toffoli gate
qc.ccx(qr[node.ctrl_a], qr[node.ctrl_b], qr[wire_num])
else:
# Controlled X gate
qc.cx(qr[node.ctrl_a], qr[wire_num])
else:
# Pauli-X gate
qc.x(qr[wire_num])
else:
# Rotation around X axis
qc.rx(node.radians, qr[wire_num])
elif node.node_type == node_types.Y:
if node.radians == 0:
if node.ctrl_a != -1:
# Controlled Y gate
qc.cy(qr[node.ctrl_a], qr[wire_num])
else:
# Pauli-Y gate
qc.y(qr[wire_num])
else:
# Rotation around Y axis
qc.ry(node.radians, qr[wire_num])
elif node.node_type == node_types.Z:
if node.radians == 0:
if node.ctrl_a != -1:
# Controlled Z gate
qc.cz(qr[node.ctrl_a], qr[wire_num])
else:
# Pauli-Z gate
qc.z(qr[wire_num])
else:
if node.ctrl_a != -1:
# Controlled rotation around the Z axis
qc.crz(node.radians, qr[node.ctrl_a], qr[wire_num])
else:
# Rotation around Z axis
qc.rz(node.radians, qr[wire_num])
elif node.node_type == node_types.S:
# S gate
qc.s(qr[wire_num])
elif node.node_type == node_types.SDG:
# S dagger gate
qc.sdg(qr[wire_num])
elif node.node_type == node_types.T:
# T gate
qc.t(qr[wire_num])
elif node.node_type == node_types.TDG:
# T dagger gate
qc.tdg(qr[wire_num])
elif node.node_type == node_types.H:
if node.ctrl_a != -1:
# Controlled Hadamard
qc.ch(qr[node.ctrl_a], qr[wire_num])
else:
# Hadamard gate
qc.h(qr[wire_num])
elif node.node_type == node_types.SWAP:
if node.ctrl_a != -1:
# Controlled Swap
qc.cswap(qr[node.ctrl_a], qr[wire_num], qr[node.swap])
else:
# Swap gate
qc.swap(qr[wire_num], qr[node.swap])
return qc
class CircuitGridNode():
"""Represents a node in the circuit grid"""
def __init__(self, node_type, radians=0.0, ctrl_a=-1, ctrl_b=-1, swap=-1):
self.node_type = node_type
self.radians = radians
self.ctrl_a = ctrl_a
self.ctrl_b = ctrl_b
self.swap = swap
def __str__(self):
string = 'type: ' + str(self.node_type)
string += ', radians: ' + str(self.radians) if self.radians != 0 else ''
string += ', ctrl_a: ' + str(self.ctrl_a) if self.ctrl_a != -1 else ''
string += ', ctrl_b: ' + str(self.ctrl_b) if self.ctrl_b != -1 else ''
return string
|
https://github.com/Alice-Bob-SW/emulation-examples
|
Alice-Bob-SW
|
from qiskit import QuantumCircuit, execute, transpile
from typing import Optional
from matplotlib import pyplot as plt
import numpy as np
import scipy as sp
from tqdm.notebook import tqdm
import warnings
# set default plot parameters
plt.rcParams.update({
'figure.facecolor': 'white',
'axes.facecolor': 'white',
'font.family': 'serif',
'font.size': 16,
'figure.dpi': 72.0,
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.major.size': 5.0,
'xtick.minor.size': 2.5,
'ytick.major.size': 5.0,
'ytick.minor.size': 2.5,
'xtick.minor.visible': True,
'ytick.minor.visible': True,
'axes.grid': True,
'axes.titlesize': 'larger',
'axes.labelsize': 'larger',
'legend.fontsize': 'larger',
'grid.color': 'gray',
'grid.linestyle': '--',
'grid.alpha': 0.3,
'lines.linewidth': 1.0,
'figure.figsize': (16, 8)
})
def fitted_curve(t, T, a, b):
return a * np.exp(- t / T) + b
def fit_typical_time(delay_durations, probs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
opt, _ = sp.optimize.curve_fit(
fitted_curve, delay_durations, probs,
p0=[np.median(delay_durations), probs[0] - probs[-1], probs[-1]],
method='trf'
)
return opt
from qiskit_alice_bob_provider.local.provider import AliceBobLocalProvider
from qiskit_alice_bob_provider.local.backend import ProcessorSimulator
from qiskit_alice_bob_provider.processor.physical_cat import PhysicalCatProcessor
from qiskit_aer import AerSimulator
provider = AliceBobLocalProvider()
provider.backends()
backend = provider.get_backend('EMU:40Q:PHYSICAL_CATS')
def build_bit_flip_circuit(delay_duration_s: float) -> QuantumCircuit:
circ = QuantumCircuit(1, 1)
circ.initialize(0)
circ.delay(delay_duration_s, 0, unit='s')
circ.measure(0, 0)
return circ
circ = build_bit_flip_circuit(10)
circ.draw('mpl')
nbars = np.linspace(4, 12, 7)
delay_durations_s = np.logspace(-4, 10, 10)
k1s = [100, 1_000, 10_000]
k2 = 10_000_000
shots = 1_000
tbf_fitted = {}
for k1 in tqdm(k1s):
tbf_fitted[k1] = []
for nbar in tqdm(nbars):
backend = provider.get_backend('EMU:40Q:PHYSICAL_CATS', average_nb_photons=nbar, kappa_1=k1, kappa_2=k2)
jobs = []
for delay_duration_s in delay_durations_s:
circ = build_bit_flip_circuit(delay_duration_s)
jobs.append(execute(circ, backend, shots=shots))
results = [job.result() for job in jobs]
flip_fractions = [r.get_counts().get('1', 0) / shots for r in results]
Tbf, a, b = fit_typical_time(delay_durations_s, flip_fractions)
tbf_fitted[k1].append(Tbf)
plt.figure()
plt.title('$T_{bf}=f(\\bar{n})$')
plt.xlabel('$\\bar{n} = |\\alpha|^2$ (number of photons)')
plt.ylabel('$T_{bf}$ [$s$]')
for k1 in k1s:
plt.plot(nbars, tbf_fitted[k1], label=f'$\\kappa_1$={k1:.0e}Hz, $\\kappa_1/\\kappa_2$={k1/k2:.0e}',
lw=0.5, marker='o', ms=10)
plt.semilogy()
plt.legend()
plt.show()
def build_phase_flip_circuit(delay_duration_s: float) -> QuantumCircuit:
circ = QuantumCircuit(1, 1)
circ.initialize('+')
circ.delay(delay_duration_s, 0, unit='s')
circ.measure_x(0, 0)
return circ
circ = build_phase_flip_circuit(0.1)
circ.draw('mpl')
nbars = np.linspace(4, 16, 7)
delay_durations_s = np.logspace(-8, -1, 10)
k1s = [100, 1_000]
k2 = 10_000_000
shots = 10_000
tpf_fitted = {}
for k1 in tqdm(k1s):
tpf_fitted[k1] = []
for nbar in tqdm(nbars):
backend = provider.get_backend('EMU:40Q:PHYSICAL_CATS', average_nb_photons=nbar, kappa_1=k1, kappa_2=k2)
jobs = []
for delay_duration_s in delay_durations_s:
circ = build_phase_flip_circuit(delay_duration_s)
jobs.append(execute(circ, backend, shots=shots))
results = [job.result() for job in jobs]
flip_fractions = [r.get_counts().get('1', 0) / shots for r in results]
Tpf, a, b = fit_typical_time(delay_durations_s, flip_fractions)
tpf_fitted[k1].append(Tpf)
plt.figure()
plt.title('$T_{pf}=f(\\bar{n})$')
plt.xlabel('$\\bar{n} = |\\alpha|^2$ (number of photons)')
plt.ylabel('$\\Gamma_{pf}/2\\pi$ [kHz]')
for k1 in k1s:
plt.plot(nbars, 0.5/np.array(tpf_fitted[k1]) * 1e-3, label=f'$\\kappa_1$={k1:.0e}Hz, $\\kappa_1/\\kappa_2$={k1/k2:.0e}',
lw=0.5, marker='o', ms=10)
plt.legend()
plt.show()
def build_oscillation_circuit(angle: float) -> QuantumCircuit:
circ = QuantumCircuit(1, 1)
circ.initialize('+')
circ.rz(angle, 0)
circ.measure_x(0, 0)
return circ
circ = build_oscillation_circuit(np.pi / 6)
circ.draw('mpl')
nbars = [9, 16, 25]
angles = np.linspace(0, 15 * np.pi, 150)
shots = 10_000
k1 = 100
k2 = 10_000
curves = {}
durations = {}
for nbar in tqdm(nbars):
curves[nbar] = []
durations[nbar] = []
backend = provider.get_backend('EMU:40Q:PHYSICAL_CATS', average_nb_photons=nbar, kappa_2=k2, kappa_1=k1)
jobs = []
for angle in angles:
circ = build_oscillation_circuit(angle)
jobs.append(execute(circ, backend, shots=shots))
results = [job.result() for job in jobs]
flip_fractions = [r.get_counts().get('1', 0) / shots for r in results]
durations_ = [job.circuits()[0].duration * backend.dt for job in jobs]
curves[nbar].append(flip_fractions)
durations[nbar].append(durations_)
plt.figure()
plt.suptitle('Phase flip errors when rotating around the Z axis (Rz) as a function of the rotation angle')
plt.title(f'$\\kappa_1/\\kappa_2$={k1/k2:.0e}')
plt.xlabel('Rotation angle $\\theta$ [rad]')
plt.ylabel('P(|+>)')
for nbar in nbars:
plt.plot(angles, np.squeeze(curves[nbar]), lw=0.5, marker='o', ms=5, label=f'$\\bar n$={nbar}')
plt.legend()
plt.show()
plt.figure()
plt.suptitle('Phase flip errors when rotating around the Z axis (Rz) as a function of the total circuit duration')
plt.title(f'$\\kappa_1/\\kappa_2$={k1/k2:.0e}')
plt.xlabel('Duration [µs]')
plt.ylabel('P(|+>)')
for nbar in nbars:
plt.plot(np.squeeze(durations[nbar]) * 1e6, np.squeeze(curves[nbar]), lw=0.5, marker='o', ms=5, label=f'$\\bar n$={nbar}')
plt.legend()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
with pulse.build(name='my_example') as my_program:
# Add instructions here
pass
my_program
from qiskit.pulse import DriveChannel
channel = DriveChannel(0)
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend=backend, name='backend_aware') as backend_aware_program:
channel = pulse.drive_channel(0)
print(pulse.num_qubits())
# Raises an error as backend only has 5 qubits
#pulse.drive_channel(100)
with pulse.build(backend) as delay_5dt:
pulse.delay(5, channel)
from qiskit.pulse import library
amp = 1
sigma = 10
num_samples = 128
gaus = pulse.library.Gaussian(num_samples, amp, sigma,
name="Parametric Gaus")
gaus.draw()
import numpy as np
times = np.arange(num_samples)
gaussian_samples = np.exp(-1/2 *((times - num_samples / 2) ** 2 / sigma**2))
gaus = library.Waveform(gaussian_samples, name="WF Gaus")
gaus.draw()
gaus = library.gaussian(duration=num_samples, amp=amp, sigma=sigma, name="Lib Gaus")
gaus.draw()
with pulse.build() as schedule:
pulse.play(gaus, channel)
schedule.draw()
with pulse.build() as schedule:
pulse.play([0.001*i for i in range(160)], channel)
schedule.draw()
with pulse.build(backend) as schedule:
pulse.set_frequency(4.5e9, channel)
with pulse.build(backend) as schedule:
pulse.shift_phase(np.pi, channel)
from qiskit.pulse import Acquire, AcquireChannel, MemorySlot
with pulse.build(backend) as schedule:
pulse.acquire(1200, pulse.acquire_channel(0), MemorySlot(0))
with pulse.build(backend, name='Left align example') as program:
with pulse.align_left():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Right align example') as program:
with pulse.align_right():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
gaussian_pulse = library.gaussian(100, 0.5, 20)
with pulse.align_equispaced(2*gaussian_pulse.duration):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
with pulse.align_sequential():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Offset example') as program:
with pulse.phase_offset(3.14, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
with pulse.frequency_offset(10e6, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
program.draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/GroenteLepel/qiskit-quantum-knn
|
GroenteLepel
|
"""The quantum KNN algorithm."""
from typing import Dict, Optional, Union
import logging
import itertools
import numpy as np
import scipy.stats as stats
import qiskit as qk
import qiskit.result as qres
import qiskit.tools as qktools
from qiskit.utils import QuantumInstance
import qiskit.providers as qkp
import qiskit.circuit.instruction as qinst
from qiskit_quantum_knn.qknn._qknn import _QKNN
from qiskit_quantum_knn.qknn import qknn_construction as qc
from qiskit_quantum_knn.qknn.quantum_algorithm import QuantumAlgorithm
from qiskit_quantum_knn.qknn.utils import get_subsystems_counts
logger = logging.getLogger(__name__)
UnionQInstBaseB = Union[QuantumInstance, qkp.BaseBackend]
OptionalQInstance = Optional[UnionQInstBaseB]
class QKNeighborsClassifier(QuantumAlgorithm):
""" Quantum KNN algorithm.
Maintains the construction of a QkNN Quantumcircuit, and manages the data
corresponding with this circuit by setting up training and test data and
maintaining the classes and labels to the data.
Args:
n_neighbors (int): number of neighbors to perform the voting.
training_dataset (array-like): data shaped ``(n, d)``, with ``n``
the number of data points, and ``d`` the dimensionality.
Corresponds to the training data, which is classified and will be
used to classify new data. ``d`` must be a positive power of two,
``n`` not per se, because it can be zero-padded to fit on a quantum
register.
training_labels (array): the labels corresponding to the training data,
must be ``len(n)``.
test_dataset (array-like): data shaped ``(m, d)``, with ``m`` the
the number of data points, and ``d`` the dimensionality. Describes
test data which is used to test the algorithm and give an
accuracy score.
TODO: this is not implemented yet, for now a test is performed manually.
data_points (array-like): data shaped ``(k, d)``, with ``k`` the number
of data points, and ``d`` the dimensionality of the data. This is
the unlabelled data which must be classified by the algorithm.
quantum_instance (:class: `QuantumInstance` or :class: BaseBackend):
the instance which ``qiskit`` will use to run the quantum algorithm.
Example:
Classify data using the Iris dataset.
.. jupyter-execute::
from qiskit_quantum_knn.qknn import QKNeighborsClassifier
from qiskit_quantum_knn.encoding import analog
from qiskit.utils import QuantumInstance
from sklearn import datasets
import qiskit as qk
# initialising the quantum instance
backend = qk.BasicAer.get_backend('qasm_simulator')
instance = QuantumInstance(backend, shots=10000)
# initialising the qknn model
qknn = QKNeighborsClassifier(
n_neighbors=3,
quantum_instance=instance
)
n_variables = 2 # should be positive power of 2
n_train_points = 4 # can be any positive integer
n_test_points = 2 # can be any positive integer
# use iris dataset
iris = datasets.load_iris()
labels = iris.target
data_raw = iris.data
# encode data
encoded_data = analog.encode(data_raw[:, :n_variables])
# now pick these indices from the data
train_data = encoded_data[:n_train_points]
train_labels = labels[:n_train_points]
test_data = encoded_data[n_train_points:(n_train_points+n_test_points), :n_variables]
test_labels = labels[n_train_points:(n_train_points+n_test_points)]
qknn.fit(train_data, train_labels)
qknn_prediction = qknn.predict(test_data)
print(qknn_prediction)
print(test_labels)
"""
def __init__(self, n_neighbors: int = 3,
training_dataset: Optional[np.ndarray] = None,
training_labels: Optional[np.ndarray] = None,
test_dataset: Optional[np.ndarray] = None,
data_points: Optional[np.ndarray] = None,
quantum_instance: OptionalQInstance = None) -> None:
super().__init__(quantum_instance)
self.n_neighbors = n_neighbors
# the datasets for training, testing and predicting
self.training_dataset = None
self.test_dataset = None
self.data_points = None
# dictionaries containing the class vs labels and reverse, respectively
self.class_to_label = None
self.label_to_class = None
# the number of classes in the provided data sets
self.num_classes = None
# setup of the data
self.training_dataset = training_dataset
self.training_labels = training_labels
self.test_dataset = test_dataset
self.data_points = data_points
# indicates the kind of instance this classifier is using, e.g.
# _QSVM_Binary, _QSVM_Multiclass, or, in this case, _QKNN. This
# instance has all the methods for running, testing and predicting.
self.instance = _QKNN(self)
def fit(self, X, y):
"""Fit the model using X as training data and y as target values
Notes:
There is no real "fitting" done here, since the data cannot
be stored somewhere. It only assigns the values so that these
cane be accessed when running.
Args:
X (array-like): Training data of shape [n_samples, n_features].
y (array-like): Target values of shape [n_samples].
"""
# TODO: create some validation and checks for the provided data
self.training_dataset = X
self.training_labels = y
@staticmethod
def construct_circuit(state_to_classify: np.ndarray,
oracle: qinst.Instruction,
add_measurement: bool = False) -> qk.QuantumCircuit:
r"""Construct one QkNN QuantumCircuit.
The Oracle provided is mentioned in :afham2020:`Afham et al. (2020)`
as the parameter :math:`\mathcal{W}`, and is created via the method
:py:func:`~qiskit_quantum_knn.qknn.qknn_construction.create_oracle`.
Args:
state_to_classify (array-like): array of dimension ``N`` complex
values describing the state to classify via kNN.
oracle (qiskit Instruction): oracle :math:`\mathcal{W}` for applying
training data.
add_measurement (bool): controls if measurements must be added
to the classical registers.
Returns:
QuantumCircuit: The constructed circuit.
"""
return qc.construct_circuit(
state_to_classify,
oracle,
add_measurement
)
@staticmethod
def construct_circuits(data_to_predict,
training_data) -> qk.QuantumCircuit:
"""Constructs all quantum circuits for each datum to classify.
Args:
data_to_predict (array): data points, 2-D array, of shape
``(N, D)``, where ``N`` is the number of data points and ``D``
is the dimensionality of the vector. ``D`` should coincide with
the provided training data.
training_data (array): data points which you want to know
the distance of between :py:attr:`data_to_predict`.
Returns:
numpy.ndarray: The constructed circuits.
Raises:
ValueError: Quantum instance is not present.
"""
measurement = True # can be adjusted if statevector_sim
oracle = qc.create_oracle(training_data)
# parallel_map() creates QuantumCircuits in parallel to be executed by
# a QuantumInstance
logger.info("Starting parallel map for constructing circuits.")
circuits = qktools.parallel_map(
QKNeighborsClassifier.construct_circuit,
data_to_predict,
task_args=[
oracle,
measurement
]
)
logger.info("Done.")
return circuits
@staticmethod
def execute_circuits(quantum_instance: UnionQInstBaseB,
circuits) -> qres.Result:
"""Executes the provided circuits (type array-like)."""
logger.info("Executing circuits")
result = quantum_instance.execute(circuits)
logger.info("Done.")
return result
def get_circuit_results(self,
circuits,
quantum_instance: OptionalQInstance = None) -> qres.Result:
"""Get the qiskit Results from the provided quantum circuits."""
self._quantum_instance = self._quantum_instance \
if quantum_instance is None else quantum_instance
if self._quantum_instance is None:
raise ValueError(
"Either provide a quantum instance or set one up."
)
return QKNeighborsClassifier.execute_circuits(
self.quantum_instance,
circuits
)
@staticmethod
def get_all_fidelities(circuit_results: qres.Result):
r"""Get all contrasts.
Gets the fidelity values which are calculated via
:func:`calculate_fidelities` and saves these in an array. For more about
fidelities, see :meth:`calculate_fidelities`.
Args:
circuit_results (qiskit.result.Result): the results from a QkNN
circuit build using ``QKNeighborsClassifier``.
Returns:
array: all fidelities corresponding to the QkNN.
"""
logger.info("Getting fidelity values.")
# get all counts from the circuit results
all_counts = circuit_results.get_counts()
# determine the length of the computational basis register by checking
# the length of the count result
# the -2 is there to compensate for the ' 0' or ' 1' at the end of
# the key.
num_qubits = len(list(all_counts[0].keys())[0]) - 2
# initialize the array which will hold the contrast values
n_occurrences = len(all_counts) # number of occurring states
n_datapoints = 2 ** num_qubits # number of data points
all_fidelities = np.empty(
shape=(n_occurrences, n_datapoints),
)
# loop over all counted states
for i, counts in enumerate(all_counts):
# calculate the contrast values q(i) for this set of counts
all_fidelities[i] = \
QKNeighborsClassifier.calculate_fidelities(counts)
logger.info("Done.")
return all_fidelities
@staticmethod
def calculate_fidelities(counts: Dict[str, int]) -> np.ndarray:
r"""Calculate the fidelities :math:`F_i`.
Calculates fidelities :math:`F_i` for each training state ``i`` in the
computational basis of the kNN QuantumCircuit. The fidelity can be
calculated via:
.. math::
F_i = \frac{M}{2} \left(p_0 (i) - p_1 (i)\right) \cdot \
\left(1 - \left( p(0) - p(1) \right) ^2 \right) + \
\left( p(0) - p(1) \right).
The values :math:`p(n)` are the probabilities that the control qubit is
in state :math:`n`, and the values :math:`p_n (i)` are the probabilities
that the computational basis is in state :math:`i` given the control
qubit is in state :math:`n`.
These values can be approximated by running the circuit :math:`T`
times using:
.. math::
p_n (i) \sim \bar{p}_n (i) = c_n(i) / T_n , \
p (n) \sim \bar{p} (n) = T_n / T,
where :math:`c_n(i), T_n` are the counts of the computational basis
in state :math:`i` given the control qubit in state :math:`n` and the
control qubit in state :math:`n`, respectively.
Args:
counts (dict): counts pulled from a qiskit Result from the QkNN.
Returns:
array: the fidelity values.
ndarray of length ``n_samples`` with each index ``i`` (representing
state :math:`|i\rangle` from the computational basis) the fidelity
belonging to :math:`|i\rangle`.
"""
# first get the total counts of 0 and 1 in the control qubit
subsystem_counts = get_subsystems_counts(counts)
# the counts from the control qubit are in the second register
# by some magical qiskit reason
control_counts = QKNeighborsClassifier.setup_control_counts(
subsystem_counts[1]
)
total_counts = control_counts['0'] + control_counts['1']
exp_fidelity = np.abs(control_counts['0'] - control_counts['1']) / \
total_counts
# now get the counts for the fidelities define possible states that
# the computational can be in.
num_qubits = len(list(subsystem_counts[0].keys())[0])
comp_basis_states = \
list(itertools.product(['0', '1'], repeat=num_qubits))
# initialise dict which is going to contain the fidelity values
fidelities = np.zeros(2 ** num_qubits, dtype=float)
for comp_state in comp_basis_states:
# convert list of '0's and '1's to one string e.g.
# ('0', '1', '0') --> '010'
comp_state = ''.join(comp_state)
# init fidelity value for this state
fidelity = 0.
for control_state in control_counts.keys():
state_str = comp_state + ' ' + control_state
if state_str not in counts:
logger.debug(
"State {0:s} not found in counts {1}. Adding"
"naught to contrast value."
.format(
state_str,
counts
)
)
fidelity += 0 # added for readability
else:
fidelity += \
(-1) ** int(control_state) * \
(counts[state_str]) / control_counts[control_state] * \
(1 - exp_fidelity ** 2)
index_state = int(comp_state, 2)
fidelity *= 2 ** num_qubits / 2
fidelity += exp_fidelity
fidelities[index_state] = fidelity
return fidelities
@staticmethod
def calculate_contrasts(counts: Dict[str, int]) -> np.ndarray:
r"""Calculate contrasts :math:`q(i)`.
Calculates contrasts :math:`q(i)` for each training state ``i`` in the
computational basis of the KNN QuantumCircuit. The contrasts
are according to :afham2020:`Afham et al. (2020)`.
.. math::
q(i) &= p_0(i) - p_1(i) \\
&= \frac{1 + F_i}
{M + \sum_{j=1}^M F_j} - \
\frac{1 - F_i}
{M - \sum_{j=1}^M F_j} \\
&= \frac{2(F_i - \langle F \rangle)}
{M(1 - \langle F \rangle^2)},
and correspond linearly to the fidelity :math:`F_i` between the
unclassified datum :math:`\psi` and :math:`\phi_i`.
Args:
counts (dict): counts pulled from a qiskit Result from the QkNN.
Returns:
array: the contrasts values.
ndarray of length ``n_samples`` with each index ``i`` (representing
state :math:`|i\rangle` from the computational basis) the contrast
belonging to :math:`|i\rangle`.
"""
# first get the total counts of 0 and 1 in the control qubit
subsystem_counts = get_subsystems_counts(counts)
# the counts from the control qubit are in the second register
# by some magical qiskit reason
control_counts = QKNeighborsClassifier.setup_control_counts(
subsystem_counts[1]
)
# now get the counts for the contrasts define possible states that
# the computational can be in.
num_qubits = len(list(subsystem_counts[0].keys())[0])
comp_basis_states = \
list(itertools.product(['0', '1'], repeat=num_qubits))
# initialise dict which is going to contain the contrast values
contrasts = np.zeros(2 ** num_qubits, dtype=float)
for comp_state in comp_basis_states:
# convert list of '0's and '1's to one string e.g.
# ('0', '1', '0') --> '010'
comp_state = ''.join(comp_state)
# init contrast value for this state
contrast = 0.
for control_state in control_counts.keys():
state_str = comp_state + ' ' + control_state
if state_str not in counts:
logger.debug(
"State {0:s} not found in counts {1}. Adding"
"naught to contrast value."
.format(
state_str,
counts
)
)
contrast += 0 # added for readability
else:
contrast += \
(-1) ** int(control_state) * \
(counts[state_str]) / control_counts[control_state]
index_state = int(comp_state, 2)
contrasts[index_state] = contrast
return contrasts
@staticmethod
def setup_control_counts(control_counts: Dict[str, int]) -> Dict[str, int]:
"""Sets up control counts dict.
In Qiskit, if a certain value is not measured (or counted), it has
no appearance in the ``counts`` dictionary from the :py:class:`Result`.
Thus, this method checks if this has happened and adds a value with
counts set to 0.
Notes:
This means that if the :py:attr:`control_counts` has both
occurrences of ``0`` and ``1``, this method just returns that exact
same dictionary, unmodified.
Args:
control_counts (dict): dictionary from a :py:class:`Result`
representing the control qubit in the QkNN circuit.
Returns:
dict: The modified control counts.
The same control_counts dict as provided but with non-counted
occurrence added as well if needed.
Raises:
ValueError: if the provided dictionary does not coincide with the
:py:class:`Result` from the QkNN.
"""
# constant describing the states possible in control_counts
control_states = np.array(['0', '1'])
# check if substition of 0 count value must be done
if control_states[0] not in control_counts:
to_substitute = int(control_states[0])
elif control_states[1] not in control_counts:
to_substitute = int(control_states[1])
else:
to_substitute = None
if to_substitute is not None:
# if to_substitute = 1, make it -1 * (1 - 1) = 0, else, make it
# -1 * (0 - 1) = 1
sole_occurrence = -1 * (to_substitute - 1)
logger.debug(
"Only one value is counted in the control qubit: {0:d},"
"setting the counts of state {1:d} to 0."
.format(
sole_occurrence,
to_substitute
)
)
control_counts = {
str(to_substitute): 0,
str(sole_occurrence): control_counts[str(sole_occurrence)]
}
return control_counts
def majority_vote(self,
labels: np.ndarray,
fidelities: np.ndarray) -> np.ndarray:
"""Performs majority vote with the :math:`k` nearest to determine class.
Args:
labels (array-like): The labels of the training data provided to
the :class:`QKNeighborsClassifier`.
fidelities (array-like): The fidelities calculated using
:meth:`get_all_fidelities'.
Returns:
ndarray: The labels resulted from the majority vote.
"""
logger.info("Performing majority vote.")
# get the neighbors sorted on their distance (lowest first) per data
# point.
if np.any(fidelities < -0.2) or np.any(fidelities > 1.2):
raise ValueError("Fidelities contain values outside range 0<=F<=1:"
f"{fidelities[fidelities < -0.2]}"
f"{fidelities[fidelities > 1.2]}")
sorted_neighbors = np.argpartition(
1 - fidelities,
-self.n_neighbors
)
# get the number of participating values
n_queries = len(labels)
# modify the argpartition to remove any "filler" qubits, e.g. if 5
# train data are given, n_queries=5 but number of qubits states must
# always be a positive number of 2 (will be 8 in example case)
# these values can accidentally participate in the voting, hence these
# must be removed
sorted_neighbors = sorted_neighbors[sorted_neighbors < n_queries]\
.reshape(sorted_neighbors.shape[0], n_queries)
if n_queries == 1:
n_closest_neighbors = sorted_neighbors[:self.n_neighbors]
else:
# this is the case when more than one data point is given to this
# majority vote, so the shape will be of (n_points, m)
n_closest_neighbors = sorted_neighbors[:, :self.n_neighbors]
# voters = np.take(data, indices_of_neighbors, axis=0)
voter_labels = np.take(labels, n_closest_neighbors)
if n_queries == 1:
votes, counts = stats.mode(voter_labels)
else:
votes, counts = stats.mode(voter_labels, axis=1)
logger.info("Done.")
return votes.real.flatten()
@property
def ret(self) -> Dict:
""" Returns result.
Returns:
Dict: return value(s).
"""
return self.instance.ret
@ret.setter
def ret(self, new_value):
""" Sets result.
Args:
new_value: new value to set.
"""
self.instance.ret = new_value
def predict(self, data) -> np.ndarray:
"""Predict the labels of the provided data."""
return self.instance.predict(data)
def _run(self) -> Dict:
return self.instance.run()
|
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
|
Qiskit-Extensions
|
import numpy as np
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
circuit = random_circuit(7, 6, max_operands=2, seed=1242)
observable = SparsePauliOp(["ZIIIIII", "IIIZIII", "IIIIIIZ"])
circuit.draw("mpl", scale=0.8)
from circuit_knitting.cutting.automated_cut_finding import (
find_cuts,
OptimizationParameters,
DeviceConstraints,
)
# Specify settings for the cut-finding optimizer
optimization_settings = OptimizationParameters(seed=111)
# Specify the size of the QPUs available
device_constraints = DeviceConstraints(qubits_per_subcircuit=4)
cut_circuit, metadata = find_cuts(circuit, optimization_settings, device_constraints)
print(
f'Found solution using {len(metadata["cuts"])} cuts with a sampling '
f'overhead of {metadata["sampling_overhead"]}.\n'
f'Lowest cost solution found: {metadata["minimum_reached"]}.'
)
for cut in metadata["cuts"]:
print(f"{cut[0]} at circuit instruction index {cut[1]}")
cut_circuit.draw("mpl", scale=0.8, fold=-1)
from circuit_knitting.cutting import cut_wires, expand_observables
qc_w_ancilla = cut_wires(cut_circuit)
observables_expanded = expand_observables(observable.paulis, circuit, qc_w_ancilla)
qc_w_ancilla.draw("mpl", scale=0.8, fold=-1)
from circuit_knitting.cutting import partition_problem
partitioned_problem = partition_problem(
circuit=qc_w_ancilla, observables=observables_expanded
)
subcircuits = partitioned_problem.subcircuits
subobservables = partitioned_problem.subobservables
print(
f"Sampling overhead: {np.prod([basis.overhead for basis in partitioned_problem.bases])}"
)
subobservables
subcircuits[0].draw("mpl", style="iqp", scale=0.8)
subcircuits[1].draw("mpl", style="iqp", scale=0.8)
from circuit_knitting.cutting import generate_cutting_experiments
subexperiments, coefficients = generate_cutting_experiments(
circuits=subcircuits, observables=subobservables, num_samples=1_000
)
print(
f"{len(subexperiments[0]) + len(subexperiments[1])} total subexperiments to run on backend."
)
|
https://github.com/qcware/qusetta
|
qcware
|
"""Translating circuits to and from ``qiskit``."""
import qiskit
import qusetta as qs
from typing import List
__all__ = "Qiskit",
class Qiskit(qs.Conversions):
"""Translation methods for qiskit's representation of a circuit.
Example
--------
Create a qiskit circuit.
>>> import qiskit
>>> circuit = qiskit.QuantumCircuit(2)
>>> circuit.h(0)
>>> circuit.cx(0, 1)
Convert the qiskit circuit to a cirq circuit.
>>> from qusetta import Qiskit
>>> cirq_circuit = Qiskit.to_cirq(circuit)
Notes
-----
As we all know, qiskit is weird in the way that they index their qubits.
In particular, they index qubits in reverse order compared to everyone
else. Therefore, in order to ensure that the first bullet point is true,
qusetta reverses the qubits of a qiskit circuit. Thus, as an example, a
qusetta (or cirq, quasar) circuit ``["H(0)", "CX(0, 1)"]`` becomes a
qiskit circuit ``["H(1)", "CX(1, 0)"]``. This is how we guarantee that
the probability vectors are the same.
"""
@staticmethod
def from_qusetta(circuit: List[str]) -> qiskit.QuantumCircuit:
"""Convert a qusetta circuit to a qiskit circuit.
Parameters
----------
circuit : list of strings.
See ``help(qusetta)`` for more details on how the list of
strings should be formatted.
Returns
-------
qiskit_circuit : qiskit.QuantumCircuit.
Examples
--------
>>> from qusetta import Qiskit
>>>
>>> circuit = ["H(0)", "CX(0, 1)", "RX(PI/2)(0)", "SWAP(1, 2)"]
>>> qiskit_circuit = Qiskit.from_qusetta(circuit)
See the ``Qiskit`` class docstring for info on how the bit ordering
is changed.
"""
n, new_circuit = -1, []
for gate in circuit:
g, params, qubits = qs.gate_info(gate)
n = max(max(qubits), n)
new_circuit.append((g.lower(), params, qubits))
qiskit_circuit = qiskit.QuantumCircuit(n + 1)
for g, params, qubits in new_circuit:
# ibm is weird and reversed their qubits from everyone else.
# So we reverse them here.
qubits = tuple(n - q for q in qubits)
getattr(qiskit_circuit, g)(*(params + qubits))
return qiskit_circuit
@staticmethod
def to_qusetta(circuit: qiskit.QuantumCircuit) -> List[str]:
"""Convert a qiskit circuit to a qusetta circuit.
Parameters
----------
circuit : qiskit.QuantumCircuit object.
Returns
-------
qs_circuit : list of strings.
See ``help(qusetta)`` for more details on how the list of
strings should be formatted.
Examples
--------
>>> from qusetta import Qiskit
>>> import qiskit
>>>
>>> circuit = qiskit.QuantumCircuit(3)
>>> circuit.h(0)
>>> circuit.cx(0, 1)
>>> circuit.rx(1/2, 0)
>>> circuit.swap(1, 2)
>>>
>>> print(Qiskit.to_qusetta(circuit))
["H(2)", "CX(2, 1)", "RX(0.5)(2)", "SWAP(1, 0)"]
Notice how the bits are reversed. See the ``Qiskit`` class docstring
for more info.
"""
qs_circuit = []
for gate, qubits, _ in circuit: # _ refers to classical bits
g = gate.name.upper()
if g == "MEASURE": # ignore measure gates
continue
elif g == "ID":
g = "I"
elif g == "U1":
g = "RZ" # same up to a phase factor
elif g == "U2":
# see below for why we reverse the qubits
r = circuit.num_qubits - qubits[0].index - 1
qs_circuit.extend([
"RZ(%g - PI/2)(%d)" % (gate.params[1], r),
"RX(PI/2)(%d)" % r,
"RZ(%g + PI/2)(%d)" % (gate.params[0], r)
])
continue
elif g == "U3":
# see below for why we reverse the qubits
r = circuit.num_qubits - qubits[0].index - 1
qs_circuit.extend([
"RZ(%g - PI/2)(%d)" % (gate.params[2], r),
"RX(%g)(%d)" % (gate.params[0], r),
"RZ(%g + PI/2)(%d)" % (gate.params[1], r)
])
continue
if gate.params:
g += "(" + ", ".join(str(x) for x in gate.params) + ")"
# ibm is weird and reversed their qubits from everyone else.
# So we reverse them here.
g += "(" + ", ".join(
str(circuit.num_qubits - q.index - 1)
for q in qubits
) + ")"
qs_circuit.append(g)
return qs_circuit
|
https://github.com/mspronesti/qlearnkit
|
mspronesti
|
import warnings
import logging
import numpy as np
from copy import deepcopy
from typing import List, Dict, Union, Optional
from qiskit import QuantumCircuit
from qiskit.result import Result
from qiskit.providers import Backend
from qiskit.tools import parallel_map
from qiskit.utils import QuantumInstance
from sklearn.exceptions import NotFittedError
from sklearn.base import ClusterMixin
from ..quantum_estimator import QuantumEstimator
from .centroid_initialization import random, kmeans_plus_plus, naive_sharding
from .qkmeans_circuit import construct_circuit
logger = logging.getLogger(__name__)
class QKMeans(ClusterMixin, QuantumEstimator):
"""
The Quantum K-Means algorithm for classification
Note:
The naming conventions follow the KMeans from
sklearn.cluster
Example:
Classify data using the Iris dataset.
.. jupyter-execute::
import numpy as np
import matplotlib.pyplot as plt
from qlearnkit.algorithms import QKMeans
from qiskit import BasicAer
from qiskit.utils import QuantumInstance, algorithm_globals
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
seed = 42
algorithm_globals.random_seed = seed
quantum_instance = QuantumInstance(BasicAer.get_backend('qasm_simulator'),
shots=1024,
optimization_level=1,
seed_simulator=seed,
seed_transpiler=seed)
# Use iris data set for training and test data
X, y = load_iris(return_X_y=True)
num_features = 2
X = np.asarray([x[0:num_features] for x, y_ in zip(X, y) if y_ != 2])
y = np.asarray([y_ for x, y_ in zip(X, y) if y_ != 2])
qkmeans = QKMeans(n_clusters=3,
quantum_instance=quantum_instance
)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=seed)
qkmeans.fit(X_train)
print(qkmeans.labels_)
print(qkmeans.cluster_centers_)
# Plot the results
colors = ['blue', 'orange', 'green']
for i in range(X_train.shape[0]):
plt.scatter(X_train[i, 0], X_train[i, 1], color=colors[qkmeans.labels_[i]])
plt.scatter(qkmeans.cluster_centers_[:, 0], qkmeans.cluster_centers_[:, 1], marker='*', c='g', s=150)
plt.show()
# Predict new points
prediction = qkmeans.predict(X_test)
print(prediction)
"""
def __init__(
self,
n_clusters: int = 6,
quantum_instance: Optional[Union[QuantumInstance, Backend]] = None,
*,
init: Union[str, np.ndarray] = "kmeans++",
n_init: int = 1,
max_iter: int = 30,
tol: float = 1e-4,
random_state: int = 42,
):
"""
Args:
n_clusters:
The number of clusters to form as well as the number of
centroids to generate.
quantum_instance:
the quantum instance to set. Can be a
:class:`~qiskit.utils.QuantumInstance` or a :class:`~qiskit.providers.Backend`
init:
Method of initialization of centroids.
n_init:
Number of time the qkmeans algorithm will be run with
different centroid seeds.
max_iter:
Maximum number of iterations of the qkmeans algorithm for a
single run.
tol:
Tolerance with regard to the difference of the cluster centroids
of two consecutive iterations to declare convergence.
random_state:
Determines random number generation for centroid initialization.
"""
super().__init__(quantum_instance=quantum_instance)
self.n_clusters = n_clusters
self.init = init
self.max_iter = max_iter
self.n_iter_ = 0
self.tol = tol
self.n_init = n_init
self.n_clusters = n_clusters
self.random_state = random_state
self.cluster_centers_ = None
# do not rename : this name is needed for
# `fit_predict` inherited method from
# `ClusterMixin` base class
self.labels_ = None
def _init_centroid(
self, X: np.ndarray, init: Union[str, np.ndarray], random_state: int
):
"""
Initializes the centroids according to the following criteria:
'kmeans++': Create cluster centroids using the k-means++ algorithm.
'random': Create random cluster centroids.
'naive_sharding': Create cluster centroids using deterministic naive sharding algorithm.
If an array is passed, it should be of shape (n_clusters, n_features)
and gives the initial centers.
Args:
X:
Training dataset.
init:
Method of initialization of centroids.
random_state:
Determines random number generation for centroid initialization.
"""
if isinstance(init, str):
if init == "random":
self.cluster_centers_ = random(X, self.n_clusters, random_state)
elif init == "kmeans++":
self.cluster_centers_ = kmeans_plus_plus(
X, self.n_clusters, random_state
)
elif init == "naive":
self.cluster_centers_ = naive_sharding(X, self.n_clusters)
else:
raise ValueError(
f"Unknown centroids initialization method {init}. "
f"Expected random, kmeans++, naive or vector of "
f"centers, but {init} was provided"
)
else:
self.cluster_centers_ = init
def _recompute_centroids(self):
"""
Reassign centroid value to be the calculated mean value for each cluster.
If a cluster is empty the corresponding centroid remains the same.
"""
for i in range(self.n_clusters):
if np.sum(self.labels_ == i) != 0:
self.cluster_centers_[i] = np.mean(
self.X_train[self.labels_ == i], axis=0
)
def _compute_distances_centroids(self, counts: Dict[str, int]) -> List[int]:
"""
Compute distance, without explicitly measure it, of a point with respect
to all the centroids using a dictionary of counts,
which refers to the following circuit:
.. parsed-literal::
┌───┐ ┌───┐
|0anc>: ┤ H ├────────────■──────┤ H ├────────M
└───┘ | └───┘
┌───┐ ┌────┐ |
|0>: ───┤ H ├───┤ U3 ├───X──────────
└───┘ └────┘ |
┌───┐ ┌────┐ |
|0>: ───┤ H ├───┤ U3 ├───X──────────
└───┘ └────┘
Args:
counts:
Counts resulting after the simulation.
Returns:
The computed distance.
"""
distance_centroids = [0] * self.n_clusters
x = 1
for i in range(0, self.n_clusters):
binary = format(x, "b").zfill(self.n_clusters)
distance_centroids[i] = counts[binary] if binary in counts else 0
x = x << 1
return distance_centroids
def _get_distances_centroids(self, results: Result) -> np.ndarray:
"""
Retrieves distances from counts via :func:`_compute_distances_centroids`
Args:
results: :class:`~qiskit.Result` object of execution results
Returns:
np.ndarray of distances
"""
counts = results.get_counts()
# compute distance from centroids using counts
distances_list = list(
map(lambda count: self._compute_distances_centroids(count), counts)
)
return np.asarray(distances_list)
def _construct_circuits(self, X_test: np.ndarray) -> List[QuantumCircuit]:
"""
Creates the circuits to be executed on
the gated quantum computer for the classification
process
Args:
X_test: The unclassified input data.
Returns:
List of quantum circuits created for the computation
"""
logger.info("Starting circuits construction ...")
"""
circuits = []
for xt in X_test:
circuits.append(construct_circuit(xt, self.cluster_centers_, self.n_clusters))
"""
circuits = parallel_map(
construct_circuit,
X_test,
task_args=[self.cluster_centers_, self.n_clusters],
)
logger.info("Done.")
return circuits
def fit(self, X: np.ndarray, y: np.ndarray = None):
"""
Fits the model using X as training dataset
and y as training labels. For the qkmeans algorithm y is ignored.
The fit model creates clusters from the training dataset given as input
Args:
X: training dataset
y: Ignored.
Kept here for API consistency
Returns:
trained QKMeans object
"""
self.X_train = np.asarray(X)
self._init_centroid(self.X_train, self.init, self.random_state)
self.labels_ = np.zeros(self.X_train.shape[0])
error = np.inf
self.n_iter_ = 0
# while error not below tolerance, reiterate the
# centroid computation for a maximum of `max_iter` times
while error > self.tol and self.n_iter_ < self.max_iter:
# construct circuits using training data
# notice: the construction uses the centroids
# which are recomputed after every iteration
circuits = self._construct_circuits(self.X_train)
# executing and computing distances from centroids
results = self.execute(circuits)
distances = self._get_distances_centroids(results)
# assigning clusters and recomputing centroids
self.labels_ = np.argmin(distances, axis=1)
cluster_centers_old = deepcopy(self.cluster_centers_)
self._recompute_centroids()
# evaluating error and updating iteration count
error = np.linalg.norm(self.cluster_centers_ - cluster_centers_old)
self.n_iter_ = self.n_iter_ + 1
if self.n_iter_ == self.max_iter:
warnings.warn(
f"QKMeans failed to converge after " f"{self.max_iter} iterations."
)
return self
def predict(self, X_test: np.ndarray) -> np.ndarray:
"""Predict the labels of the provided data.
Args:
X_test: ndarray, test samples
Returns:
Index of the cluster each sample belongs to.
"""
if self.labels_ is None:
raise NotFittedError(
"This QKMeans instance is not fitted yet. "
"Call 'fit' with appropriate arguments before using "
"this estimator."
)
circuits = self._construct_circuits(X_test)
results = self.execute(circuits)
distances = self._get_distances_centroids(results)
predicted_labels = np.argmin(distances, axis=1)
return predicted_labels
def score(
self,
X: np.ndarray,
y: np.ndarray = None,
sample_weight: Optional[np.ndarray] = None,
) -> float:
"""
Returns Mean Silhouette Coefficient for all samples.
Args:
X: array of features
y: Ignored.
Not used, present here for API consistency by convention.
sample_weight: Ignored.
Not used, present here for API consistency by convention.
Returns:
Mean Silhouette Coefficient for all samples.
"""
from sklearn.metrics import silhouette_score
predicted_labels = self.predict(X)
return silhouette_score(X, predicted_labels)
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import QuantumCircuit,Aer,transpile
from qiskit.visualization import plot_state_qsphere
from math import pi
backend = Aer.get_backend("aer_simulator_statevector")
qc = QuantumCircuit(3)
qc.rx(pi, 0)
qc.ry(pi/8, 2)
qc.swap(0, 2)
qc.h(0)
qc.cp(pi/2,0, 1)
qc.cp(pi/4, 0, 2)
qc.h(1)
qc.cp(pi/2, 1, 2)
qc.h(2)
qc.save_statevector()
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
statevector = result.get_statevector()
plot_state_qsphere(statevector)
from qiskit.quantum_info import DensityMatrix, \
Operator
from qiskit.visualization import plot_state_city
dens_mat = 0.5*DensityMatrix.from_label('11') + \
0.5*DensityMatrix.from_label('+0')
tt_op = Operator.from_label('TT')
dens_mat = dens_mat.evolve(tt_op)
plot_state_city(dens_mat)
from qiskit import QuantumCircuit,Aer,transpile
from qiskit.visualization import plot_bloch_multivector
from math import pi
backend = Aer.get_backend("aer_simulator_statevector")
qc = QuantumCircuit(3)
qc.rx(pi, 0)
qc.ry(pi/8, 2)
qc.swap(0, 2)
qc.h(0)
qc.cp(pi/2,0, 1)
qc.cp(pi/4, 0, 2)
qc.h(1)
qc.cp(pi/2, 1, 2)
qc.h(2)
qc.save_statevector()
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
statevector = result.get_statevector()
plot_bloch_multivector(statevector)
from qiskit.quantum_info import DensityMatrix, \
Operator
from qiskit.visualization import plot_state_hinton
dens_mat = 0.5*DensityMatrix.from_label('11') + \
0.5*DensityMatrix.from_label('+0')
tt_op = Operator.from_label('TT')
dens_mat = dens_mat.evolve(tt_op)
plot_state_hinton(dens_mat)
from qiskit.quantum_info import DensityMatrix, \
Operator
from qiskit.visualization import plot_state_paulivec
dens_mat = 0.5*DensityMatrix.from_label('11') + \
0.5*DensityMatrix.from_label('+0')
tt_op = Operator.from_label('TT')
dens_mat = dens_mat.evolve(tt_op)
plot_state_paulivec(dens_mat)
|
https://github.com/googlercolin/Qiskit-Course
|
googlercolin
|
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), Pauli operators (X, Y, Z), and the identity operator (I)
from qiskit.opflow import Zero, One, X, Y, Z, I
# Returns the XXX Heisenberg model for 3 spin-1/2 particles in a line
def ex1_compute_H_heis3():
# FILL YOUR CODE IN HERE
H = (I^X^X) + (X^X^I) + (I^Y^Y) + (Y^Y^I) + (I^Z^Z) + (Z^Z^I)
# Return Hamiltonian
return H
from qc_grader.challenges.qgss_2022 import grade_lab4_ex1
# The grading function is expecting a PauliSumOp operator
grade_lab4_ex1(ex1_compute_H_heis3())
# Returns the time evolution operator U_heis3(t) for a given time t assuming an XXX Heisenberg Hamiltonian for 3 spins-1/2 particles in a line
def ex2_compute_U_heis3(t):
# FILL YOUR CODE IN HERE
H = ex1_compute_H_heis3()
U = (t*H).exp_i()
return U
from qc_grader.challenges.qgss_2022 import grade_lab4_ex2
# The grading function is expecting a funtion that returns PauliSumOp operator
grade_lab4_ex2(ex2_compute_U_heis3)
# Define array of time points
ts = np.linspace(0, np.pi, 100)
# Define initial state |110>
initial_state = One^One^Zero
# Compute probability of remaining in |110> state over the array of time points
# ~initial_state gives the bra of the initial state (<110|)
# @ is short hand for matrix multiplication
# ex2_compute_U_heis3(t) is the unitary time evolution at time t
# t needs to be wrapped with float(t) to avoid a bug
# (...).eval() returns the inner product <110|ex2_compute_U_heis3(t)|110>
# np.abs(...)**2 is the modulus squared of the innner product which is the expectation value, or probability, of remaining in |110>
probs_110 = [np.abs((~initial_state @ ex2_compute_U_heis3(float(t)) @ initial_state).eval())**2 for t in ts]
# Plot evolution of |110>
plt.plot(ts, probs_110, linewidth=2)
plt.xlabel('time')
plt.ylabel(r'probability of state $|110\rangle$')
plt.title(r'Evolution of state $|110\rangle$ under $H_{Heis3}$')
plt.ylim([-0.05,1.05])
plt.grid()
plt.show()
!pip install qiskit_ignis --quiet
# Importing standard Qiskit modules
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# load IBMQ Account data
# IBMQ.save_account(TOKEN) # replace TOKEN with your API token string (https://quantum-computing.ibm.com/lab/docs/iql/manage/account/ibmq)
provider = IBMQ.load_account()
# Get backend for experiment
provider = IBMQ.get_provider(hub='ibm-q')
manila = provider.get_backend('ibmq_manila')
# properties = manila.properties()
# Simulated backend based on ibmq_manila's device noise profile
sim_noisy_manila = QasmSimulator.from_backend(provider.get_backend('ibmq_manila'))
# Noiseless simulated backend
sim = QasmSimulator()
# Parameterize variable t to be evaluated at t=pi later
t = Parameter('t')
# Build a subcircuit for XX(t) two-qubit gate
def compute_XX_gate(t):
XX_qr = QuantumRegister(2)
XX_qc = QuantumCircuit(XX_qr, name='XX')
XX_qc.ry(np.pi/2,[0,1])
XX_qc.cnot(0,1)
XX_qc.rz(2 * t, 1)
XX_qc.cnot(0,1)
XX_qc.ry(-np.pi/2,[0,1])
# Convert custom quantum circuit into a gate
XX = XX_qc.to_instruction()
return XX
# Build a subcircuit for YY(t) two-qubit gate
def ex3_compute_YY_gate(t):
# FILL YOUR CODE IN HERE
YY_qr = QuantumRegister(2)
YY_qc = QuantumCircuit(YY_qr, name='YY')
YY_qc.s(0)
YY_qc.s(1)
XX = compute_XX_gate(t)
YY_qc.append(XX, [YY_qr[0], YY_qr[1]])
YY_qc.sdg(0)
YY_qc.sdg(1)
YY = YY_qc.to_instruction()
return YY
from qc_grader.challenges.qgss_2022 import grade_lab4_ex3
# The grading function is expecting an Instruction
grade_lab4_ex3(ex3_compute_YY_gate(t))
# Build a subcircuit for ZZ(t) two-qubit gate
def ex4_compute_ZZ_gate(t):
# FILL YOUR CODE IN HERE
ZZ_qr = QuantumRegister(2)
ZZ_qc = QuantumCircuit(ZZ_qr, name='ZZ')
ZZ_qc.h(0)
ZZ_qc.h(1)
XX = compute_XX_gate(t)
ZZ_qc.append(XX, [ZZ_qr[0], ZZ_qr[1]])
ZZ_qc.h(0)
ZZ_qc.h(1)
ZZ = ZZ_qc.to_instruction()
return ZZ
from qc_grader.challenges.qgss_2022 import grade_lab4_ex4
# The grading function is expecting an Instruction
grade_lab4_ex4(ex4_compute_ZZ_gate(t))
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# Define two-qubit interactions Parameterized by t
XX = compute_XX_gate(t)
YY = ex3_compute_YY_gate(t)
ZZ = ex4_compute_ZZ_gate(t)
Trot_qr = QuantumRegister(num_qubits)
Trot_qc = QuantumCircuit(Trot_qr, name='Trot')
for i in range(0, num_qubits - 1):
Trot_qc.append(ZZ, [Trot_qr[i], Trot_qr[i+1]])
Trot_qc.append(YY, [Trot_qr[i], Trot_qr[i+1]])
Trot_qc.append(XX, [Trot_qr[i], Trot_qr[i+1]])
# Convert custom quantum circuit into a gate
Trot_gate = Trot_qc.to_instruction()
# Setup experiment parameters
# The final time of the state evolution
target_time = np.pi # DO NOT MODIFY
# Number of trotter steps
trotter_steps = 20 ### CAN BE >= 4
# Select which qubits to use for the simulation
q_regs = [0,1,2]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(5)
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on manila qubits (q_5, q_3, q_1) corresponding to the state |110>)
qc.x([q_regs[2], q_regs[1]]) # For example this could be (q_regs=[2, 1, 0] which corresponds to => |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, q_regs)
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({t: target_time/trotter_steps})
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, q_regs)
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw() # only view trotter gates
shots = 8192
reps = 4
# Pick the simulated or real backend for manila
# backend = sim # Noiseless simulator
backend = sim_noisy_manila # Simulator that mimics ibmq_manila
# backend = manila # The real manila backend
jobs = []
for _ in range(reps):
# Execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
for job in jobs:
job_monitor(job)
try:
if job.error_message() is not None:
print(job.error_message())
except:
pass
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
fids = []
for job in jobs:
fid = state_tomo(job.result(), st_qcs)
fids.append(fid)
# Share tomography fidelity of discord to compete and collaborate with other students
print('state tomography fidelity on ' + str(backend) + ' = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
# Share what lectures and techniques were useful in optimizing your results
print('Inspiration: Measurement error mitigation, Olivia Lanes\'s 2nd lecture')
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/shaurya010/Shor-s-Algorithm-
|
shaurya010
|
from qiskit import IBMQ
from qiskit.utils import QuantumInstance
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API KEY HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator') # Specifies the quantum device
print('\n Shors Algorithm')
print('--------------------')
print('\nExecuting...\n')
factors = Shor(QuantumInstance(backend, shots=100, skip_qobj_validation=False))
result_dict = factors.factor(N=21, a=2) # Where N is the integer to be factored
result = result_dict.factors
print(result)
print('\nPress any key to close')
input()
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
#Program 2.1 Initialize qubit state
from qiskit import QuantumCircuit
import math
qc = QuantumCircuit(4)
qc.initialize([1,0],0)
qc.initialize([0,1],1)
qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],2)
qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],3)
qc.draw('mpl')
#Program 2.2 Initialize qubit state and show Bloch sphere
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
import math
qc = QuantumCircuit(4)
qc.initialize([1,0],0)
qc.initialize([0,1],1)
qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],2)
qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],3)
state = Statevector.from_instruction(qc)
display(qc.draw('mpl'))
display(state.draw('bloch'))
#Program 2.3 Show Bloch sphere
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
#Program 2.4 Measure qubit state
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(4,4)
qc.initialize([1,0],0)
qc.initialize([1,0],1)
qc.initialize([0,1],2)
qc.initialize([0,1],3)
qc.measure([0,1,2,3],[0,1,2,3])
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
#Program 2.5 Measure qubit state again
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
import math
qc = QuantumCircuit(4,4)
qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],0)
qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],1)
qc.initialize([1/math.sqrt(2), 1j/math.sqrt(2)],2)
qc.initialize([1/math.sqrt(2), -1j/math.sqrt(2)],3)
qc.measure([0,1,2,3],[0,1,2,3])
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
|
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
|
PacktPublishing
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020
@author: hassi
"""
print("Ch 7: Understanding your circuits with the unitary simulator")
print("------------------------------------------------------------")
# Import the required Qiskit classes
from qiskit import(QuantumCircuit, execute, Aer)
# Import some math that we might need
from math import pow
import numpy as np
np.set_printoptions(precision=3)
# Create some circuits
def circuits():
circuits=[]
# Circuit 1 - one qubit in superposition
circuit1 = QuantumCircuit(1,1)
circuit1.h(0)
# Circuit 2 - two qubits in superposition
circuit2 = QuantumCircuit(2,2)
circuit2.h([0,1])
# Circuit 3 - two entangled qubits
circuit3 = QuantumCircuit(2,2)
circuit3.h([0])
circuit3.cx(0,1)
# Bundle the circuits in a list and return the list
circuits=[circuit1,circuit2,circuit3]
return(circuits)
# Get unitary matrix from unitary simulator
def show_unitary(circuit):
global unit
backend = Aer.get_backend('unitary_simulator')
unit=execute(circuit, backend).result().get_unitary(circuit)
print("Unitary matrix for the circuit:\n-------------------------------\n",unit)
# Calculate and display the unitary matrix
def calc_unitary(circuit,unitary):
# Set number of shots
shots=1000
# Calculate possible number of outcomes, 2^n qubits
binary=int(pow(2,circuit.width()/2))
# Set the binary key for correct binary conversion
bin_key='0'+str(int(circuit.width()/2))+'b'
# Create a qubit vector based on all qubits in the ground state |0> and a results list for all possible outcomes.
vector=[1]
outcomes=[format(0, bin_key)+":"]
for q in range (1,binary):
vector.append(0)
outcomes.append(format(q, bin_key)+":")
qubits=np.array(vector)
# Calculate the dot product of the unitary matrix and the qubits set by the qubits parameter.
a_thru_d=np.dot(unitary,qubits)
# Print the probabilities (counts) of the calculated outcome.
calc_counts={}
for out in range (0,len(a_thru_d)):
calc_counts[outcomes[out]]=(int(pow(abs(a_thru_d[out]),2)*shots))
print("\nCalculated counts:\n------------------\n",calc_counts)
# Automate creation of measurement gates from number of qubits
# Run the circuit on the backend
if circuit.width()==2:
circuit.measure([0],[0])
else:
circuit.measure([0,1],[0,1])
backend_count = Aer.get_backend('qasm_simulator')
counts=execute(circuit, backend_count,shots=shots).result().get_counts(circuit)
# Print the counts of the measured outcome.
print("\nExecuted counts:\n----------------\n",counts,"\n")
# Main loop
def main():
user_input=1
print("\nEnter the number for the circuit to explore:\n--------------------------------------------")
while user_input!=0:
print("\n0. Exit \n1. One qubit superposition\n2. Two qubit superposition\n3. Two qubit entanglement\n4. Import QASM from IBM Quantum Experience")
user_input=int(input())
if user_input!=0:
if user_input==4:
# From Qasm to Qiskit
print("Paste a QASM string after stripping off any measurement gates:")
qc = QuantumCircuit.from_qasm_str(input())
print("\nImported circuit:\n-----------------")
else:
circ=circuits()
qc=circ[user_input-1]
print("\nSelected circuit:\n-----------------")
print(qc)
show_unitary(qc)
calc_unitary(qc,unit)
else:
print("Exiting")
if __name__ == '__main__':
main()
|
https://github.com/minminjao/qiskit1
|
minminjao
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from numpy import pi
qreg_q = QuantumRegister(3, 'q')
creg_c = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.u(0, pi / 4, pi / 4, qreg_q[0]).c_if(creg_c, 0)
circuit.x(qreg_q[0])
circuit.measure(qreg_q[0], creg_c[0])
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
counts = execute(circuit, backend=simulator, shots=1000).result().get_counts(circuit)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Tests for qiskit-terra/qiskit/quantum_info/synthesis/xx_decompose/qiskit.py .
"""
from statistics import mean
import unittest
import ddt
import numpy as np
from scipy.stats import unitary_group
import qiskit
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info.synthesis.xx_decompose.decomposer import (
XXDecomposer,
TwoQubitWeylDecomposition,
)
from .utilities import canonical_matrix
EPSILON = 1e-8
@ddt.ddt
class TestXXDecomposer(unittest.TestCase):
"""Tests for decomposition of two-qubit unitaries over discrete gates from XX family."""
decomposer = XXDecomposer(euler_basis="PSX")
def __init__(self, *args, seed=42, **kwargs):
super().__init__(*args, **kwargs)
self._random_state = np.random.Generator(np.random.PCG64(seed))
def test_random_compilation(self):
"""Test that compilation gives correct results."""
for _ in range(100):
unitary = unitary_group.rvs(4, random_state=self._random_state)
unitary /= np.linalg.det(unitary) ** (1 / 4)
# decompose into CX, CX/2, and CX/3
circuit = self.decomposer(unitary, approximate=False)
decomposed_unitary = Operator(circuit).data
self.assertTrue(np.all(unitary - decomposed_unitary < EPSILON))
def test_compilation_determinism(self):
"""Test that compilation is stable under multiple calls."""
for _ in range(10):
unitary = unitary_group.rvs(4, random_state=self._random_state)
unitary /= np.linalg.det(unitary) ** (1 / 4)
# decompose into CX, CX/2, and CX/3
circuit1 = self.decomposer(unitary, approximate=False)
circuit2 = self.decomposer(unitary, approximate=False)
self.assertEqual(circuit1, circuit2)
@ddt.data(np.pi / 3, np.pi / 5, np.pi / 2)
def test_default_embodiment(self, angle):
"""Test that _default_embodiment actually does yield XX gates."""
embodiment = self.decomposer._default_embodiment(angle)
embodiment_matrix = Operator(embodiment).data
self.assertTrue(np.all(canonical_matrix(angle, 0, 0) - embodiment_matrix < EPSILON))
def test_check_embodiment(self):
"""Test that XXDecomposer._check_embodiments correctly diagnoses il/legal embodiments."""
# build the member of the XX family corresponding to a single CX
good_angle = np.pi / 2
good_embodiment = qiskit.QuantumCircuit(2)
good_embodiment.h(0)
good_embodiment.cx(0, 1)
good_embodiment.h(1)
good_embodiment.rz(np.pi / 2, 0)
good_embodiment.rz(np.pi / 2, 1)
good_embodiment.h(1)
good_embodiment.h(0)
good_embodiment.global_phase += np.pi / 4
# mismatch two members of the XX family
bad_angle = np.pi / 10
bad_embodiment = qiskit.QuantumCircuit(2)
# "self.assertDoesNotRaise"
XXDecomposer(embodiments={good_angle: good_embodiment})
self.assertRaises(
qiskit.exceptions.QiskitError, XXDecomposer, embodiments={bad_angle: bad_embodiment}
)
def test_compilation_improvement(self):
"""Test that compilation to CX, CX/2, CX/3 improves over CX alone."""
slope, offset = (64 * 90) / 1000000, 909 / 1000000 + 1 / 1000
strength_table = self.decomposer._strength_to_infidelity(
basis_fidelity={
strength: 1 - (slope * strength / (np.pi / 2) + offset)
for strength in [np.pi / 2, np.pi / 4, np.pi / 6]
},
approximate=True,
)
limited_strength_table = {np.pi / 2: strength_table[np.pi / 2]}
clever_costs = []
naive_costs = []
for _ in range(200):
unitary = unitary_group.rvs(4, random_state=self._random_state)
unitary /= np.linalg.det(unitary) ** (1 / 4)
weyl_decomposition = TwoQubitWeylDecomposition(unitary)
target = [getattr(weyl_decomposition, x) for x in ("a", "b", "c")]
if target[-1] < -EPSILON:
target = [np.pi / 2 - target[0], target[1], -target[2]]
# decompose into CX, CX/2, and CX/3
clever_costs.append(self.decomposer._best_decomposition(target, strength_table)["cost"])
naive_costs.append(
self.decomposer._best_decomposition(target, limited_strength_table)["cost"]
)
# the following are taken from Fig 14 of the XX synthesis paper
self.assertAlmostEqual(mean(clever_costs), 1.445e-2, delta=5e-3)
self.assertAlmostEqual(mean(naive_costs), 2.058e-2, delta=5e-3)
def test_error_on_empty_basis_fidelity(self):
"""Test synthesizing entangling gate with no entangling basis fails."""
decomposer = XXDecomposer(basis_fidelity={})
qc = QuantumCircuit(2)
qc.cx(0, 1)
mat = Operator(qc).to_matrix()
with self.assertRaisesRegex(
qiskit.exceptions.QiskitError,
"Attempting to synthesize entangling gate with no controlled gates in basis set.",
):
decomposer(mat)
def test_no_error_on_empty_basis_fidelity_trivial_target(self):
"""Test synthesizing non-entangling gate with no entangling basis succeeds."""
decomposer = XXDecomposer(basis_fidelity={})
qc = QuantumCircuit(2)
qc.x(0)
qc.y(1)
mat = Operator(qc).to_matrix()
dqc = decomposer(mat)
self.assertTrue(np.allclose(mat, Operator(dqc).to_matrix()))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure([0, 1], [0, 1])
circ.draw("mpl")
from qiskit import transpile, schedule as build_schedule
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
transpiled_circ = transpile(circ, backend) # Undefined Hadamard is replaced by U1
schedule = build_schedule(transpiled_circ, backend)
schedule.draw()
from qiskit import pulse
with pulse.build() as h_q0:
pulse.play(pulse.library.Gaussian(duration=256, amp=0.2, sigma=50, name='custom'),
pulse.DriveChannel(0))
circ.add_calibration('h', [0], h_q0)
schedule = build_schedule(circ, backend)
schedule.draw()
circ = QuantumCircuit(2, 2)
circ.x(0)
circ.x(0)
circ.x(1)
circ.measure([0, 1], [0, 1])
circ.draw("mpl")
schedule = build_schedule(circ, backend, method="as_late_as_possible")
schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw()
schedule = build_schedule(circ, backend, method="as_soon_as_possible")
schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
from matplotlib.pyplot import bar
labels = []
L = []
for i in range(8):
labels = labels + [i+1]
L = L + [1]
# visualize the values of elements in the list
bar(labels,L)
#
# 1st step - query
#
# 4th element is marked flip the sign
L[3] = -1 * L[3]
# visualize the values of elements in the list
bar(labels,L)
#
# 1st step - inversion
#
import numpy as np
# find reflection over the mean
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
# reflection over the mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
# visualize the values of elements in the list
bar(labels,L)
#
# 2nd step - query
#
L[3] = -1 * L[3]
# visualize the values of elements in the list
bar(labels,L)
#
# 2nd step - inversion
#
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
# reflection over the mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
# visualize the values of elements in the list
bar(labels,L)
#
# your code is here
#
# Construct the list with all elements 1
def query(L):
L[3] = -1 * L[3]
return L
def inversion(L):
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
# reflection over the mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
return L
# iterate same steps 3 times
for i in range(3):
L = query(L)
L = inversion(L)
# visualize the values of elements in the list
bar(labels,L)
#
# your code is here
#
labels = []
L = []
for i in range(16):
labels = labels + [i+1]
L = L + [1]
def query(L):
L[10] = -1 * L[10]
return L
def inversion(L):
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
# reflection over the mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
return L
# iterate the game 16 times
for i in range(1, 17):
L = query(L)
L = inversion(L)
print("Value of 11th element after ", i, " iteration: ", L[10] )
print()
# visualize the values of elements in the list
bar(labels,L)
#
# your code is here
#
N = 8
marked = 1
L = []
for i in range(N):
L = L + [1/(N**0.5)]
# print the elements of a given list with a given precision
def print_list(L,precision):
output = ""
for i in range(len(L)):
output = output + str(round(L[i],precision))+" "
print(output)
print_list(L,3)
for i in range(10):
print((i+1),"th iteration:")
# flip the sign of the marked element
L[marked] = -1 * L[marked]
# print after query phase
print_list(L,3)
# summation of all values
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
print("mean = ",round(mean,3))
# reflection over mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
# calculate the length of the list
length_of_list = 0
for j in range(len(L)):
length_of_list += L[j]*L[j]
print("length of list is",round(length_of_list,3))
# print after inversion phase
print_list(L,3)
print()
# visualize the values of elements in the list
bar(labels,L)
#
# your code is here
#
N = 16
marked_elements = [0,2,9]
L = []
for i in range(N):
L = L + [1/(N**0.5)]
# print the elements of a given list with a given precision
def print_list(L,precision):
output = ""
for i in range(len(L)):
output = output + str(round(L[i],precision))+" "
print(output)
print_list(L,3)
for i in range(10):
print((i+1),"th iteration:")
# flip the sign of the marked element
for marked in marked_elements:
L[marked] = -1 * L[marked]
# print after query phase
print_list(L,3)
# summation of all values
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
# reflection over mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
# calculate the length of the list
length_of_list = 0
for j in range(len(L)):
length_of_list += L[j]*L[j]
print("length of list is",round(length_of_list,3))
# print after inversion phase
print_list(L,3)
print()
#
# your code is here
#
N = 16
marked_elements = range(12)
L = []
for i in range(N):
L = L + [1/(N**0.5)]
# print the elements of a given list with a given precision
def print_list(L,precision):
output = ""
for i in range(len(L)):
output = output + str(round(L[i],precision))+" "
print(output)
print_list(L,3)
for i in range(10):
print((i+1),"th iteration:")
# flip the sign of the marked element
for marked in marked_elements:
L[marked] = -1 * L[marked]
# print after query phase
print_list(L,3)
# summation of all values
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
# reflection over mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
# calculate the length of the list
length_of_list = 0
for j in range(len(L)):
length_of_list += L[j]*L[j]
print("length of list is",round(length_of_list,3))
# print after inversion phase
print_list(L,3)
print()
|
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=unused-argument
"""Waveform generators.
A collection of functions that generate drawings from formatted input data.
See py:mod:`qiskit.visualization.pulse_v2.types` for more info on the required data.
In this module the input data is `types.PulseInstruction`.
An end-user can write arbitrary functions that generate custom drawings.
Generators in this module are called with the `formatter` and `device` kwargs.
These data provides stylesheet configuration and backend system configuration.
The format of generator is restricted to:
```python
def my_object_generator(data: PulseInstruction,
formatter: Dict[str, Any],
device: DrawerBackendInfo) -> List[ElementaryData]:
pass
```
Arbitrary generator function satisfying the above format can be accepted.
Returned `ElementaryData` can be arbitrary subclasses that are implemented in
the plotter API.
"""
from __future__ import annotations
import re
from fractions import Fraction
from typing import Any
import numpy as np
from qiskit import pulse, circuit
from qiskit.pulse import instructions, library
from qiskit.visualization.exceptions import VisualizationError
from qiskit.visualization.pulse_v2 import drawings, types, device_info
def gen_filled_waveform_stepwise(
data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo
) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]:
"""Generate filled area objects of the real and the imaginary part of waveform envelope.
The curve of envelope is not interpolated nor smoothed and presented
as stepwise function at each data point.
Stylesheets:
- The `fill_waveform` style is applied.
Args:
data: Waveform instruction data to draw.
formatter: Dictionary of stylesheet settings.
device: Backend configuration.
Returns:
List of `LineData`, `BoxData`, or `TextData` drawings.
Raises:
VisualizationError: When the instruction parser returns invalid data format.
"""
# generate waveform data
waveform_data = _parse_waveform(data)
channel = data.inst.channel
# update metadata
meta = waveform_data.meta
qind = device.get_qubit_index(channel)
meta.update({"qubit": qind if qind is not None else "N/A"})
if isinstance(waveform_data, types.ParsedInstruction):
# Draw waveform with fixed shape
xdata = waveform_data.xvals
ydata = waveform_data.yvals
# phase modulation
if formatter["control.apply_phase_modulation"]:
ydata = np.asarray(ydata, dtype=complex) * np.exp(1j * data.frame.phase)
else:
ydata = np.asarray(ydata, dtype=complex)
return _draw_shaped_waveform(
xdata=xdata, ydata=ydata, meta=meta, channel=channel, formatter=formatter
)
elif isinstance(waveform_data, types.OpaqueShape):
# Draw parametric pulse with unbound parameters
# parameter name
unbound_params = []
for pname, pval in data.inst.pulse.parameters.items():
if isinstance(pval, circuit.ParameterExpression):
unbound_params.append(pname)
pulse_data = data.inst.pulse
if isinstance(pulse_data, library.SymbolicPulse):
pulse_shape = pulse_data.pulse_type
else:
pulse_shape = "Waveform"
return _draw_opaque_waveform(
init_time=data.t0,
duration=waveform_data.duration,
pulse_shape=pulse_shape,
pnames=unbound_params,
meta=meta,
channel=channel,
formatter=formatter,
)
else:
raise VisualizationError("Invalid data format is provided.")
def gen_ibmq_latex_waveform_name(
data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo
) -> list[drawings.TextData]:
r"""Generate the formatted instruction name associated with the waveform.
Channel name and ID string are removed and the rotation angle is expressed in units of pi.
The controlled rotation angle associated with the CR pulse name is divided by 2.
Note that in many scientific articles the controlled rotation angle implies
the actual rotation angle, but in IQX backend the rotation angle represents
the difference between rotation angles with different control qubit states.
For example:
- 'X90p_d0_abcdefg' is converted into 'X(\frac{\pi}{2})'
- 'CR90p_u0_abcdefg` is converted into 'CR(\frac{\pi}{4})'
Stylesheets:
- The `annotate` style is applied.
Notes:
This generator can convert pulse names used in the IQX backends.
If pulses are provided by the third party providers or the user defined,
the generator output may be the as-is pulse name.
Args:
data: Waveform instruction data to draw.
formatter: Dictionary of stylesheet settings.
device: Backend configuration.
Returns:
List of `TextData` drawings.
"""
if data.is_opaque:
return []
style = {
"zorder": formatter["layer.annotate"],
"color": formatter["color.annotate"],
"size": formatter["text_size.annotate"],
"va": "center",
"ha": "center",
}
if isinstance(data.inst, pulse.instructions.Acquire):
systematic_name = "Acquire"
latex_name = None
elif isinstance(data.inst, instructions.Delay):
systematic_name = data.inst.name or "Delay"
latex_name = None
else:
pulse_data = data.inst.pulse
if pulse_data.name:
systematic_name = pulse_data.name
else:
if isinstance(pulse_data, library.SymbolicPulse):
systematic_name = pulse_data.pulse_type
else:
systematic_name = "Waveform"
template = r"(?P<op>[A-Z]+)(?P<angle>[0-9]+)?(?P<sign>[pm])_(?P<ch>[dum])[0-9]+"
match_result = re.match(template, systematic_name)
if match_result is not None:
match_dict = match_result.groupdict()
sign = "" if match_dict["sign"] == "p" else "-"
if match_dict["op"] == "CR":
# cross resonance
if match_dict["ch"] == "u":
op_name = r"{\rm CR}"
else:
op_name = r"\overline{\rm CR}"
# IQX name def is not standard. Echo CR is annotated with pi/4 rather than pi/2
angle_val = match_dict["angle"]
frac = Fraction(int(int(angle_val) / 2), 180)
if frac.numerator == 1:
angle = rf"\pi/{frac.denominator:d}"
else:
angle = r"{num:d}/{denom:d} \pi".format(
num=frac.numerator, denom=frac.denominator
)
else:
# single qubit pulse
op_name = r"{{\rm {}}}".format(match_dict["op"])
angle_val = match_dict["angle"]
if angle_val is None:
angle = r"\pi"
else:
frac = Fraction(int(angle_val), 180)
if frac.numerator == 1:
angle = rf"\pi/{frac.denominator:d}"
else:
angle = r"{num:d}/{denom:d} \pi".format(
num=frac.numerator, denom=frac.denominator
)
latex_name = rf"{op_name}({sign}{angle})"
else:
latex_name = None
text = drawings.TextData(
data_type=types.LabelType.PULSE_NAME,
channels=data.inst.channel,
xvals=[data.t0 + 0.5 * data.inst.duration],
yvals=[-formatter["label_offset.pulse_name"]],
text=systematic_name,
latex=latex_name,
ignore_scaling=True,
styles=style,
)
return [text]
def gen_waveform_max_value(
data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo
) -> list[drawings.TextData]:
"""Generate the annotation for the maximum waveform height for
the real and the imaginary part of the waveform envelope.
Maximum values smaller than the vertical resolution limit is ignored.
Stylesheets:
- The `annotate` style is applied.
Args:
data: Waveform instruction data to draw.
formatter: Dictionary of stylesheet settings.
device: Backend configuration.
Returns:
List of `TextData` drawings.
"""
if data.is_opaque:
return []
style = {
"zorder": formatter["layer.annotate"],
"color": formatter["color.annotate"],
"size": formatter["text_size.annotate"],
"ha": "center",
}
# only pulses.
if isinstance(data.inst, instructions.Play):
# pulse
operand = data.inst.pulse
if isinstance(operand, (pulse.ParametricPulse, pulse.SymbolicPulse)):
pulse_data = operand.get_waveform()
else:
pulse_data = operand
xdata = np.arange(pulse_data.duration) + data.t0
ydata = pulse_data.samples
else:
return []
# phase modulation
if formatter["control.apply_phase_modulation"]:
ydata = np.asarray(ydata, dtype=complex) * np.exp(1j * data.frame.phase)
else:
ydata = np.asarray(ydata, dtype=complex)
texts = []
# max of real part
re_maxind = np.argmax(np.abs(ydata.real))
if np.abs(ydata.real[re_maxind]) > 0.01:
# generator shows only 2 digits after the decimal point.
if ydata.real[re_maxind] > 0:
max_val = f"{ydata.real[re_maxind]:.2f}\n\u25BE"
re_style = {"va": "bottom"}
else:
max_val = f"\u25B4\n{ydata.real[re_maxind]:.2f}"
re_style = {"va": "top"}
re_style.update(style)
re_text = drawings.TextData(
data_type=types.LabelType.PULSE_INFO,
channels=data.inst.channel,
xvals=[xdata[re_maxind]],
yvals=[ydata.real[re_maxind]],
text=max_val,
styles=re_style,
)
texts.append(re_text)
# max of imag part
im_maxind = np.argmax(np.abs(ydata.imag))
if np.abs(ydata.imag[im_maxind]) > 0.01:
# generator shows only 2 digits after the decimal point.
if ydata.imag[im_maxind] > 0:
max_val = f"{ydata.imag[im_maxind]:.2f}\n\u25BE"
im_style = {"va": "bottom"}
else:
max_val = f"\u25B4\n{ydata.imag[im_maxind]:.2f}"
im_style = {"va": "top"}
im_style.update(style)
im_text = drawings.TextData(
data_type=types.LabelType.PULSE_INFO,
channels=data.inst.channel,
xvals=[xdata[im_maxind]],
yvals=[ydata.imag[im_maxind]],
text=max_val,
styles=im_style,
)
texts.append(im_text)
return texts
def _draw_shaped_waveform(
xdata: np.ndarray,
ydata: np.ndarray,
meta: dict[str, Any],
channel: pulse.channels.PulseChannel,
formatter: dict[str, Any],
) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]:
"""A private function that generates drawings of stepwise pulse lines.
Args:
xdata: Array of horizontal coordinate of waveform envelope.
ydata: Array of vertical coordinate of waveform envelope.
meta: Metadata dictionary of the waveform.
channel: Channel associated with the waveform to draw.
formatter: Dictionary of stylesheet settings.
Returns:
List of drawings.
Raises:
VisualizationError: When the waveform color for channel is not defined.
"""
fill_objs: list[drawings.LineData | drawings.BoxData | drawings.TextData] = []
resolution = formatter["general.vertical_resolution"]
# stepwise interpolation
xdata: np.ndarray = np.concatenate((xdata, [xdata[-1] + 1]))
ydata = np.repeat(ydata, 2)
re_y = np.real(ydata)
im_y = np.imag(ydata)
time: np.ndarray = np.concatenate(([xdata[0]], np.repeat(xdata[1:-1], 2), [xdata[-1]]))
# setup style options
style = {
"alpha": formatter["alpha.fill_waveform"],
"zorder": formatter["layer.fill_waveform"],
"linewidth": formatter["line_width.fill_waveform"],
"linestyle": formatter["line_style.fill_waveform"],
}
try:
color_real, color_imag = formatter["color.waveforms"][channel.prefix.upper()]
except KeyError as ex:
raise VisualizationError(
f"Waveform color for channel type {channel.prefix} is not defined"
) from ex
# create real part
if np.any(re_y):
# data compression
re_valid_inds = _find_consecutive_index(re_y, resolution)
# stylesheet
re_style = {"color": color_real}
re_style.update(style)
# metadata
re_meta = {"data": "real"}
re_meta.update(meta)
# active xy data
re_xvals = time[re_valid_inds]
re_yvals = re_y[re_valid_inds]
# object
real = drawings.LineData(
data_type=types.WaveformType.REAL,
channels=channel,
xvals=re_xvals,
yvals=re_yvals,
fill=formatter["control.fill_waveform"],
meta=re_meta,
styles=re_style,
)
fill_objs.append(real)
# create imaginary part
if np.any(im_y):
# data compression
im_valid_inds = _find_consecutive_index(im_y, resolution)
# stylesheet
im_style = {"color": color_imag}
im_style.update(style)
# metadata
im_meta = {"data": "imag"}
im_meta.update(meta)
# active xy data
im_xvals = time[im_valid_inds]
im_yvals = im_y[im_valid_inds]
# object
imag = drawings.LineData(
data_type=types.WaveformType.IMAG,
channels=channel,
xvals=im_xvals,
yvals=im_yvals,
fill=formatter["control.fill_waveform"],
meta=im_meta,
styles=im_style,
)
fill_objs.append(imag)
return fill_objs
def _draw_opaque_waveform(
init_time: int,
duration: int,
pulse_shape: str,
pnames: list[str],
meta: dict[str, Any],
channel: pulse.channels.PulseChannel,
formatter: dict[str, Any],
) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]:
"""A private function that generates drawings of stepwise pulse lines.
Args:
init_time: Time when the opaque waveform starts.
duration: Duration of opaque waveform. This can be None or ParameterExpression.
pulse_shape: String that represents pulse shape.
pnames: List of parameter names.
meta: Metadata dictionary of the waveform.
channel: Channel associated with the waveform to draw.
formatter: Dictionary of stylesheet settings.
Returns:
List of drawings.
"""
fill_objs: list[drawings.LineData | drawings.BoxData | drawings.TextData] = []
fc, ec = formatter["color.opaque_shape"]
# setup style options
box_style = {
"zorder": formatter["layer.fill_waveform"],
"alpha": formatter["alpha.opaque_shape"],
"linewidth": formatter["line_width.opaque_shape"],
"linestyle": formatter["line_style.opaque_shape"],
"facecolor": fc,
"edgecolor": ec,
}
if duration is None or isinstance(duration, circuit.ParameterExpression):
duration = formatter["box_width.opaque_shape"]
box_obj = drawings.BoxData(
data_type=types.WaveformType.OPAQUE,
channels=channel,
xvals=[init_time, init_time + duration],
yvals=[
-0.5 * formatter["box_height.opaque_shape"],
0.5 * formatter["box_height.opaque_shape"],
],
meta=meta,
ignore_scaling=True,
styles=box_style,
)
fill_objs.append(box_obj)
# parameter name
func_repr = "{func}({params})".format(func=pulse_shape, params=", ".join(pnames))
text_style = {
"zorder": formatter["layer.annotate"],
"color": formatter["color.annotate"],
"size": formatter["text_size.annotate"],
"va": "bottom",
"ha": "center",
}
text_obj = drawings.TextData(
data_type=types.LabelType.OPAQUE_BOXTEXT,
channels=channel,
xvals=[init_time + 0.5 * duration],
yvals=[0.5 * formatter["box_height.opaque_shape"]],
text=func_repr,
ignore_scaling=True,
styles=text_style,
)
fill_objs.append(text_obj)
return fill_objs
def _find_consecutive_index(data_array: np.ndarray, resolution: float) -> np.ndarray:
"""A helper function to return non-consecutive index from the given list.
This drastically reduces memory footprint to represent a drawing,
especially for samples of very long flat-topped Gaussian pulses.
Tiny value fluctuation smaller than `resolution` threshold is removed.
Args:
data_array: The array of numbers.
resolution: Minimum resolution of sample values.
Returns:
The compressed data array.
"""
try:
vector = np.asarray(data_array, dtype=float)
diff = np.diff(vector)
diff[np.where(np.abs(diff) < resolution)] = 0
# keep left and right edges
consecutive_l = np.insert(diff.astype(bool), 0, True)
consecutive_r = np.append(diff.astype(bool), True)
return consecutive_l | consecutive_r
except ValueError:
return np.ones_like(data_array).astype(bool)
def _parse_waveform(
data: types.PulseInstruction,
) -> types.ParsedInstruction | types.OpaqueShape:
"""A helper function that generates an array for the waveform with
instruction metadata.
Args:
data: Instruction data set
Raises:
VisualizationError: When invalid instruction type is loaded.
Returns:
A data source to generate a drawing.
"""
inst = data.inst
meta: dict[str, Any] = {}
if isinstance(inst, instructions.Play):
# pulse
operand = inst.pulse
if isinstance(operand, (pulse.ParametricPulse, pulse.SymbolicPulse)):
# parametric pulse
params = operand.parameters
duration = params.pop("duration", None)
if isinstance(duration, circuit.Parameter):
duration = None
if isinstance(operand, library.SymbolicPulse):
pulse_shape = operand.pulse_type
else:
pulse_shape = "Waveform"
meta["waveform shape"] = pulse_shape
meta.update(
{
key: val.name if isinstance(val, circuit.Parameter) else val
for key, val in params.items()
}
)
if data.is_opaque:
# parametric pulse with unbound parameter
if duration:
meta.update(
{
"duration (cycle time)": inst.duration,
"duration (sec)": inst.duration * data.dt if data.dt else "N/A",
}
)
else:
meta.update({"duration (cycle time)": "N/A", "duration (sec)": "N/A"})
meta.update(
{
"t0 (cycle time)": data.t0,
"t0 (sec)": data.t0 * data.dt if data.dt else "N/A",
"phase": data.frame.phase,
"frequency": data.frame.freq,
"name": inst.name,
}
)
return types.OpaqueShape(duration=duration, meta=meta)
else:
# fixed shape parametric pulse
pulse_data = operand.get_waveform()
else:
# waveform
pulse_data = operand
xdata = np.arange(pulse_data.duration) + data.t0
ydata = pulse_data.samples
elif isinstance(inst, instructions.Delay):
# delay
xdata = np.arange(inst.duration) + data.t0
ydata = np.zeros(inst.duration)
elif isinstance(inst, instructions.Acquire):
# acquire
xdata = np.arange(inst.duration) + data.t0
ydata = np.ones(inst.duration)
acq_data = {
"memory slot": inst.mem_slot.name,
"register slot": inst.reg_slot.name if inst.reg_slot else "N/A",
"discriminator": inst.discriminator.name if inst.discriminator else "N/A",
"kernel": inst.kernel.name if inst.kernel else "N/A",
}
meta.update(acq_data)
else:
raise VisualizationError(
"Unsupported instruction {inst} by "
"filled envelope.".format(inst=inst.__class__.__name__)
)
meta.update(
{
"duration (cycle time)": inst.duration,
"duration (sec)": inst.duration * data.dt if data.dt else "N/A",
"t0 (cycle time)": data.t0,
"t0 (sec)": data.t0 * data.dt if data.dt else "N/A",
"phase": data.frame.phase,
"frequency": data.frame.freq,
"name": inst.name,
}
)
return types.ParsedInstruction(xvals=xdata, yvals=ydata, meta=meta)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# useful additional packages
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
from qiskit_aer import Aer
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.library import TwoLocal
from qiskit_optimization.applications import Maxcut, Tsp
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import SPSA
from qiskit.utils import algorithm_globals
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
# Generating a graph of 4 nodes
n = 4 # Number of nodes in graph
G = nx.Graph()
G.add_nodes_from(np.arange(0, n, 1))
elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0)]
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
colors = ["r" for node in G.nodes()]
pos = nx.spring_layout(G)
def draw_graph(G, colors, pos):
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
draw_graph(G, colors, pos)
# Computing the weight matrix from the random graph
w = np.zeros([n, n])
for i in range(n):
for j in range(n):
temp = G.get_edge_data(i, j, default=0)
if temp != 0:
w[i, j] = temp["weight"]
print(w)
best_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))]
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i, j] * x[i] * (1 - x[j])
if best_cost_brute < cost:
best_cost_brute = cost
xbest_brute = x
print("case = " + str(x) + " cost = " + str(cost))
colors = ["r" if xbest_brute[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
print("\nBest solution = " + str(xbest_brute) + " cost = " + str(best_cost_brute))
max_cut = Maxcut(w)
qp = max_cut.to_quadratic_program()
print(qp.prettyprint())
qubitOp, offset = qp.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
# solving Quadratic Program using exact classical eigensolver
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
result = exact.solve(qp)
print(result.prettyprint())
# Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver()
result = ee.compute_minimum_eigenvalue(qubitOp)
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
colors = ["r" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
# construct SamplingVQE
optimizer = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer)
# run SamplingVQE
result = vqe.compute_minimum_eigenvalue(qubitOp)
# print results
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("time:", result.optimizer_time)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
# plot results
colors = ["r" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
# create minimum eigen optimizer based on SamplingVQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result.prettyprint())
colors = ["r" if result.x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
# Generating a graph of 3 nodes
n = 3
num_qubits = n**2
tsp = Tsp.create_random_instance(n, seed=123)
adj_matrix = nx.to_numpy_array(tsp.graph)
print("distance\n", adj_matrix)
colors = ["r" for node in tsp.graph.nodes]
pos = [tsp.graph.nodes[node]["pos"] for node in tsp.graph.nodes]
draw_graph(tsp.graph, colors, pos)
from itertools import permutations
def brute_force_tsp(w, N):
a = list(permutations(range(1, N)))
last_best_distance = 1e10
for i in a:
distance = 0
pre_j = 0
for j in i:
distance = distance + w[j, pre_j]
pre_j = j
distance = distance + w[pre_j, 0]
order = (0,) + i
if distance < last_best_distance:
best_order = order
last_best_distance = distance
print("order = " + str(order) + " Distance = " + str(distance))
return last_best_distance, best_order
best_distance, best_order = brute_force_tsp(adj_matrix, n)
print(
"Best order from brute force = "
+ str(best_order)
+ " with total distance = "
+ str(best_distance)
)
def draw_tsp_solution(G, order, colors, pos):
G2 = nx.DiGraph()
G2.add_nodes_from(G)
n = len(order)
for i in range(n):
j = (i + 1) % n
G2.add_edge(order[i], order[j], weight=G[order[i]][order[j]]["weight"])
default_axes = plt.axes(frameon=True)
nx.draw_networkx(
G2, node_color=colors, edge_color="b", node_size=600, alpha=0.8, ax=default_axes, pos=pos
)
edge_labels = nx.get_edge_attributes(G2, "weight")
nx.draw_networkx_edge_labels(G2, pos, font_color="b", edge_labels=edge_labels)
draw_tsp_solution(tsp.graph, best_order, colors, pos)
qp = tsp.to_quadratic_program()
print(qp.prettyprint())
from qiskit_optimization.converters import QuadraticProgramToQubo
qp2qubo = QuadraticProgramToQubo()
qubo = qp2qubo.convert(qp)
qubitOp, offset = qubo.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
result = exact.solve(qubo)
print(result.prettyprint())
# Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver()
result = ee.compute_minimum_eigenvalue(qubitOp)
print("energy:", result.eigenvalue.real)
print("tsp objective:", result.eigenvalue.real + offset)
x = tsp.sample_most_likely(result.eigenstate)
print("feasible:", qubo.is_feasible(x))
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
optimizer = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer)
result = vqe.compute_minimum_eigenvalue(qubitOp)
print("energy:", result.eigenvalue.real)
print("time:", result.optimizer_time)
x = tsp.sample_most_likely(result.eigenstate)
print("feasible:", qubo.is_feasible(x))
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
# create minimum eigen optimizer based on SamplingVQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result.prettyprint())
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Utility functions for debugging and testing.
"""
from typing import Tuple
import numpy as np
from scipy.stats import unitary_group
import qiskit.transpiler.synthesis.aqc.fast_gradient.fast_grad_utils as fgu
def relative_error(a_mat: np.ndarray, b_mat: np.ndarray) -> float:
"""
Computes relative residual between two matrices in Frobenius norm.
"""
return float(np.linalg.norm(a_mat - b_mat, "fro")) / float(np.linalg.norm(b_mat, "fro"))
def make_unit_vector(pos: int, nbits: int) -> np.ndarray:
"""
Makes a unit vector ``e = (0 ... 0 1 0 ... 0)`` of size ``2^n`` with
unit at the position ``num``. **Note**: result depends on bit ordering.
Args:
pos: position of unit in vector.
nbits: number of meaningful bit in the number "pos".
Returns:
unit vector of size ``2^n``.
"""
vec = np.zeros((2**nbits,), dtype=np.int64)
vec[fgu.reverse_bits(pos, nbits, enable=True)] = 1
return vec
def eye_int(n: int) -> np.ndarray:
"""
Creates an identity matrix with integer entries.
Args:
n: number of bits.
Returns:
unit matrix of size ``2^n`` with integer entries.
"""
return np.eye(2**n, dtype=np.int64)
def kron3(a_mat: np.ndarray, b_mat: np.ndarray, c_mat: np.ndarray) -> np.ndarray:
"""
Computes Kronecker product of 3 matrices.
"""
return np.kron(a_mat, np.kron(b_mat, c_mat))
def kron5(
a_mat: np.ndarray, b_mat: np.ndarray, c_mat: np.ndarray, d_mat: np.ndarray, e_mat: np.ndarray
) -> np.ndarray:
"""
Computes Kronecker product of 5 matrices.
"""
return np.kron(np.kron(np.kron(np.kron(a_mat, b_mat), c_mat), d_mat), e_mat)
def rand_matrix(dim: int, kind: str = "complex") -> np.ndarray:
"""
Generates a random complex or integer value matrix.
Args:
dim: matrix size dim-x-dim.
kind: "complex" or "randint".
Returns:
a random matrix.
"""
if kind == "complex":
return (
np.random.rand(dim, dim).astype(np.cfloat)
+ np.random.rand(dim, dim).astype(np.cfloat) * 1j
)
else:
return np.random.randint(low=1, high=100, size=(dim, dim), dtype=np.int64)
def make_test_matrices2x2(n: int, k: int, kind: str = "complex") -> Tuple[np.ndarray, np.ndarray]:
"""
Creates a ``2^n x 2^n`` random matrix made as a Kronecker product of identity
ones and a single 1-qubit gate. This models a layer in quantum circuit with
an arbitrary 1-qubit gate somewhere in the middle.
Args:
n: number of qubits.
k: index of qubit a 1-qubit gate is acting on.
kind: entries of the output matrix are defined as:
"complex", "primes" or "randint".
Returns:
A tuple of (1) ``2^n x 2^n`` random matrix; (2) ``2 x 2`` matrix of 1-qubit
gate used for matrix construction.
"""
if kind == "primes":
a_mat = np.asarray([[2, 3], [5, 7]], dtype=np.int64)
else:
a_mat = rand_matrix(dim=2, kind=kind)
m_mat = kron3(eye_int(k), a_mat, eye_int(n - k - 1))
return m_mat, a_mat
def make_test_matrices4x4(
n: int, j: int, k: int, kind: str = "complex"
) -> Tuple[np.ndarray, np.ndarray]:
"""
Creates a ``2^n x 2^n`` random matrix made as a Kronecker product of identity
ones and a single 2-qubit gate. This models a layer in quantum circuit with
an arbitrary 2-qubit gate somewhere in the middle.
Args:
n: number of qubits.
j: index of the first qubit the 2-qubit gate acting on.
k: index of the second qubit the 2-qubit gate acting on.
kind: entries of the output matrix are defined as:
"complex", "primes" or "randint".
Returns:
A tuple of (1) ``2^n x 2^n`` random matrix; (2) ``4 x 4`` matrix of
2-qubit gate used for matrix construction.
"""
if kind == "primes":
a_mat = np.asarray([[2, 3], [5, 7]], dtype=np.int64)
b_mat = np.asarray([[11, 13], [17, 19]], dtype=np.int64)
c_mat = np.asarray([[47, 53], [41, 43]], dtype=np.int64)
d_mat = np.asarray([[31, 37], [23, 29]], dtype=np.int64)
else:
a_mat, b_mat = rand_matrix(dim=2, kind=kind), rand_matrix(dim=2, kind=kind)
c_mat, d_mat = rand_matrix(dim=2, kind=kind), rand_matrix(dim=2, kind=kind)
if j < k:
m_mat = kron5(eye_int(j), a_mat, eye_int(k - j - 1), b_mat, eye_int(n - k - 1)) + kron5(
eye_int(j), c_mat, eye_int(k - j - 1), d_mat, eye_int(n - k - 1)
)
else:
m_mat = kron5(eye_int(k), b_mat, eye_int(j - k - 1), a_mat, eye_int(n - j - 1)) + kron5(
eye_int(k), d_mat, eye_int(j - k - 1), c_mat, eye_int(n - j - 1)
)
g_mat = np.kron(a_mat, b_mat) + np.kron(c_mat, d_mat)
return m_mat, g_mat
def rand_circuit(num_qubits: int, depth: int) -> np.ndarray:
"""
Generates a random circuit of unit blocks for debugging and testing.
"""
blocks = np.tile(np.arange(num_qubits).reshape(num_qubits, 1), depth)
for i in range(depth):
np.random.shuffle(blocks[:, i])
return blocks[0:2, :].copy()
def rand_su_mat(dim: int) -> np.ndarray:
"""
Generates a random SU matrix.
Args:
dim: matrix size ``dim-x-dim``.
Returns:
random SU matrix.
"""
u_mat = unitary_group.rvs(dim)
u_mat /= np.linalg.det(u_mat) ** (1.0 / float(dim))
return u_mat
|
https://github.com/epelaaez/QuantumLibrary
|
epelaaez
|
import numpy as np
from qiskit.quantum_info import state_fidelity
def schmidt_decomp_even(state):
n = int(np.log2(len(state)))
mat = state.reshape(2 ** (n // 2), 2 ** (n // 2))
u, s, v = np.linalg.svd(mat)
a = [u[:, i].reshape(2 ** (n // 2), 1) for i in range(2 ** (n // 2))]
b = [v[i, :].reshape(2 ** (n // 2), 1) for i in range(2 ** (n // 2))]
new_state = np.sum([np.kron(a[i], b[i]) * s[i] for i in range(2 ** (n // 2))], axis=0)
assert np.isclose(state_fidelity(state, new_state), 1), "Didnt work :("
return a, b, s
n = 2 # must be even
state = np.random.rand(2 ** n)
state = state / np.linalg.norm(state)
a, b, s = schmidt_decomp_even(state)
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Statevector, random_statevector
from sympy import Matrix
qc = QuantumCircuit(n)
qc.ry(2 * np.arccos(s[0]), 0)
qc.draw()
Matrix(np.round(Statevector(qc), 5))
qc.cx(0, 1)
qc.draw()
Matrix(np.round(Statevector(qc), 5))
theta = 2 * np.arccos(a[0][0][0])
phi = np.real(np.log(a[0][1][0] / np.sin(np.arccos(a[0][0][0])), dtype='complex') / 1j)
lamb = np.real(np.log(-a[1][0][0] / np.sin(np.arccos(a[0][0][0])), dtype='complex') / 1j)
qc.u(theta, phi, lamb, 0)
qc.draw()
Matrix(np.round(Statevector(qc), 5))
theta = 2 * np.arccos(b[0][0][0])
phi = np.real(np.log(b[0][1][0] / np.sin(np.arccos(b[0][0][0])), dtype='complex') / 1j)
lamb = np.real(np.log(-b[1][0][0] / np.sin(np.arccos(b[0][0][0])), dtype='complex') / 1j)
qc.u(theta, phi, lamb, 1)
qc.draw()
Matrix(np.round(Statevector(qc.reverse_bits()), 5))
Matrix(np.round(state, 5))
def two_qubit_state(state):
qc = QuantumCircuit(2)
# Normalize state and get Schmidt decomposition
state = state / np.linalg.norm(state)
a, b, s = schmidt_decomp_even(state)
# Phase 1
qc.ry(2 * np.arccos(s[0]), 0)
# Phase 2
qc.cx(0, 1)
# Phase 3
qc.unitary(np.block([a[0].flatten().T, a[1].flatten().T]).reshape(2, 2).T, 0)
# Phase 4
qc.unitary(np.block([b[0].flatten().T, b[1].flatten().T]).reshape(2, 2).T, 1)
return qc
state = random_statevector(4).data
qc = two_qubit_state(state)
qc.decompose().draw()
circ = Statevector(qc.reverse_bits()).data
Matrix(np.round(circ, 5))
Matrix(np.round(state, 5))
for _ in range(100):
state = random_statevector(4).data
qc = two_qubit_state(state)
circ = Statevector(qc.reverse_bits()).data
assert np.allclose(circ, state)
|
https://github.com/anpaschool/quantum-computing
|
anpaschool
|
from qiskit import *
from math import pi
import numpy as np
from qiskit.visualization import *
import matplotlib.pyplot as plt
qc = QuantumCircuit(1)
qc.h(0)
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
plot_bloch_multivector(out)
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
# Show the results
print(result.get_unitary(qc, decimals=3))
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.barrier()
qc.h(1)
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
plot_bloch_multivector(out)
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
# Show the results
print(result.get_unitary(qc, decimals=3))
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.h(2)
qc.barrier()
qc1 = qc.copy()
qc.x(0)
qc.y(1)
qc.z(2)
qc.barrier()
qc2 = qc.copy()
qc.x(0)
qc.y(1)
qc.z(2)
qc.barrier()
qc3 = qc.copy()
qc.h(0)
qc.h(1)
qc.h(2)
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
plot_bloch_multivector(out)
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
# Show the results
print(result.get_unitary(qc, decimals=3))
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc1,backend).result().get_statevector()
print(out)
plot_bloch_multivector(out)
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc2,backend).result().get_statevector()
print(out)
plot_bloch_multivector(out)
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc3,backend).result().get_statevector()
print(out)
plot_bloch_multivector(out)
qc = QuantumCircuit(1)
qc.s(0)
qc.draw(output='mpl')
qc = QuantumCircuit(1)
qc.sdg(0)
qc.draw(output='mpl')
qc = QuantumCircuit(1)
qc.t(0)
qc.draw(output='mpl')
qc = QuantumCircuit(1)
qc.tdg(0)
qc.draw(output='mpl')
qc = QuantumCircuit(1)
qc.x(0)
qc.barrier()
qc1 = qc.copy()
qc.h(0)
qc.barrier()
qc2 = qc.copy()
qc.s(0)
qc.barrier()
qc3 = qc.copy()
qc.s(0)
qc.barrier()
qc4 = qc.copy()
qc.s(0)
qc.barrier()
qc5 = qc.copy()
qc.sdg(0)
qc.h(0)
qc.barrier()
qc6 = qc.copy()
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
plot_bloch_multivector(out)
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
for qc in [qc1,qc2,qc3,qc4,qc5,qc6]:
out = execute(qc,backend).result().get_statevector()
print(out)
|
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.
"""Test RemoveDiagonalGatesBeforeMeasure pass"""
import unittest
from copy import deepcopy
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit.library import U1Gate, CU1Gate
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import RemoveDiagonalGatesBeforeMeasure, DAGFixedPoint
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TesRemoveDiagonalGatesBeforeMeasure(QiskitTestCase):
"""Test remove_diagonal_gates_before_measure optimizations."""
def test_optimize_1rz_1measure(self):
"""Remove a single RZGate
qr0:-RZ--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1z_1measure(self):
"""Remove a single ZGate
qr0:--Z--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.z(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1t_1measure(self):
"""Remove a single TGate, SGate, TdgGate, SdgGate, U1Gate
qr0:--T--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.t(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1s_1measure(self):
"""Remove a single SGate
qr0:--S--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.s(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1tdg_1measure(self):
"""Remove a single TdgGate
qr0:-Tdg-m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.tdg(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1sdg_1measure(self):
"""Remove a single SdgGate
qr0:-Sdg--m-- qr0:--m-
| |
qr1:------|-- ==> qr1:--|-
| |
cr0:------.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.sdg(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1u1_1measure(self):
"""Remove a single U1Gate
qr0:--U1-m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(U1Gate(0.1), [qr[0]])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1rz_1z_1measure(self):
"""Remove a single RZ and leave the other Z
qr0:-RZ--m-- qr0:----m-
| |
qr1:--Z--|-- ==> qr1:--Z-|-
| |
cr0:-----.-- cr0:----.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[0])
circuit.z(qr[1])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.z(qr[1])
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_simple_if_else(self):
"""Test that the pass recurses into an if-else."""
pass_ = RemoveDiagonalGatesBeforeMeasure()
base_test = QuantumCircuit(1, 1)
base_test.z(0)
base_test.measure(0, 0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
test = QuantumCircuit(1, 1)
test.if_else(
(test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(1, 1)
expected.if_else(
(expected.clbits[0], True),
base_expected.copy(),
base_expected.copy(),
expected.qubits,
expected.clbits,
)
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the pass recurses into nested control flow."""
pass_ = RemoveDiagonalGatesBeforeMeasure()
base_test = QuantumCircuit(2, 1)
base_test.cz(0, 1)
base_test.measure(0, 0)
base_expected = QuantumCircuit(2, 1)
base_expected.measure(1, 0)
body_test = QuantumCircuit(2, 1)
body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits)
body_expected = QuantumCircuit(2, 1)
body_expected.for_loop(
(0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits
)
test = QuantumCircuit(2, 1)
test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits)
expected = QuantumCircuit(2, 1)
expected.while_loop(
(expected.clbits[0], True), body_expected, expected.qubits, expected.clbits
)
self.assertEqual(pass_(test), expected)
class TesRemoveDiagonalControlGatesBeforeMeasure(QiskitTestCase):
"""Test remove diagonal control gates before measure."""
def test_optimize_1cz_2measure(self):
"""Remove a single CZGate
qr0:--Z--m--- qr0:--m---
| | |
qr1:--.--|-m- ==> qr1:--|-m-
| | | |
cr0:-----.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1crz_2measure(self):
"""Remove a single CRZGate
qr0:-RZ--m--- qr0:--m---
| | |
qr1:--.--|-m- ==> qr1:--|-m-
| | | |
cr0:-----.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.crz(0.1, qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1cu1_2measure(self):
"""Remove a single CU1Gate
qr0:-CU1-m--- qr0:--m---
| | |
qr1:--.--|-m- ==> qr1:--|-m-
| | | |
cr0:-----.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU1Gate(0.1), [qr[0], qr[1]])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1rzz_2measure(self):
"""Remove a single RZZGate
qr0:--.----m--- qr0:--m---
|zz | |
qr1:--.----|-m- ==> qr1:--|-m-
| | | |
cr0:-------.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rzz(0.1, qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
class TestRemoveDiagonalGatesBeforeMeasureOveroptimizations(QiskitTestCase):
"""Test situations where remove_diagonal_gates_before_measure should not optimize"""
def test_optimize_1cz_1measure(self):
"""Do not remove a CZGate because measure happens on only one of the wires
Compare with test_optimize_1cz_2measure.
qr0:--Z--m---
| |
qr1:--.--|---
|
cr0:-----.---
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = deepcopy(dag)
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(expected, after)
def test_do_not_optimize_with_conditional(self):
"""Diagonal gates with conditionals on a measurement target.
See https://github.com/Qiskit/qiskit-terra/pull/2208#issuecomment-487238819
░ ┌───┐┌─┐
qr_0: |0>────────────░─┤ H ├┤M├
┌─────────┐ ░ └───┘└╥┘
qr_1: |0>┤ Rz(0.1) ├─░───────╫─
└─┬──┴──┬─┘ ░ ║
cr_0: 0 ══╡ = 1 ╞═══════════╩═
└─────┘
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[1]).c_if(cr, 1)
circuit.barrier()
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = deepcopy(dag)
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(expected, after)
class TestRemoveDiagonalGatesBeforeMeasureFixedPoint(QiskitTestCase):
"""Test remove_diagonal_gates_before_measure optimizations in
a transpiler, using fixed point."""
def test_optimize_rz_z(self):
"""Remove two swaps that overlap
qr0:--RZ-Z--m-- qr0:--m--
| |
cr0:--------.-- cr0:--.--
"""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[0])
circuit.z(qr[0])
circuit.measure(qr[0], cr[0])
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_manager = PassManager()
pass_manager.append(
[RemoveDiagonalGatesBeforeMeasure(), DAGFixedPoint()],
do_while=lambda property_set: not property_set["dag_fixed_point"],
)
after = pass_manager.run(circuit)
self.assertEqual(expected, after)
if __name__ == "__main__":
unittest.main()
|
https://github.com/psasanka1729/nisq-grover-qiskit-floquet-model
|
psasanka1729
|
L = 8;
using PyCall
using Random
using LinearAlgebra
using SparseArrays
using DelimitedFiles
file = raw"gates_list_"*string(L)*".txt" # Change for every L.
M = readdlm(file)
# Name.
Gates_data_1 = M[:,1];
# Angle.
Gates_data_2 = M[:,2];
# Qubit.
Gates_data_3 = M[:,3];
Number_of_Gates = length(Gates_data_1)
#Gates_data_2;
SEED = 100
Random.seed!(SEED)
NOISE = 2*rand(Float64,Number_of_Gates).-1;
I2 = [1 0;
0 1];
Pauli_Z = [1 0;
0 -1];
Pauli_X = [0 1;
1 0]
H = (1/sqrt(2))*[1 1;
1 -1]
U_1(theta) = [1 0;
0 exp(1im*theta)];
Rx(theta) = sparse(exp(-1im*(theta/2)*collect(Pauli_X)));
Rz(theta) = sparse(exp(-1im*(theta/2)*collect(Pauli_Z)));
U1(theta) = sparse(exp(-1im*(theta/2)*(collect(Pauli_Z)-I2)));
Hadamard(noise) = sparse(exp(-1im*(pi/2+noise)*collect(I2-H)))
X(noise) = sparse(exp(-1im*(pi/2+noise)*collect(I2-Pauli_X)));
Z_gate(noise) = sparse(exp(-1im*(pi/2+noise)*collect(I2-Pauli_Z)))
Identity(dimension) = spdiagm(0 => ones(dimension));
int(x) = floor(Int,x);
function single_qubit_gate_matrix(single_qubit_gate, qubit)
## The case Qubit=1 is treated differently because we need to
# initialize the matrix as U before starting the kronecker product.
if qubit == 1
gate_matrix = sparse(single_qubit_gate)
for i=2:L
gate_matrix = kron(gate_matrix, I2)
end
#=
Single qubit gates acting on qubits othe than the first.
=#
else
gate_matrix = I2
for i=2:L
if i == qubit
gate_matrix = kron(gate_matrix, single_qubit_gate)
else
gate_matrix = kron(gate_matrix, I2)
end
end
end
return gate_matrix
end;
function single_qubit_controlled_gate_exponential(single_qubit_gate, c, t)
I2 = [1 0;0 1]
Z = [1 0;0 -1]
Matrices = Dict("I" => I2,"PI_1" => I2-Z,"U" => I2 - single_qubit_gate)
p = fill("I", L)
p[c] = "PI_1"
p[t] = "U"
H_matrix = Matrices[p[1]]
for i = 2:L
H_matrix = kron(H_matrix, Matrices[p[i]])
end
#= pi/4 = (pi)/(2*2)=#
return sparse(H_matrix)/4
end;
function single_qubit_controlled_gate_matrix(single_qubit_gate,c,t) # c t
Z = [1 0;
0 -1]
# |0><0|.
PI_0 = (I2+Z)/2
# |1><1|.
PI_1 = (I2-Z)/2
Matrices = Dict("I" => I2,"PI_0" => PI_0,"U" => single_qubit_gate, "PI_1" => PI_1)
p0 = fill("I", L)
p1 = fill("I", L)
p0[c] = "PI_0"
p1[c] = "PI_1"
p1[t] = "U"
PI_0_matrix = Matrices[p0[1]]
for i = 2:L
PI_0_matrix = kron(PI_0_matrix,Matrices[p0[i]])
end
PI_1_matrix = Matrices[p1[1]]
for i = 2:L
PI_1_matrix = kron(PI_1_matrix,Matrices[p1[i]])
end
return sparse(PI_0_matrix + PI_1_matrix)
end;
#L = 2
#single_qubit_controlled_gate_matrix(Pauli_X,1,2)
using PyCall
py"""
import numpy
import numpy.linalg
def adjoint(psi):
return psi.conjugate().transpose()
def psi_to_rho(psi):
return numpy.outer(psi,psi.conjugate())
def exp_val(psi, op):
return numpy.real(numpy.dot(adjoint(psi),op.dot(psi)))
def norm_sq(psi):
return numpy.real(numpy.dot(adjoint(psi),psi))
def normalize(psi,tol=1e-9):
ns=norm_sq(psi)**0.5
if ns < tol:
raise ValueError
return psi/ns
def is_herm(M,tol=1e-9):
if M.shape[0]!=M.shape[1]:
return False
diff=M-adjoint(M)
return max(numpy.abs(diff.flatten())) < tol
def is_unitary(M,tol=1e-9):
if M.shape[0]!=M.shape[1]:
return False
diff=M.dot(adjoint(M))-numpy.identity((M.shape[0]))
return max(numpy.abs(diff.flatten())) < tol
def eigu(U,tol=1e-9):
(E_1,V_1)=numpy.linalg.eigh(U+adjoint(U))
U_1=adjoint(V_1).dot(U).dot(V_1)
H_1=adjoint(V_1).dot(U+adjoint(U)).dot(V_1)
non_diag_lst=[]
j=0
while j < U_1.shape[0]:
k=0
while k < U_1.shape[0]:
if j!=k and abs(U_1[j,k]) > tol:
if j not in non_diag_lst:
non_diag_lst.append(j)
if k not in non_diag_lst:
non_diag_lst.append(k)
k+=1
j+=1
if len(non_diag_lst) > 0:
non_diag_lst=numpy.sort(numpy.array(non_diag_lst))
U_1_cut=U_1[non_diag_lst,:][:,non_diag_lst]
(E_2_cut,V_2_cut)=numpy.linalg.eigh(1.j*(U_1_cut-adjoint(U_1_cut)))
V_2=numpy.identity((U.shape[0]),dtype=V_2_cut.dtype)
for j in range(len(non_diag_lst)):
V_2[non_diag_lst[j],non_diag_lst]=V_2_cut[j,:]
V_1=V_1.dot(V_2)
U_1=adjoint(V_2).dot(U_1).dot(V_2)
# Sort by phase
U_1=numpy.diag(U_1)
inds=numpy.argsort(numpy.imag(numpy.log(U_1)))
return (U_1[inds],V_1[:,inds]) # = (U_d,V) s.t. U=V*U_d*V^\dagger
"""
U_0 = Identity(2^L)#[-1 0 0 0; 0 1 0 0; 0 0 1 0;0 0 0 1];
U_0[1,1] = -1
A = ones(2^L,2^L);
U_x = (2/2^L)*A-Identity(2^L); # 2\s><s|-I
G_exact = U_x*U_0;
#V = py"eigu"(G_exact)[2];
function grover_delta(DELTA)
U_list = []
GROVER_DELTA = Identity(2^L)
# U_x
for i = 1:Number_of_Gates
if Gates_data_1[i] == "x"
epsilon = NOISE[i]
GROVER_DELTA *= single_qubit_gate_matrix(X(DELTA*epsilon), Gates_data_3[i]+1)
#push!(U_list,single_qubit_gate_matrix(X(0.0), Gates_data_3[i]+1))
elseif Gates_data_1[i] == "h"
epsilon = NOISE[i]
GROVER_DELTA *= single_qubit_gate_matrix(Hadamard(DELTA*epsilon), Gates_data_3[i]+1)
#push!(U_list,single_qubit_gate_matrix(Hadamard(0.0), Gates_data_3[i]+1))
elseif Gates_data_1[i] == "z"
epsilon = NOISE[i]
GROVER_DELTA *= single_qubit_gate_matrix(Z_gate(DELTA*epsilon), Gates_data_3[i]+1)
#push!(U_list,single_qubit_gate_matrix(Z_gate(0.0), Gates_data_3[i]+1))
elseif Gates_data_1[i] == "rx"
epsilon = NOISE[i]
GROVER_DELTA *= single_qubit_gate_matrix(Rx(Gates_data_2[i]+DELTA*epsilon),Gates_data_3[i]+1)
#push!(U_list,single_qubit_gate_matrix(Rx(Gates_data_2[i]),Gates_data_3[i]+1))
elseif Gates_data_1[i] == "rz"
epsilon = NOISE[i]
GROVER_DELTA *= single_qubit_gate_matrix(Rz(Gates_data_2[i]+DELTA*epsilon),Gates_data_3[i]+1)
#push!(U_list,single_qubit_gate_matrix(Rz(Gates_data_2[i]),Gates_data_3[i]+1))
elseif Gates_data_1[i] == "u1"
epsilon = NOISE[i]
GROVER_DELTA *= single_qubit_gate_matrix(U1(Gates_data_2[i]+DELTA*epsilon),Gates_data_3[i]+1)
#push!(U_list,single_qubit_gate_matrix(U1(Gates_data_2[i]),Gates_data_3[i]+1))
elseif Gates_data_1[i] == "cx"
epsilon = NOISE[i]
GROVER_DELTA *= single_qubit_controlled_gate_matrix(X(DELTA*epsilon), Gates_data_2[i]+1, Gates_data_3[i]+1)
#push!(U_list, single_qubit_controlled_gate_matrix(Pauli_X, Gates_data_2[i]+1, Gates_data_3[i]+1))
else
println("Kant")
end
end
#=
function kth_term(k)
f_k = Identity(2^L);
for i = k:length(U_list)
f_k = f_k*collect(U_list[length(U_list)-i+k])
end
#= Corresponding H for the kth term. =#
if Gates_data_1[k] == "h"
Qubit = Gates_data_3[k]+1 # qubit.
H_k = single_qubit_gate_matrix(I2-H,Qubit) #= H_H = I2-H. =#
elseif Gates_data_1[k] == "x"
Qubit = Gates_data_3[k]+1 # qubit.
H_k = single_qubit_gate_matrix([1 0;0 1]-[0 1;1 0],Qubit) #= H_X = I2-X. =#
elseif Gates_data_1[k] == "z"
Qubit = Gates_data_3[k]+1 # qubit.
H_k = single_qubit_gate_matrix([1 0;0 1]-[1 0;0 -1],Qubit) #= H_Z = I2-Z. =#
elseif Gates_data_1[k] == "rz"
Qubit = Gates_data_3[k]+1 # qubit.
H_k = single_qubit_gate_matrix([1 0;0 -1],Qubit) #= H_Z = I2-Z. =#
elseif Gates_data_1[k] == "rx"
Qubit = Gates_data_3[k]+1 # qubit.
H_k = single_qubit_gate_matrix(Pauli_X,Qubit) #= H_Z = I2-Z. =#
elseif Gates_data_1[k] == "cx"
Angle = Gates_data_1[k]
Control_Qubit = int(Gates_data_2[k])+1
Target_Qubit = int(Gates_data_3[k])+1
Z = [1 0;0 -1]
#= H = ((I-Z)/2)_c \otimes ((I-X)/2)_t.=#
Matrices = Dict("I" => [1 0;0 1],"U" => [1 0; 0 1]-[0 1;1 0], "PI_1" => [1 0;0 1]-[1 0;0 -1])
p1 = fill("I", L)
p1[Control_Qubit] = "PI_1"
p1[Target_Qubit] = "U"
H_k = Matrices[p1[1]]
for i = 2:L
H_k = kron(H_k,Matrices[p1[i]])
end
elseif Gates_data_1[k] == "u1"
Qubit = Gates_data_3[k]+1 # qubit.
H_k = single_qubit_gate_matrix(Pauli_Z-I2,Qubit) #= H_Z = I2-Z. =#
else
println(Gates_data_1[k]*" H_k cannot be calculated")
end
return f_k*H_k*(f_k')
end;
h_eff = zeros(2^L,2^L);
for i = 1:length(U_list)
h_eff += NOISE[i]*kth_term(i)
end
#h_eff_D = h_eff
#h_eff_D = (V')*h_eff*(V) # Matrix in |0> and |xbar> basis.
#E_eff_D = eigvals(h_eff_D) # Diagonalizing H_eff matrix.
#E_eff_D_sorted = sort(real(E_eff_D),rev = true); # Soring the eigenvalues in descending order.
#EIGU = py"eigu"(collect(-GROVER_DELTA'))
#E_exact = real(1im*log.(EIGU[1])); # Eigenvalue.
#return E_exact, E_eff_D_sorted
return h_eff
=#
return -GROVER_DELTA'
#return GROVER_DELTA
end;
#real.((collect(grover_delta(0.0))))-G_exact
#=
The following function returns the matrix of rolling operator.
=#
function One_Roll_Operator(number_of_qubits::Int64)
#= Function converts a binary number to a decimal number. =#
Bin2Dec(BinaryNumber) = parse(Int, string(BinaryNumber); base=2);
#= Function converts a decimal number to a binary number. =#
function Dec2Bin(DecimalNumber::Int64)
init_binary = string(DecimalNumber, base = 2);
#=
While converting numbers from decimal to binary, for example, 1
is mapped to 1, to make sure that every numbers have N qubits in them,
the following loop adds leading zeros to make the length of the binary
string equal to N. Now, 1 is mapped to 000.....1 (string of length N).
=#
while length(init_binary) < number_of_qubits
init_binary = "0"*init_binary
end
return init_binary
end
#=
The following function takes a binary string as input
and rolls the qubits by one and returns the rolled binary string.
=#
Roll_String_Once(binary_string) = binary_string[end]*binary_string[1:end-1]
#= Initializing the rolling operator. =#
R = zeros(Float64,2^number_of_qubits,2^number_of_qubits);
#= The numbers are started from 0 to 2^L-1 because for L qubits,
binary representation goes from 0 to 2^L-1.=#
for i = 0:2^number_of_qubits-1
#=
Steps in the following loop.
(1) The number is converted from decimal to binary.
(2) The qubits are rolled once.
(3) The rolled binary number is converted to decimal number.
(4) The corresponding position in R is replaced by 1.
=#
#= The index in R will be shifted by 1 as Julia counts from 1. =#
R[i+1,Bin2Dec(Roll_String_Once(Dec2Bin(i)))+1] = 1
end
return sparse(R)
end;
#=
The following function returns the von-Neumann entropy of a given
wavefunction. The sub-system size is L/2.
=#
function entanglement_entropy(Psi)
sub_system_size = floor(Int,L/2)
Psi = Psi/norm(Psi)
function psi(s)
return Psi[2^(sub_system_size)*s+1:2^(sub_system_size)*s+2^(sub_system_size)]
end
#= (s,s_p) element of the reduced density matrix is given by psi(s_p)^(\dagger)*psi(s). =#
rhoA(s,s_p) = psi(s_p)' * psi(s)
M = zeros(ComplexF64,2^sub_system_size,2^sub_system_size)
#=
Since the matrix is symmetric only terms above the diagonal will be calculated.
=#
for i = 0:2^sub_system_size-1
for j = 0:2^sub_system_size-1
if i <= j
M[i+1,j+1] = rhoA(i,j)
else
M[i+1,j+1] = M[j+1,i+1]'
end
end
end
#= Eigenvalues of M. The small quantity is added to avoid singularity in log.=#
w = eigvals(M).+1.e-10
return real(-sum([w[i]*log(w[i]) for i = 1:2^(sub_system_size)]))
end;
function average_entanglement_entropy(initial_wavefunction)
initial_wavefunction = initial_wavefunction/norm(initial_wavefunction)
R = One_Roll_Operator(L)
rolled_wavefunction = R * initial_wavefunction
rolled_entropies = [entanglement_entropy(rolled_wavefunction)]
for i = 2:L
rolled_wavefunction = R * rolled_wavefunction
push!(rolled_entropies,entanglement_entropy(rolled_wavefunction))
end
return sum(rolled_entropies)/L
end;
#H_EFF = h_eff_from_derivative(1.e-5);
#=
h_eff = H_EFF # Matrix in Z basis.
h_eff = (V')*h_eff*(V) # Matrix in |0> and |xbar> basis.
h_eff_D = h_eff[3:2^L,3:2^L];=#
#h_eff_D
"""function Level_Statistics(n,Es)
return min(abs(Es[n]-Es[n-1]),abs(Es[n+1]-Es[n])) / max(abs(Es[n]-Es[n-1]),abs(Es[n+1]-Es[n]))
end;
h_eff_level_statistics = Array{Float64, 1}(undef, 0)
for i = 2:2^L-3 # relative index i.e length of the eigenvector array.
push!(h_eff_level_statistics,Level_Statistics(i,h_eff_D ))
end
level_statistics_file = open("level_statistics.txt", "w")
for i = 1:2^L-4
write(level_statistics_file, string(i))
write(level_statistics_file, "\t") # Add a tab indentation between the columns
write(level_statistics_file, string(h_eff_level_statistics[i]))
write(level_statistics_file, "\n") # Add a newline character to start a new line
end
close(level_statistics_file)""";
#h_eff_level_statistics
#using Statistics
#mean(h_eff_level_statistics)
#Eigvals_h_eff = eigvals(collect(h_eff_D));
#Eigvecs_h_eff = eigvecs(collect(h_eff));
#=
using Plots
using DelimitedFiles
using ColorSchemes
using LaTeXStrings
eigenvalue_file = open("compare_h_eff_G_exact_eigenvalues.txt", "w")
Exact_list = []
Effec_list = []
delta_list = []
Num = 10;
for i = 1:Num
delta = 0.1*(i/Num)
EE = -Grover_delta(delta)
EIGU = py"eigu"(collect(EE))
Exact = real(1im*log.(EIGU[1]))[2:2^L-1]
Effec = delta*real(Eigvals_h_eff)
#println(Exact)
#println(Effec)
for j = 1:2^L-2
write(eigenvalue_file, string(delta))
write(eigenvalue_file, "\t")
write(eigenvalue_file, string(Exact[j]))
write(eigenvalue_file, "\t")
write(eigenvalue_file, string(Effec[j]))
write(eigenvalue_file, "\n")
#py"Write_file2"(delta,Exact[j],Effec[j])
push!(delta_list,delta)
push!(Exact_list, Exact[j])
push!(Effec_list, Effec[j])
#println(delta);
end
end
delta = delta_list
exact = Exact_list # exact energy.
effec = Effec_list # effective energy.
S_Page = 0.5*L*log(2)-0.5
gr()
L = 4;
S_Page = 0.5*L*log(2)-0.5
MyTitle = "L = 4 ";
p = plot(delta,exact,
seriestype = :scatter,
markercolor = "firebrick1 ",#"red2",
markerstrokewidth=0.0,
markersize=3.2,
thickness_scaling = 1.4,
xlims=(0,0.3),
ylims=(-3.14,3.14),
#title = MyTitle,
label = "Exact energy",
legend = :bottomleft,
dpi=500,
#zcolor = entropy,
grid = false,
#colorbar_title = "Average entanglement entropy",
font="CMU Serif",
color = :jet1,
right_margin = 5Plots.mm,
left_margin = Plots.mm,
titlefontsize=10,
guidefontsize=13,
tickfontsize=13,
legendfontsize=15,
framestyle = :box
)
p = plot!(delta,effec,
seriestype = :scatter,
markercolor = "blue2",
markershape=:pentagon,#:diamond,
markerstrokewidth=0.0,
markersize=2.2,
thickness_scaling = 1.4,
xlims=(0,0.1),
ylims=(-3.14,3.14),
#title = MyTitle,
label = "Effective energy",
legend = :bottomleft,
dpi=100,
#zcolor = entropy,
grid = false,
#colorbar_title = "Average entanglement entropy",
font="CMU Serif",
right_margin = 5Plots.mm,
left_margin = Plots.mm,
titlefontsize=10,
guidefontsize=13,
tickfontsize=13,
legendfontsize=15,
framestyle = :box
)
plot!(size=(830,700))
xlabel!("Noise")
ylabel!("Energy of the bulk states")
#savefig("exact_effec_4_2000.png")
=#
"""function KLd(Eigenvectors_Matrix)
KL = []
for n = 1:2^L-1 # Eigenvector index goes from 1 to dim(H)-1.
#=
Here n is the index of the eigenstate e.g n = 3 denotes the
third eigenstate of the h_eff matrix in sigma_z basis.
=#
#= Calculates the p(i) = |<i|n>|^2 for a given i. This is the moduli
squared of the i-th component of the n-th eigenstate. This is because
in the sigma_z basis <i|n> = i-th component of |n>.
=#
# Initialize the sum.
KLd_sum = 0.0
# The sum goes from 1 to dim(H) i.e length of an eigenvector.
for i = 1:2^L
p = abs(Eigenvectors_Matrix[:,n][i])^2 + 1.e-9 # To avoid singularity in log.
q = abs(Eigenvectors_Matrix[:,n+1][i])^2 + 1.e-9
KLd_sum += p*log(p/q)
end
#println(KLd_sum)
push!(KL,KLd_sum)
end
return KL
end;""";
#KLd_h_eff = KLd(Eigvecs_h_eff);
#mean(KLd_h_eff)
#=
KLd_file = open("KLd.txt", "w")
for i = 1:2^L-1
write(KLd_file , string(i))
write(KLd_file , "\t") # Add a tab indentation between the columns
write(KLd_file , string(KLd_h_eff[i]))
write(KLd_file , "\n") # Add a newline character to start a new line
end
# Close the file
close(KLd_file)=#
eigenvalue_file = open(string(L)*"_"*string(SEED)*"_eigenvalues.txt", "w");
deltas = []
Ys = []
Entropies = []
Num = 200
for i=0:Num
println(i)
delta = 0.1*i/Num
Op = -collect(grover_delta(delta))
EIGU = py"eigu"(Op)
deltas = string(delta)
Y = real(1im*log.(EIGU[1]))
V = EIGU[2]
for j=1:2^L
write(eigenvalue_file , string(delta))
write(eigenvalue_file , "\t") # Add a tab indentation between the columns
write(eigenvalue_file , string(real(Y[j])))
write(eigenvalue_file , "\t")
write(eigenvalue_file , string(average_entanglement_entropy(V[1:2^L,j:j])))
write(eigenvalue_file , "\n") # Add a newline character to start a new line
#end
#py"Write_file"(delta, real(Y[j]), average_entanglement_entropy(V[1:2^L,j:j]))
end
end
close(eigenvalue_file)
#=
using Plots
using DelimitedFiles
using ColorSchemes
#using CSV
using LaTeXStrings
#using PyPlot=#
#=
file = "eigenvalues.txt"
M = readdlm(file)
delta = M[:,1]; # eigenvalue index
quasienergy = M[:,2]; # level stat
entanglement = M[:,3]; # level stat std
gr()
MSW = 0.4
Linewidth = 0.6
Markersize = 1.7
MarkerStrokeWidth = 0.0;
plot_font = "Computer Modern"
default(fontfamily=plot_font)
MyTitle = "L = "*string(L)*", Page Value = "*string(round(0.5*L*log(2)-0.5;digits = 2))*" ";
p = plot(delta,quasienergy ,
seriestype = :scatter,
markerstrokecolor = "grey30",
markerstrokewidth=MarkerStrokeWidth,
markersize=Markersize,
thickness_scaling = 2.5,
xlims=(0,0.4),
ylims=(-3.2,3.2),
title = "",
label = "",
#legend = :bottomleft,
dpi=300,
zcolor = entanglement,
grid = false,
#colorbar_title = "Average entanglement entropy",
right_margin = Plots.mm,
font="CMU Serif",
color = :jet1,
#:linear_bmy_10_95_c78_n256,#:diverging_rainbow_bgymr_45_85_c67_n256,#:linear_bmy_10_95_c78_n256,#:rainbow1,
#right_margin = 2Plots.mm,
left_margin = Plots.mm,
titlefontsize=10,
guidefontsize=10,
tickfontsize=9,
legendfontsize=8,
framestyle = :box
)
yticks!([-pi,-3*pi/4,-pi/2,-pi/4,0,pi/4,pi/2,3*pi/4,pi], [L"-\pi",L"-3\pi/4",L"-\pi/2",L"-\pi/4",L"0",L"\pi/4",L"\pi/2",L"3\pi/4",L"\pi"])
function ticks_length!(;tl=0.01)
p = Plots.current()
xticks, yticks = Plots.xticks(p)[1][1], Plots.yticks(p)[1][1]
xl, yl = Plots.xlims(p), Plots.ylims(p)
x1, y1 = zero(yticks) .+ xl[1], zero(xticks) .+ yl[1]
sz = p.attr[:size]
r = sz[1]/sz[2]
dx, dy = tl*(xl[2] - xl[1]), tl*r*(yl[2] - yl[1])
plot!([xticks xticks]', [y1 y1 .+ dy]', c=:black, labels=false,linewidth = 1.3)
plot!([x1 x1 .+ dx]', [yticks yticks]', c=:black, labels=false,linewidth = 1.3, xlims=xl, ylims=yl)
return Plots.current()
end
ticks_length!(tl=0.005)
plot!(size=(1200,800))
#plot!(yticks = ([(-pi) : (-pi/2): (-pi/4): 0: (pi/4) : (pi/2) : pi;], ["-\\pi", "-\\pi/2", "-\\pi/4","0","\\pi/4","\\pi/2","\\pi"]))
#hline!([[-quasienergy]],lc=:deeppink1,linestyle= :dashdotdot,legend=false)
#hline!([ [0]],lc=:deeppink1,linestyle= :dashdotdot,legend=false)
#hline!([ [quasienergy]],lc=:deeppink1,linestyle= :dashdotdot,legend=false)
xlabel!("Disorder strength, \$\\delta\$")
ylabel!("Quasienergy, \$\\phi_{F}\$")
plot!(background_color=:white)
#savefig(string(L)*"_"*string(SEED)*"_plot_data_0.0_0.15.png")
=#
#round(0.5*L*log(2)-0.5;digits = 2)
|
https://github.com/ionq-samples/getting-started
|
ionq-samples
|
import numpy as np
from qiskit import QuantumCircuit
# Building the circuit
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
# We can visualise the circuit using QuantumCircuit.draw()
circ.draw('mpl')
from qiskit.quantum_info import Statevector
# Set the initial state of the simulator to the ground state using from_int
state = Statevector.from_int(0, 2**3)
# Evolve the state by the quantum circuit
state = state.evolve(circ)
#draw using latex
state.draw('latex')
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Build
#------
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# END
# Execute
#--------
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Return counts
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)
# END
# Visualize
#----------
# Using QuantumCircuit.draw(), as in previous example
circuit.draw('mpl')
# Analyze
#--------
# Plot a histogram
plot_histogram(counts)
# END
<h3 style="color: rgb(0, 125, 65)"><i>References</i></h3>
https://qiskit.org/documentation/tutorials.html
https://www.youtube.com/watch?v=P5cGeDKOIP0
https://qiskit.org/documentation/tutorials/circuits/01_circuit_basics.html
https://docs.quantum-computing.ibm.com/lab/first-circuit
|
https://github.com/vm6502q/qiskit-qrack-provider
|
vm6502q
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import unittest
import copy
import pickle
from multiprocessing import Pool
from qiskit import assemble, transpile, QuantumCircuit
from qiskit.providers.qrack.backends import QasmSimulator
#from qiskit.providers.aer.backends.controller_wrappers import qasm_controller_execute
from test.terra.reference import ref_algorithms, ref_measure, ref_1q_clifford
from test.terra.common import QiskitAerTestCase
class TestControllerExecuteWrappers(QiskitAerTestCase):
"""Basic functionality tests for pybind-generated wrappers"""
#CFUNCS = [qasm_controller_execute()]
#def test_deepcopy(self):
# """Test that the functors are deepcopy-able."""
# for cfunc in self.CFUNCS:
# cahpy = copy.deepcopy(cfunc)
#def test_pickleable(self):
# """Test that the functors are pickle-able (directly)."""
# for cfunc in self.CFUNCS:
# bites = pickle.dumps(cfunc)
# cahpy = pickle.loads(bites)
def _create_qobj(self, backend, noise_model=None):
num_qubits = 2
circuit = QuantumCircuit(num_qubits)
circuit.x(list(range(num_qubits)))
qobj = assemble(transpile(circuit, backend), backend)
opts = {'max_parallel_threads': 1}
fqobj = backend._format_qobj(qobj, **opts, noise_model=noise_model)
return fqobj.to_dict()
def _map_and_test(self, cfunc, qobj):
n = 2
with Pool(processes=1) as p:
rs = p.map(cfunc, [copy.deepcopy(qobj) for _ in range(n)])
self.assertEqual(len(rs), n)
for r in rs:
self.assertTrue(r['success'])
#def test_mappable_qasm(self):
# """Test that the qasm controller can be mapped."""
# cfunc = qasm_controller_execute()
# sim = QasmSimulator()
# fqobj = self._create_qobj(sim)
# self._map_and_test(cfunc, fqobj)
#def test_mappable_statevector(self):
# """Test that the statevector controller can be mapped."""
# cfunc = statevector_controller_execute()
# sim = StatevectorSimulator()
# fqobj = self._create_qobj(sim)
# self._map_and_test(cfunc, fqobj)
if __name__ == '__main__':
unittest.main()
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/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/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#from qiskit.providers.aer import Aer, execute
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
Q_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(1)
hello_qubit = QuantumCircuit(q)
hello_qubit.id(q[0])
#job = execute(hello_qubit, S_simulator)
new_circuit = transpile(hello_qubit, S_simulator)
job = S_simulator.run(new_circuit)
print('job = AerJob class: ', type(job))
result = job.result()
print('result = Result class: ',type(result))
result.get_statevector()
print('simulator: ', S_simulator)
print('simulator type: ', type(S_simulator))
print('Aer.get_backend(name=statevector_simulator): ', Aer.get_backend(name='statevector_simulator'))
print('backend type: ', type(Aer.get_backend(name='statevector_simulator')))
q = QuantumRegister(3)
three_qubits = QuantumCircuit(q)
three_qubits.id(q[0])
three_qubits.id(q[1])
three_qubits.id(q[2])
job = oq.execute(three_qubits, S_simulator)
result = job.result()
result.get_statevector()
q = QuantumRegister(3)
three_qubits = QuantumCircuit(q)
three_qubits.x(q[0])
three_qubits.id(q[1])
three_qubits.id(q[2])
job = oq.execute(three_qubits, S_simulator)
result = job.result()
result.get_statevector()
oq.Wavefunction(three_qubits)
q = QuantumRegister(2)
H_circuit = QuantumCircuit(q)
H_circuit.h(q[0])
H_circuit.h(q[1])
oq.Wavefunction(H_circuit)
q = QuantumRegister(2)
H_circuit = QuantumCircuit(q)
H_circuit.h(q[0])
H_circuit.id(q[1])
oq.Wavefunction(H_circuit)
from qiskit import ClassicalRegister
M_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.measure(q, c)
job = oq.execute(qc, M_simulator)
result = job.result()
result.get_counts(qc)
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.measure(q, c)
M = oq.execute(qc, M_simulator, shots = 100).result().get_counts(qc)
print('Dictionary entry 0: ', M['0'])
print('Dictionary entry 1: ', M['1'])
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[1])
qc.measure(q, c)
M = oq.execute(qc, M_simulator).result().get_counts(qc)
print(M)
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[1])
qc.measure(q[0], c[0])
M = oq.execute(qc, M_simulator).result().get_counts(qc)
print(M)
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.id(q[0])
qc.x(q[1])
qc.measure(q, c)
M = oq.execute(qc, M_simulator).result().get_counts(qc)
print(M)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.id(q[0])
qc.x(q[1])
oq.Wavefunction(qc)
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[1])
qc.measure(q[0], c[0])
oq.Measurement(qc, shots = 1024)
def Quantum_Coin_Flips(flips):
'''
Simulates a perfect coin, measuring heads or tails, using a qubit
'''
q = QuantumRegister(1)
c = ClassicalRegister(1)
perfect_coin = QuantumCircuit(q, c)
perfect_coin.h(q[0])
perfect_coin.measure(q,c)
M = oq.execute(perfect_coin, M_simulator, shots=flips).result().get_counts(perfect_coin)
heads = M['0']
tails = M['1']
return heads, tails
Heads, Tails = Quantum_Coin_Flips(100)
if (Heads > Tails):
print('Alice wins!')
if (Heads < Tails):
print('Bob wins!')
if (Heads == Tails):
print('Draw!')
print(' ')
print('Score: Alice: ', Heads, ' Bob: ', Tails)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
2*acos(sqrt(2/3)), 2*asin(sqrt(1/3)).
cos(2*pi/3), sin(2*pi/3), cos(4*pi/3), sin(4*pi/3), cos(8*pi/3), sin(8*pi/3)
cos(2*pi/3), sin(2*pi/3), cos(4*pi/3), sin(4*pi/3), cos(8*pi/3), sin(8*pi/3)
|
https://github.com/parton-quark/RLSB-CongX-Qiskit
|
parton-quark
|
# (c) Copyright 2020 Shin Nishio, parton@sfc.wide.ad.jp
def tfc_to_qiskit(tfc_path):
tfc_file = open(tfc_path, "r", encoding = "utf_8")
# convert tfc_file into list of lines
tfc_lines = tfc_file.readlines()
# prepare .py file
tfc_path_left = tfc_path.split('.')
py_file_name = "RLSBCQ_" + str(tfc_path_left[0]) + ".py"
py_file = open(py_file_name, "w", encoding = "utf_8")
# py_file.write(text)で書き込める
_write_head(py_file)
tfc_line_number = 0
for tfc_line in tfc_lines:
tfc_line_number += 1
if tfc_line.startswith('t'):
_gt(py_file, tfc_line, valiables_dict)
elif tfc_line.startswith('f'):
_gf(py_file, tfc_line, valiables_dict)
elif tfc_line.startswith('#'):
_write_comment(py_file, tfc_line)
elif tfc_line.startswith('.v'):
# get list of valiables
valiables_dict = _valiables(py_file, tfc_line)
# make_register
_prepare_register(py_file, valiables_dict)
elif tfc_line.startswith('.i'):
# get inputs
input_dict = _inputs(py_file, tfc_line, valiables_dict)
elif tfc_line.startswith('.o'):
# get outputs
output_dict = _outputs(py_file, tfc_line, valiables_dict)
elif tfc_line.startswith('.ol'):
# get outputs list
ol_dict = _outputs_list(py_file, tfc_line, valiables_dict)
elif tfc_line.startswith('.c'):
# get constants
constants_ = _constants(py_file, tfc_line, valiables_dict)
elif tfc_line.startswith('BEGIN'):
py_file.write('# BEGIN\n')
elif tfc_line.startswith('END'):
py_file.write('# END\n')
py_file.close()
else:
print("The first letter of the" + tfc_line_number + "line of the input is strange.")
#終わり
tfc_file.close()
return
def _write_head(py_file):
lisences = _license_info()
# import SDKs
import_qiskit = 'from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\n'
import_CongX = 'from CongX.extensions.standard import cnx\n'
# Comments from RLSB-CongX-Qiskit
comments_from_RLSB_CongX_Qiskit = '# Can be run by installing Qiskit and CongX.\n' + '# !pip install qiskit\n' + '# !pip install CongX\n'
py_file.write(lisences)
py_file.write(import_qiskit)
py_file.write(import_CongX)
py_file.write(comments_from_RLSB_CongX_Qiskit)
def _license_info():
original_lisence = '# LISENCE\n'
congx_lisence = '# This file is converted by RLSB-CongX-Qiskit. RLSB-CongX-Qiskit is written by Shin Nishio. bib file is https://github.com/parton-quark/RLSB-CongX-Qiskit/blob/master/RLSB-CongX-Qiskit.bib \n'
license_info = original_lisence + congx_lisence
return license_info
def _prepare_register(py_file, valiables_dict):
num_qubits = len(valiables_dict)
q = 'q = QuantumRegister(' + str(num_qubits) + ')\n'
# c = ClassicalRegister(0)
qc = 'qc = QuantumCircuit(q)\n'
py_file.write(q)
py_file.write(qc)
def _write_comment(py_file, tfc_line):
# Write as it is
py_file.write(tfc_line)
def _gt(py_file, tfc_line, valiables_dict):
'''
e.g.
input t3 b,c,d
{b:1, c:2, d:3}
output qc.cnx(valiables_dict[b],valiables_dict[c],valiables_dict[d])
'''
# delete tn
tfc_line = tfc_line.lstrip('t')
# Delete the head number
tfc_line = tfc_line.strip()
tfc_line = tfc_line.strip(' ')
operand_number = int(tfc_line[0])
tfc_line = tfc_line[2:]
# make valuable list
val_list = tfc_line.split(',')
operand_list = []
for i in val_list:
operand = valiables_dict[str(i)]
operand_list.append(operand)
operand_str = ', '.join(map(str, operand_list))
cnx = "qc.cnx(" + operand_str + ")"
py_file.write(cnx)
py_file.write('\n')
def _gf(py_file, tfc_line, valiables_dict):
message = 'Generalized Fredkin is under construction\n'
return message
def _valiables(py_file, tfc_line):
'''
e.g.
input .v a,b,c,d
output {'a':0, 'b':1, 'c':2, 'd':3}
'''
# delete str = '.v'
tfc_line = tfc_line.lstrip('.v ')
# remove whitespace
tfc_line = tfc_line.strip()
tfc_line = tfc_line.strip(' ')
# make valuable list
val_list = tfc_line.split(',')
num_qubit = len(val_list)
qubit_list = [i for i in range(num_qubit)]
# make valuable_list and qubit_list to dict
valiables_dict = dict(zip(val_list,qubit_list))
py_file.write('# valuables' + str(valiables_dict) + '\n')
return valiables_dict
def _inputs(py_file, tfc_line, valiables_dict):
'''
e.g.
input i. a,b,c,d
output {'a':0, 'b':1, 'c':2, 'd':3}
'''
# delete str = '.v'
tfc_line = tfc_line.lstrip('.i')
# remove whitespace
tfc_line = tfc_line.strip()
# make valuable list
input_list = tfc_line.split(',')
qubit_list = []
for i in input_list:
qubit_number = valiables_dict[i]
qubit_list.append(qubit_number)
# make valuable_list and qubit_list to dict
input_dict = dict(zip(input_list,qubit_list))
py_file.write('# inputs' + str(input_dict) + '\n')
return input_dict
def _outputs(py_file, tfc_line, valiables_dict):
'''
e.g.
input o. a,b,c,d
output {'a':0, 'b':1, 'c':2, 'd':3}
'''
# delete str = '.v'
tfc_line = tfc_line.lstrip('.o')
# remove whitespace
tfc_line = tfc_line.strip()
# make valuable list
output_list = tfc_line.split(',')
qubit_list = []
for i in output_list:
qubit_number = valiables_dict[i]
qubit_list.append(qubit_number)
# make valuable_list and qubit_list to dict
output_dict = dict(zip(output_list,qubit_list))
py_file.write('# outputs' + str(output_dict) + '\n')
return output_dict
def _outputs_list(py_file, tfc_line, valiables_dict):
'''
e.g.
input .ol b1,b2,b3,b4,b5,b6,b7,b8,b9
output {'a':0, 'b':1, 'c':2, 'd':3}
'''
# delete str = '.v'
tfc_line = tfc_line.lstrip('.ol')
# remove whitespace
tfc_line = tfc_line.strip()
# make valuable list
ol_list = tfc_line.split(',')
qubit_list = []
for i in ol_list:
qubit_number = valiables_dict[i]
qubit_list.append(qubit_number)
# make valuable_list and qubit_list to dict
ol_dict = dict(zip(ol_list, qubit_list))
py_file.write('#' + str(ol_dict) + '\n')
return ol_dict
def _constants(py_file, tfc_line):
'''
e.g.
input .c 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
output {'c0':0, 'c1':0, 'c2':2, 'c3':3....}
'''
# delete str = '.c'
tfc_line = tfc_line.lstrip('.c')
# remove whitespace
tfc_line = tfc_line.strip()
# make valuable list
contstants = tfc_line.split(',')
py_file.write('#' + str(contstants) + '\n')
return contstants
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.