repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
|
https://github.com/AMevans12/Quantum-Codes-Qiskit-Module-
|
AMevans12
|
import qiskit.quantum_info as qi
from qiskit.circuit.library import FourierChecking
from qiskit.visualization import plot_histogram
f=[1,-1,-1,-1]
g=[1,1,-1,-1]
circ = FourierChecking(f=f, g=g)
circ.draw(output='mpl')
zero=qi.Statevector.from_label('00')
sv=zero.evolve(circ)
probs=sv.probabilities_dict()
plot_histogram(probs)
import qiskit.quantum_info as qi
from qiskit.circuit.library import FourierChecking
from qiskit.visualization import plot_histogram
f=[1,-1,-1,-1]
g=[1,1,-1,-1]
circ = FourierChecking(f=f, g=g)
circ.draw(output='mpl')
zero=qi.Statevector.from_label('00')
sv=zero.evolve(circ)
probs=sv.probabilities_dict()
plot_histogram(probs)
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import pew_tunnel as pew
import pygame
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
import numpy as np
#########################################################################
#FUNCTIONS
#########################################################################
simulator = Aer.get_backend('qasm_simulator')
shot=1
def Qand(First_bool,Second_bool):
First_bool=bool(First_bool)
Second_bool=bool(Second_bool)
a = int(First_bool)
b = int(Second_bool)
qc = QuantumCircuit(3,1)
if a == 1:
qc.x(0)
if b == 1:
qc.x(1)
qc.ccx(0, 1, 2) #toffoli
qc.measure(2,0)
job = execute(qc, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value ==1]
return bool(int(state[0]))
def Qnand(First_bool,Second_bool):
First_bool=bool(First_bool)
Second_bool=bool(Second_bool)
a = int(First_bool)
b = int(Second_bool)
qc = QuantumCircuit(3,1)
if a == 1:
qc.x(0)
if b == 1:
qc.x(1)
qc.ccx(0, 1, 2) #toffoli
qc.x(2)
qc.measure(2,0)
job = execute(qc, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value ==1]
return bool(int(state[0]))
def Qor(First_bool,Second_bool):
return Qnand(Qnand(First_bool,First_bool),Qnand(Second_bool,Second_bool))
def qrand(nbits):
"""generates nbits real random numbers using quantum state measurements in qiskit."""
circ = QuantumCircuit(1, 1)
circ.h(0)
circ.measure(0, 0)
b=''#string holder
for i in range(nbits):
job=execute(circ, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value == 1] #find the measured state, this is a list
b=b+state[0] #state[0] is a string
return int(b, 2)
def Pt(U0, E, L, betac, gamma_sqc):
"""return tunneling probability for square barrier"""
return 1/ (np.cosh(betac * L)**2 + gamma_sqc * np.sinh(betac * L)**2)
def beta(U0, E):
"""supply function for Pt"""
return np.sqrt(2* (U0 - E))
def gamma_sq(U0, E):
"""supply function for Pt"""
return 0.25 * ((1 - E/U0)/(E/U0) + (E/U0)/(1-E/U0) - 2)
def theta(p_tunnel):
"""returns rotation angle corresponding to tunneling prob. p_tunnel"""
return 2 * np.arcsin(np.sqrt(p_tunnel))
def tunnelres(U0, length_snake, L, betac, gamma_sqc):
"""returns 0 if tunnel, returns 1 if no tunnel"""
P_t = Pt(U0, length_snake, L, betac, gamma_sqc) #get tunneling prob depending on current snake length
theta_rot = theta(P_t) #get rot angle
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circ = QuantumCircuit(qr, cr)
circ.rx(theta_rot, qr[0])
circ.measure(qr, cr)
job = execute(circ, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value == 1]
return int(state[0])
##########################################################################
#MAIN
##########################################################################
#initialize pew
dis = pew.init()
screen = pew.Pix()
#set size
bits = 3
ds= 2**bits #displazsize
#set game starting parameters
game_speed = 4
snake = [(2, 4)]
dx, dy = 1, 0
apple_x, apple_y = 6, 5
screen.pixel(apple_x, apple_y, 1)
howmanyapples = 1 #marker for total number of eaten apples, used for scoring
#set graphics for probability display
pygame.font.init()
#gate backkgorund
font1 = pygame.font.Font(None, 33)
text = font1.render('Probability for tunneling is', True, (255, 0, 0))
dis.blit(text, (20, 330))
font2 = pygame.font.Font(None, 45)
text2 = font2.render('100%', True, (255, 0, 0))
dis.blit(text2, (130, 360))
ima = pygame.image.load('pewblack.jpg')
#tunneling parameters
U0=37 #max snake length = 6x6 = 36
E=1
L=0.05 #optimal barrier size for nice tunneling probabilities
#initialize tunneling tracker
tunnel=0 #don't see other side as second barrier
snakepos=1 #marker of snakepos, 1=head, increase towards tail
headtunnel=0 #let the head tunnel again through other even if tail still in process
while True: #snake runs
#create barrier
bar= []
for i in range(ds):
screen.pixel(0, i, 2)
screen.pixel(ds-1, i, 2)
screen.pixel(i, 0, 2)
screen.pixel(i, ds-1, 2)
bar.append((0, i))
bar.append((ds-1, i))
bar.append((i, 0))
bar.append((i, ds-1))
#find the head
if len(snake) > 1:
x, y = snake[-2]
screen.pixel(x, y, 1)
x, y = snake[-1]
screen.pixel(x, y, 3) #color the head yellow
pew.show(screen)
pew.tick(1 / game_speed)
#get commands
keys = pew.keys()
if headtunnel==0:
if keys & pew.K_UP and dy == 0:
dx, dy = 0, -1
elif keys & pew.K_LEFT and dx == 0:
dx, dy = -1, 0
elif keys & pew.K_RIGHT and dx == 0:
dx, dy = 1, 0
elif keys & pew.K_DOWN and dy == 0:
dx, dy = 0, 1
elif headtunnel==1: #steering not allowed during tunneling of the head (during two rounds)
headtunnel=2
elif headtunnel>=2:
headtunnel=0
x = (x + dx) % 8
y = (y + dy) % 8
##TUNNELING PROCESS
#snake tail tunnels
if Qand(tunnel>0 ,snakepos<=len(snake)):
#get segment for tunneling
sx, sy = snake[-snakepos]
E=len(snake)/2 #divide by two for lower tunnel prob for tail (lower mass->lower energy)
tunnels = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E))
if tunnels==1: #tunnels
snakepos+=1
else: #does not tunnel
del snake[-snakepos]
screen.pixel(sx, sy, 0)
#reset if last segment tunneled
if Qand(tunnel>0 ,snakepos==(len(snake)+1)):
tunnel=0
snakepos=1
#snake head tunnels
if Qand(headtunnel==0, (x, y) in bar):
E=len(snake)
tunnel = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E))
if Qand(tunnel==0, len(snake) != 1): #head doesn't tunnel --> game over
break
else:
snakepos+=1
headtunnel+=1
elif headtunnel==1 and (x, y) in bar:
headtunnel=0
#display tunneling prob.
E = len(snake)
if E > 1:
prob = Pt(U0, E, L, beta(U0, E), gamma_sq(U0, E))
text3 = font2.render(str(int(round(prob * 100))) + '%', True, (255, 0, 0))
dis.blit(ima, (130, 360))
dis.blit(text3, (130, 360))
else: #if length of snake ==1 (only head), tunneling prob = 100%
dis.blit(ima, (130, 360)) #cover the ultimate prob. display
dis.blit(text2, (130, 360)) #text2 = '100%'
#####TUNNEL END
if (x, y) in snake: #exit, game over condition
break
snake.append((x, y))
#apple generation
if Qand(x == apple_x, y == apple_y):
screen.pixel(apple_x, apple_y, 0)
apple_x, apple_y = snake[0]
while Qor((apple_x, apple_y) in snake , (apple_x, apple_y) in bar):
apple_x = qrand(bits) #random.getrandbits(3) #use this for pseudo random number gen, no qiskit needed
apple_y = qrand(bits) #random.getrandbits(3)
screen.pixel(apple_x, apple_y, 1)
game_speed += 0.2 #increase game speed
howmanyapples += 1 #increase number of eaten apples, score +1
else:
x, y = snake.pop(0)
screen.pixel(x, y, 0)
text = pew.Pix.from_text("Game over!") #Game over message and closing
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
text = pew.Pix.from_text("Score:" + str(int(howmanyapples))) #Score message
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
pygame.quit()
|
https://github.com/pranavdurai10/quantum-gates
|
pranavdurai10
|
'''
///////////////////////////////////////////////////////////////////////////
Code written by Pranav Durai for Quantum Computer on 31.05.2023 @ 21:26:45
Component: Controlled-NOT Gate (CNOT)
Framework: Qiskit 0.43.0
///////////////////////////////////////////////////////////////////////////
'''
# Import necessary libraries
from qiskit import QuantumCircuit, Aer, execute
# Create a quantum circuit with two qubits
circuit = QuantumCircuit(2)
# Apply the CNOT gate with control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Measure the qubits
circuit.measure_all()
# Simulate the circuit using the local Aer simulator
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=1)
# Get the result
result = job.result()
counts = result.get_counts(circuit)
# Print the measurement outcome
print("Measurement outcome:", list(counts.keys())[0])
|
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, 0)
circ.measure(1, 1)
circ.draw('mpl')
from qiskit import pulse
from qiskit.pulse.library import Gaussian
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration('h', [0], h_q0)
from qiskit import transpile
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
circ = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ.draw('mpl', idle_wires=False)
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
circ = QuantumCircuit(1, 1)
custom_gate = Gate('my_custom_gate', 1, [3.14, 1])
# 3.14 is an arbitrary parameter for demonstration
circ.append(custom_gate, [0])
circ.measure(0, 0)
circ.draw('mpl')
with pulse.build(backend, name='custom') as my_schedule:
pulse.play(Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0))
circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1])
# Alternatively: circ.add_calibration(custom_gate, [0], my_schedule)
circ = transpile(circ, backend)
circ.draw('mpl', idle_wires=False)
circ = QuantumCircuit(2, 2)
circ.append(custom_gate, [1])
from qiskit import QiskitError
try:
circ = transpile(circ, backend)
except QiskitError as e:
print(e)
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 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.
"""
Core module of the timeline drawer.
This module provides the `DrawerCanvas` which is a collection of drawings.
The canvas instance is not just a container of drawing objects, as it also performs
data processing like binding abstract coordinates.
Initialization
~~~~~~~~~~~~~~
The `DataCanvas` is not exposed to users as they are implicitly initialized in the
interface function. It is noteworthy that the data canvas is agnostic to plotters.
This means once the canvas instance is initialized we can reuse this data
among multiple plotters. The canvas is initialized with a stylesheet.
```python
canvas = DrawerCanvas(stylesheet=stylesheet)
canvas.load_program(sched)
canvas.update()
```
Once all properties are set, `.update` method is called to apply changes to drawings.
Update
~~~~~~
To update the image, a user can set new values to canvas and then call the `.update` method.
```python
canvas.set_time_range(2000, 3000)
canvas.update()
```
All stored drawings are updated accordingly. The plotter API can access to
drawings with `.collections` property of the canvas instance. This returns
an iterator of drawings with the unique data key.
If a plotter provides object handler for plotted shapes, the plotter API can manage
the lookup table of the handler and the drawings by using this data key.
"""
from __future__ import annotations
import warnings
from collections.abc import Iterator
from copy import deepcopy
from functools import partial
from enum import Enum
import numpy as np
from qiskit import circuit
from qiskit.visualization.exceptions import VisualizationError
from qiskit.visualization.timeline import drawings, types
from qiskit.visualization.timeline.stylesheet import QiskitTimelineStyle
class DrawerCanvas:
"""Data container for drawings."""
def __init__(self, stylesheet: QiskitTimelineStyle):
"""Create new data container."""
# stylesheet
self.formatter = stylesheet.formatter
self.generator = stylesheet.generator
self.layout = stylesheet.layout
# drawings
self._collections: dict[str, drawings.ElementaryData] = {}
self._output_dataset: dict[str, drawings.ElementaryData] = {}
# vertical offset of bits
self.bits: list[types.Bits] = []
self.assigned_coordinates: dict[types.Bits, float] = {}
# visible controls
self.disable_bits: set[types.Bits] = set()
self.disable_types: set[str] = set()
# time
self._time_range = (0, 0)
# graph height
self.vmax = 0
self.vmin = 0
@property
def time_range(self) -> tuple[int, int]:
"""Return current time range to draw.
Calculate net duration and add side margin to edge location.
Returns:
Time window considering side margin.
"""
t0, t1 = self._time_range
duration = t1 - t0
new_t0 = t0 - duration * self.formatter["margin.left_percent"]
new_t1 = t1 + duration * self.formatter["margin.right_percent"]
return new_t0, new_t1
@time_range.setter
def time_range(self, new_range: tuple[int, int]):
"""Update time range to draw."""
self._time_range = new_range
@property
def collections(self) -> Iterator[tuple[str, drawings.ElementaryData]]:
"""Return currently active entries from drawing data collection.
The object is returned with unique name as a key of an object handler.
When the horizontal coordinate contains `AbstractCoordinate`,
the value is substituted by current time range preference.
"""
yield from self._output_dataset.items()
def add_data(self, data: drawings.ElementaryData):
"""Add drawing to collections.
If the given object already exists in the collections,
this interface replaces the old object instead of adding new entry.
Args:
data: New drawing to add.
"""
if not self.formatter["control.show_clbits"]:
data.bits = [b for b in data.bits if not isinstance(b, circuit.Clbit)]
self._collections[data.data_key] = data
# pylint: disable=cyclic-import
def load_program(self, program: circuit.QuantumCircuit):
"""Load quantum circuit and create drawing..
Args:
program: Scheduled circuit object to draw.
Raises:
VisualizationError: When circuit is not scheduled.
"""
not_gate_like = (circuit.Barrier,)
if getattr(program, "_op_start_times") is None:
# Run scheduling for backward compatibility
from qiskit import transpile
from qiskit.transpiler import InstructionDurations, TranspilerError
warnings.warn(
"Visualizing un-scheduled circuit with timeline drawer has been deprecated. "
"This circuit should be transpiled with scheduler though it consists of "
"instructions with explicit durations.",
DeprecationWarning,
)
try:
program = transpile(
program,
scheduling_method="alap",
instruction_durations=InstructionDurations(),
optimization_level=0,
)
except TranspilerError as ex:
raise VisualizationError(
f"Input circuit {program.name} is not scheduled and it contains "
"operations with unknown delays. This cannot be visualized."
) from ex
for t0, instruction in zip(program.op_start_times, program.data):
bits = list(instruction.qubits) + list(instruction.clbits)
for bit_pos, bit in enumerate(bits):
if not isinstance(instruction.operation, not_gate_like):
# Generate draw object for gates
gate_source = types.ScheduledGate(
t0=t0,
operand=instruction.operation,
duration=instruction.operation.duration,
bits=bits,
bit_position=bit_pos,
)
for gen in self.generator["gates"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(gate_source):
self.add_data(datum)
if len(bits) > 1 and bit_pos == 0:
# Generate draw object for gate-gate link
line_pos = t0 + 0.5 * instruction.operation.duration
link_source = types.GateLink(
t0=line_pos, opname=instruction.operation.name, bits=bits
)
for gen in self.generator["gate_links"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(link_source):
self.add_data(datum)
if isinstance(instruction.operation, circuit.Barrier):
# Generate draw object for barrier
barrier_source = types.Barrier(t0=t0, bits=bits, bit_position=bit_pos)
for gen in self.generator["barriers"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(barrier_source):
self.add_data(datum)
self.bits = list(program.qubits) + list(program.clbits)
for bit in self.bits:
for gen in self.generator["bits"]:
# Generate draw objects for bit
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(bit):
self.add_data(datum)
# update time range
t_end = max(program.duration, self.formatter["margin.minimum_duration"])
self.set_time_range(t_start=0, t_end=t_end)
def set_time_range(self, t_start: int, t_end: int):
"""Set time range to draw.
Args:
t_start: Left boundary of drawing in units of cycle time.
t_end: Right boundary of drawing in units of cycle time.
"""
self.time_range = (t_start, t_end)
def set_disable_bits(self, bit: types.Bits, remove: bool = True):
"""Interface method to control visibility of bits.
Specified object in the blocked list will not be shown.
Args:
bit: A qubit or classical bit object to disable.
remove: Set `True` to disable, set `False` to enable.
"""
if remove:
self.disable_bits.add(bit)
else:
self.disable_bits.discard(bit)
def set_disable_type(self, data_type: types.DataTypes, remove: bool = True):
"""Interface method to control visibility of data types.
Specified object in the blocked list will not be shown.
Args:
data_type: A drawing data type to disable.
remove: Set `True` to disable, set `False` to enable.
"""
if isinstance(data_type, Enum):
data_type_str = str(data_type.value)
else:
data_type_str = data_type
if remove:
self.disable_types.add(data_type_str)
else:
self.disable_types.discard(data_type_str)
def update(self):
"""Update all collections.
This method should be called before the canvas is passed to the plotter.
"""
self._output_dataset.clear()
self.assigned_coordinates.clear()
# update coordinate
y0 = -self.formatter["margin.top"]
for bit in self.layout["bit_arrange"](self.bits):
# remove classical bit
if isinstance(bit, circuit.Clbit) and not self.formatter["control.show_clbits"]:
continue
# remove idle bit
if not self._check_bit_visible(bit):
continue
offset = y0 - 0.5
self.assigned_coordinates[bit] = offset
y0 = offset - 0.5
self.vmax = 0
self.vmin = y0 - self.formatter["margin.bottom"]
# add data
temp_gate_links = {}
temp_data = {}
for data_key, data in self._collections.items():
# deep copy to keep original data hash
new_data = deepcopy(data)
new_data.xvals = self._bind_coordinate(data.xvals)
new_data.yvals = self._bind_coordinate(data.yvals)
if data.data_type == str(types.LineType.GATE_LINK.value):
temp_gate_links[data_key] = new_data
else:
temp_data[data_key] = new_data
# update horizontal offset of gate links
temp_data.update(self._check_link_overlap(temp_gate_links))
# push valid data
for data_key, data in temp_data.items():
if self._check_data_visible(data):
self._output_dataset[data_key] = data
def _check_data_visible(self, data: drawings.ElementaryData) -> bool:
"""A helper function to check if the data is visible.
Args:
data: Drawing object to test.
Returns:
Return `True` if the data is visible.
"""
_barriers = [str(types.LineType.BARRIER.value)]
_delays = [str(types.BoxType.DELAY.value), str(types.LabelType.DELAY.value)]
def _time_range_check(_data):
"""If data is located outside the current time range."""
t0, t1 = self.time_range
if np.max(_data.xvals) < t0 or np.min(_data.xvals) > t1:
return False
return True
def _associated_bit_check(_data):
"""If any associated bit is not shown."""
if all(bit not in self.assigned_coordinates for bit in _data.bits):
return False
return True
def _data_check(_data):
"""If data is valid."""
if _data.data_type == str(types.LineType.GATE_LINK.value):
active_bits = [bit for bit in _data.bits if bit not in self.disable_bits]
if len(active_bits) < 2:
return False
elif _data.data_type in _barriers and not self.formatter["control.show_barriers"]:
return False
elif _data.data_type in _delays and not self.formatter["control.show_delays"]:
return False
return True
checks = [_time_range_check, _associated_bit_check, _data_check]
if all(check(data) for check in checks):
return True
return False
def _check_bit_visible(self, bit: types.Bits) -> bool:
"""A helper function to check if the bit is visible.
Args:
bit: Bit object to test.
Returns:
Return `True` if the bit is visible.
"""
_gates = [str(types.BoxType.SCHED_GATE.value), str(types.SymbolType.FRAME.value)]
if bit in self.disable_bits:
return False
if self.formatter["control.show_idle"]:
return True
for data in self._collections.values():
if bit in data.bits and data.data_type in _gates:
return True
return False
def _bind_coordinate(self, vals: Iterator[types.Coordinate]) -> np.ndarray:
"""A helper function to bind actual coordinates to an `AbstractCoordinate`.
Args:
vals: Sequence of coordinate objects associated with a drawing.
Returns:
Numpy data array with substituted values.
"""
def substitute(val: types.Coordinate):
if val == types.AbstractCoordinate.LEFT:
return self.time_range[0]
if val == types.AbstractCoordinate.RIGHT:
return self.time_range[1]
if val == types.AbstractCoordinate.TOP:
return self.vmax
if val == types.AbstractCoordinate.BOTTOM:
return self.vmin
raise VisualizationError(f"Coordinate {val} is not supported.")
try:
return np.asarray(vals, dtype=float)
except TypeError:
return np.asarray(list(map(substitute, vals)), dtype=float)
def _check_link_overlap(
self, links: dict[str, drawings.GateLinkData]
) -> dict[str, drawings.GateLinkData]:
"""Helper method to check overlap of bit links.
This method dynamically shifts horizontal position of links if they are overlapped.
"""
duration = self.time_range[1] - self.time_range[0]
allowed_overlap = self.formatter["margin.link_interval_percent"] * duration
# return y coordinates
def y_coords(link: drawings.GateLinkData):
return np.array([self.assigned_coordinates.get(bit, np.nan) for bit in link.bits])
# group overlapped links
overlapped_group: list[list[str]] = []
data_keys = list(links.keys())
while len(data_keys) > 0:
ref_key = data_keys.pop()
overlaps = set()
overlaps.add(ref_key)
for key in data_keys[::-1]:
# check horizontal overlap
if np.abs(links[ref_key].xvals[0] - links[key].xvals[0]) < allowed_overlap:
# check vertical overlap
y0s = y_coords(links[ref_key])
y1s = y_coords(links[key])
v1 = np.nanmin(y0s) - np.nanmin(y1s)
v2 = np.nanmax(y0s) - np.nanmax(y1s)
v3 = np.nanmin(y0s) - np.nanmax(y1s)
v4 = np.nanmax(y0s) - np.nanmin(y1s)
if not (v1 * v2 > 0 and v3 * v4 > 0):
overlaps.add(data_keys.pop(data_keys.index(key)))
overlapped_group.append(list(overlaps))
# renew horizontal offset
new_links = {}
for overlaps in overlapped_group:
if len(overlaps) > 1:
xpos_mean = np.mean([links[key].xvals[0] for key in overlaps])
# sort link key by y position
sorted_keys = sorted(overlaps, key=lambda x: np.nanmax(y_coords(links[x])))
x0 = xpos_mean - 0.5 * allowed_overlap * (len(overlaps) - 1)
for ind, key in enumerate(sorted_keys):
data = links[key]
data.xvals = [x0 + ind * allowed_overlap]
new_links[key] = data
else:
key = overlaps[0]
new_links[key] = links[key]
return {key: new_links[key] for key in links.keys()}
|
https://github.com/peiyong-addwater/Hackathon-QNLP
|
peiyong-addwater
|
import re
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import string
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer, SnowballStemmer
from nltk import pos_tag, ne_chunk
from nltk.chunk import tree2conlltags
import os
import seaborn as sns
import matplotlib.pyplot as plt
from collections import Counter
import nltk
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('averaged_perceptron_tagger')
nltk.download('maxent_ne_chunker')
nltk.download('words')
import warnings
warnings.filterwarnings("ignore")
pd.set_option('display.width', 1000)
pd.options.display.max_colwidth=120
print(os.getcwd())
columns = ["Id","Entity","Target","Text"]
data = pd.read_csv("/app/data/twitter_training.csv", names=columns,header=None)
data.head()
df_train = data[["Text","Target"]]
df_train = df_train.loc[(df_train["Target"]=='Positive') | (df_train["Target"]=='Negative')]
df_train.head()
df_train.info()
df_train= df_train.drop_duplicates()
df_train.info()
sns.countplot(x="Target",data=df_train)
data_val = pd.read_csv("/app/data/twitter_validation.csv", names=columns,header=None)
data_val.head()
df_val = data_val[['Text', 'Target']]
df_val = df_val.loc[(df_val['Target'] == 'Positive') | (df_val['Target'] == 'Negative')]
df_val.head()
df_val.info()
sns.countplot(x="Target",data=df_val)
text_cleaning_re = "@\S+|https?:\S+|http?:\S|[^A-Za-z0-9]+"
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
"]+", flags=re.UNICODE)
stemmer = SnowballStemmer('english')
def preprocess(text):
text = re.sub(text_cleaning_re, ' ', str(text).lower()).strip()
text = emoji_pattern.sub(r'', text)
tokens = []
for token in text.split():
tokens.append(token)
return " ".join(tokens)
df_train["Text"] = df_train["Text"].apply(preprocess)
df_train["Text"]= df_train["Text"].str.replace("im","i am")
df_train["Text"].head()
df_val["Text"] = df_val["Text"].apply(preprocess)
df_val["Text"]=df_val["Text"].str.replace("im","i am")
df_val["Text"].head()
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 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.
"""An algorithm to implement a Trotterization real time-evolution."""
from __future__ import annotations
from qiskit import QuantumCircuit
from qiskit_algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem
from qiskit_algorithms.time_evolvers.time_evolution_result import TimeEvolutionResult
from qiskit_algorithms.time_evolvers.real_time_evolver import RealTimeEvolver
from qiskit_algorithms.observables_evaluator import estimate_observables
from qiskit.opflow import PauliSumOp
from qiskit.circuit.library import PauliEvolutionGate
from qiskit.circuit.parametertable import ParameterView
from qiskit.primitives import BaseEstimator
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.synthesis import ProductFormula, LieTrotter
class TrotterQRTE(RealTimeEvolver):
"""Quantum Real Time Evolution using Trotterization.
Type of Trotterization is defined by a ``ProductFormula`` provided.
Examples:
.. code-block:: python
from qiskit.opflow import PauliSumOp
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit import QuantumCircuit
from qiskit_algorithms import TimeEvolutionProblem
from qiskit_algorithms.time_evolvers import TrotterQRTE
from qiskit.primitives import Estimator
operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")]))
initial_state = QuantumCircuit(1)
time = 1
evolution_problem = TimeEvolutionProblem(operator, time, initial_state)
# LieTrotter with 1 rep
estimator = Estimator()
trotter_qrte = TrotterQRTE(estimator=estimator)
evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state
"""
def __init__(
self,
product_formula: ProductFormula | None = None,
estimator: BaseEstimator | None = None,
num_timesteps: int = 1,
) -> None:
"""
Args:
product_formula: A Lie-Trotter-Suzuki product formula. If ``None`` provided, the
Lie-Trotter first order product formula with a single repetition is used. ``reps``
should be 1 to obtain a number of time-steps equal to ``num_timesteps`` and an
evaluation of :attr:`.TimeEvolutionProblem.aux_operators` at every time-step. If ``reps``
is larger than 1, the true number of time-steps will be ``num_timesteps * reps``.
num_timesteps: The number of time-steps the full evolution time is devided into
(repetitions of ``product_formula``)
estimator: An estimator primitive used for calculating expectation values of
``TimeEvolutionProblem.aux_operators``.
"""
self.product_formula = product_formula
self.num_timesteps = num_timesteps
self.estimator = estimator
@property
def product_formula(self) -> ProductFormula:
"""Returns a product formula."""
return self._product_formula
@product_formula.setter
def product_formula(self, product_formula: ProductFormula | None):
"""Sets a product formula. If ``None`` provided, sets the Lie-Trotter first order product
formula with a single repetition."""
if product_formula is None:
product_formula = LieTrotter()
self._product_formula = product_formula
@property
def estimator(self) -> BaseEstimator | None:
"""
Returns an estimator.
"""
return self._estimator
@estimator.setter
def estimator(self, estimator: BaseEstimator) -> None:
"""
Sets an estimator.
"""
self._estimator = estimator
@property
def num_timesteps(self) -> int:
"""Returns the number of timesteps."""
return self._num_timesteps
@num_timesteps.setter
def num_timesteps(self, num_timesteps: int) -> None:
"""
Sets the number of time-steps.
Raises:
ValueError: If num_timesteps is not positive.
"""
if num_timesteps <= 0:
raise ValueError(
f"Number of time steps must be positive integer, {num_timesteps} provided"
)
self._num_timesteps = num_timesteps
@classmethod
def supports_aux_operators(cls) -> bool:
"""
Whether computing the expectation value of auxiliary operators is supported.
Returns:
``True`` if ``aux_operators`` expectations in the ``TimeEvolutionProblem`` can be
evaluated, ``False`` otherwise.
"""
return True
def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult:
"""
Evolves a quantum state for a given time using the Trotterization method
based on a product formula provided. The result is provided in the form of a quantum
circuit. If auxiliary operators are included in the ``evolution_problem``, they are
evaluated on the ``init_state`` and on the evolved state at every step (``num_timesteps``
times) using an estimator primitive provided.
Args:
evolution_problem: Instance defining evolution problem. For the included Hamiltonian,
``Pauli`` or ``PauliSumOp`` are supported by TrotterQRTE.
Returns:
Evolution result that includes an evolved state as a quantum circuit and, optionally,
auxiliary operators evaluated for a resulting state on an estimator primitive.
Raises:
ValueError: If ``t_param`` is not set to ``None`` in the ``TimeEvolutionProblem``
(feature not currently supported).
ValueError: If ``aux_operators`` provided in the time evolution problem but no estimator
provided to the algorithm.
ValueError: If the ``initial_state`` is not provided in the ``TimeEvolutionProblem``.
ValueError: If an unsupported Hamiltonian type is provided.
"""
evolution_problem.validate_params()
if evolution_problem.aux_operators is not None and self.estimator is None:
raise ValueError(
"The time evolution problem contained ``aux_operators`` but no estimator was "
"provided. The algorithm continues without calculating these quantities. "
)
# ensure the hamiltonian is a sparse pauli op
hamiltonian = evolution_problem.hamiltonian
if not isinstance(hamiltonian, (Pauli, PauliSumOp, SparsePauliOp)):
raise ValueError(
f"TrotterQRTE only accepts Pauli | PauliSumOp | SparsePauliOp, {type(hamiltonian)} "
"provided."
)
if isinstance(hamiltonian, PauliSumOp):
hamiltonian = hamiltonian.primitive * hamiltonian.coeff
elif isinstance(hamiltonian, Pauli):
hamiltonian = SparsePauliOp(hamiltonian)
t_param = evolution_problem.t_param
free_parameters = hamiltonian.parameters
if t_param is not None and free_parameters != ParameterView([t_param]):
raise ValueError(
f"Hamiltonian time parameters ({free_parameters}) do not match "
f"evolution_problem.t_param ({t_param})."
)
# make sure PauliEvolutionGate does not implement more than one Trotter step
dt = evolution_problem.time / self.num_timesteps
if evolution_problem.initial_state is not None:
initial_state = evolution_problem.initial_state
else:
raise ValueError("``initial_state`` must be provided in the ``TimeEvolutionProblem``.")
evolved_state = QuantumCircuit(initial_state.num_qubits)
evolved_state.append(initial_state, evolved_state.qubits)
if evolution_problem.aux_operators is not None:
observables = []
observables.append(
estimate_observables(
self.estimator,
evolved_state,
evolution_problem.aux_operators,
None,
evolution_problem.truncation_threshold,
)
)
else:
observables = None
if t_param is None:
# the evolution gate
single_step_evolution_gate = PauliEvolutionGate(
hamiltonian, dt, synthesis=self.product_formula
)
for n in range(self.num_timesteps):
# if hamiltonian is time-dependent, bind new time-value at every step to construct
# evolution for next step
if t_param is not None:
time_value = (n + 1) * dt
bound_hamiltonian = hamiltonian.assign_parameters([time_value])
single_step_evolution_gate = PauliEvolutionGate(
bound_hamiltonian,
dt,
synthesis=self.product_formula,
)
evolved_state.append(single_step_evolution_gate, evolved_state.qubits)
if evolution_problem.aux_operators is not None:
observables.append(
estimate_observables(
self.estimator,
evolved_state,
evolution_problem.aux_operators,
None,
evolution_problem.truncation_threshold,
)
)
evaluated_aux_ops = None
if evolution_problem.aux_operators is not None:
evaluated_aux_ops = observables[-1]
return TimeEvolutionResult(evolved_state, evaluated_aux_ops, observables)
|
https://github.com/usamisaori/quantum-expressibility-entangling-capability
|
usamisaori
|
import numpy as np
from qiskit.quantum_info import state_fidelity, Statevector
def getStatevector(circuit):
return Statevector(circuit).data
import warnings
warnings.filterwarnings('ignore')
def P_haar(N, F):
if F == 1:
return 0
else:
return (N - 1) * ((1 - F) ** (N - 2))
def KL(P, Q):
epsilon = 1e-8
kl_divergence = 0.0
for p, q in zip(P, Q):
kl_divergence += p * np.log( (p + epsilon) / (q + epsilon) )
return abs(kl_divergence)
def expressibility(qubits, sampler, *, bins=100, epoch=3000, layer=1, encode=False, return_detail=False):
unit = 1 / bins
limits = []
probabilities = np.array([0] * bins)
for i in range(1, bins + 1):
limits.append(unit * i)
for i in range(epoch):
circuit_1 = sampler(layer=layer, qubits=qubits)
circuit_2 = sampler(layer=layer, qubits=qubits)
f = state_fidelity(
getStatevector(circuit_1),
getStatevector(circuit_2)
)
for j in range(bins):
if f <= limits[j]:
probabilities[j] += 1
break
pHaar_vqc = [ P_haar(2 ** qubits, f - (unit/2)) / bins for f in limits]
probabilities = [ p / epoch for p in probabilities ]
if return_detail:
return pHaar_vqc, probabilities
else:
return KL(probabilities, pHaar_vqc)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Quantum Operation Mixin."""
from abc import ABC, abstractmethod
class Operation(ABC):
"""Quantum Operation Interface Class.
For objects that can be added to a :class:`~qiskit.circuit.QuantumCircuit`.
These objects include :class:`~qiskit.circuit.Gate`, :class:`~qiskit.circuit.Reset`,
:class:`~qiskit.circuit.Barrier`, :class:`~qiskit.circuit.Measure`,
and operators such as :class:`~qiskit.quantum_info.Clifford`.
The main purpose is to add an :class:`~qiskit.circuit.Operation` to a
:class:`~qiskit.circuit.QuantumCircuit` without synthesizing it before the transpilation.
Example:
Add a Clifford and a Toffoli gate to a QuantumCircuit.
.. plot::
:include-source:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford, random_clifford
qc = QuantumCircuit(3)
cliff = random_clifford(2)
qc.append(cliff, [0, 1])
qc.ccx(0, 1, 2)
qc.draw('mpl')
"""
__slots__ = ()
@property
@abstractmethod
def name(self):
"""Unique string identifier for operation type."""
raise NotImplementedError
@property
@abstractmethod
def num_qubits(self):
"""Number of qubits."""
raise NotImplementedError
@property
@abstractmethod
def num_clbits(self):
"""Number of classical bits."""
raise NotImplementedError
|
https://github.com/amitcrypto/ARIA-Blocks-Qiskit
|
amitcrypto
|
# Copyright (c) Amit Kumar Chauhan, IIT Ropar, India.
# Licensed under the GNU General Public License.
# Importing standard Qiskit libraries and configuring account
import qiskit
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# Creating qubits
q = qiskit.QuantumRegister(128)
circuit = qiskit.QuantumCircuit(q)
# Applying CNOT gates on the register of qubits
circuit.cx(q[4], q[0])
circuit.cx(q[6], q[0])
circuit.cx(q[5], q[1])
circuit.cx(q[4], q[2])
circuit.cx(q[7], q[2])
circuit.cx(q[5], q[3])
circuit.cx(q[6], q[4])
circuit.cx(q[7], q[4])
circuit.cx(q[6], q[5])
circuit.cx(q[6], q[7])
circuit.cx(q[5], q[6])
circuit.cx(q[4], q[6])
# Printing the circuit
qc = circuit.draw()
print(qc)
# Estimating the circuit depth
d = QuantumCircuit.depth(circuit)
print('The Circuit Depth :=', d)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.primitives import Sampler
sampler = Sampler()
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
circuit = random_circuit(2, 2, seed=1, measure=True).decompose(reps=1)
job = sampler.run(circuit)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
circuits = (
random_circuit(2, 2, seed=0, measure=True).decompose(reps=1),
random_circuit(2, 2, seed=1, measure=True).decompose(reps=1),
)
job = sampler.run(circuits)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f">>> Quasi-distribution: {result.quasi_dists}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
circuit.measure_all()
parameter_values = [0, 1, 2, 3, 4, 5]
job = sampler.run(circuit, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Parameter values: {parameter_values}")
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Sampler
sampler = Sampler(session=backend)
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Metadata: {result.metadata[0]}")
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
sampler = Sampler()
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the first run: {result.quasi_dists[0]}")
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the second run: {result.quasi_dists[0]}")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
estimator_circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(estimator_circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(estimator_circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/ka-us-tubh/quantum-computing-qiskit-
|
ka-us-tubh
|
from ibm_quantum_widgets import CircuitComposer
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from numpy import pi
qreg_q = QuantumRegister(4, 'q')
creg_c = ClassicalRegister(4, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.x(qreg_q[3])
circuit.barrier(qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3])
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
circuit.h(qreg_q[3])
circuit.barrier(qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3])
circuit.cx(qreg_q[2], qreg_q[3])
circuit.cx(qreg_q[0], qreg_q[3])
circuit.barrier(qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3])
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
circuit.measure(qreg_q[0], creg_c[0])
circuit.measure(qreg_q[1], creg_c[1])
circuit.measure(qreg_q[2], creg_c[2])
editor = CircuitComposer(circuit=circuit)
editor
|
https://github.com/Qiskit/feedback
|
Qiskit
|
import warnings
warnings.filterwarnings('ignore')
import datetime
import os
import json
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as opt
from scipy import signal
from qiskit import IBMQ, pulse, circuit
from qiskit.visualization.pulse_v2 import IQXDebugging
from qiskit.result import Result, marginal_counts
from qiskit.providers.ibmq.utils.json_encoder import IQXJsonEncoder
from qiskit.providers.ibmq.utils.json_decoder import decode_result
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):
return obj.isoformat()
elif isinstance(obj, datetime.timedelta):
return (datetime.datetime.min + obj).time().isoformat()
return super(DateTimeEncoder, self).default(obj)
IBMQ.load_account()
backend = IBMQ.get_provider("ibm-q-internal", "deployed", "default").get_backend("ibmq_lima")
qubits = 0, 1
durs1 = 160, 880
durs2 = 320, 1760
basename = "lima_20210813"
def get_params(sx_dur, cx_dur, sigma_r=4, cx_sigma=64, cx_risefall=2):
return {
"sx0": {"duration": sx_dur, "amp": 0., "sigma": sx_dur/sigma_r, "beta": 0.},
"sx1": {"duration": sx_dur, "amp": 0., "sigma": sx_dur/sigma_r, "beta": 0.},
"ecr": {"duration": cx_dur, "amp": 0., "phase": 0., "sigma": cx_sigma, "risefall_sigma_ratio": cx_risefall}
}
def rough_amp(qubits, amps, cals):
amp = circuit.Parameter("amp")
with pulse.build(backend, default_alignment="sequential") as sched:
with pulse.align_left():
for ind, q in enumerate(qubits):
sxcal = cals[f"sx{ind}"].copy()
sxcal["amp"] = amp
pulse.play(pulse.Drag(**sxcal), pulse.drive_channel(q))
pulse.measure(qubits, [pulse.MemorySlot(ind) for ind in range(len(qubits))])
return [sched.assign_parameters({amp: amp_val}, inplace=False) for amp_val in amps]
def rough_amp_cr(qubits, amps, cals):
amp = circuit.Parameter("amp")
qc, qt = qubits
with pulse.build(backend, default_alignment="sequential") as sched:
sxcal = cals["sx0"]
crcal = cals["ecr"].copy()
crcal["amp"] = amp * np.exp(1j*crcal.pop("phase", 0.))
u_chan = pulse.control_channels(*qubits)[0]
pulse.play(pulse.GaussianSquare(**crcal), u_chan)
pulse.play(pulse.Drag(**sxcal), pulse.drive_channel(qc))
pulse.play(pulse.Drag(**sxcal), pulse.drive_channel(qc))
with pulse.phase_offset(np.pi, u_chan):
pulse.play(pulse.GaussianSquare(**crcal), u_chan)
pulse.measure([qt], [pulse.MemorySlot(0)])
return [sched.assign_parameters({amp: amp_val}, inplace=False) for amp_val in amps]
def phase_cr(qubits, phases, cals):
phase = circuit.Parameter("phase")
qc, qt = qubits
with pulse.build(backend, default_alignment="sequential") as sched:
sxcal_c = cals["sx0"]
sxcal_t = cals["sx1"]
crcal = cals["ecr"].copy()
crcal.pop("phase")
crcal["amp"] *= np.exp(1j*phase)
u_chan = pulse.control_channels(*qubits)[0]
pulse.play(pulse.GaussianSquare(**crcal), u_chan)
pulse.play(pulse.Drag(**sxcal_c), pulse.drive_channel(qc))
pulse.play(pulse.Drag(**sxcal_c), pulse.drive_channel(qc))
with pulse.phase_offset(np.pi, u_chan):
pulse.play(pulse.GaussianSquare(**crcal), u_chan)
pulse.play(pulse.Drag(**sxcal_t), pulse.drive_channel(qt))
pulse.measure([qt], [pulse.MemorySlot(0)])
return [sched.assign_parameters({phase: val}, inplace=False) for val in phases]
def fine_amp(qubits, delta_amps, n_rep, cals):
delta_amp = circuit.Parameter("delta_amp")
with pulse.build(backend=backend, default_alignment="sequential") as sched_p:
with pulse.align_left():
for ind, q in enumerate(qubits):
sxcal = cals[f"sx{ind}"].copy()
sxcal["amp"] += delta_amp
sx_pulse = pulse.Drag(**sxcal)
for _ in range(4 * n_rep):
pulse.play(sx_pulse, pulse.drive_channel(q))
pulse.play(sx_pulse, pulse.drive_channel(q))
pulse.measure(qubits, [pulse.MemorySlot(ind) for ind in range(len(qubits))])
with pulse.build(backend=backend, default_alignment="sequential") as sched_m:
with pulse.align_left():
for ind, q in enumerate(qubits):
sxcal = cals[f"sx{ind}"].copy()
sxcal["amp"] += delta_amp
sx_pulse = pulse.Drag(**sxcal)
with pulse.phase_offset(np.pi, pulse.drive_channel(q)):
for _ in range(4 * n_rep):
pulse.play(sx_pulse, pulse.drive_channel(q))
pulse.play(sx_pulse, pulse.drive_channel(q))
pulse.measure(qubits, [pulse.MemorySlot(ind) for ind in range(len(qubits))])
sched_p_assigned = [sched_p.assign_parameters({delta_amp: val}, inplace=False) for val in delta_amps]
sched_m_assigned = [sched_m.assign_parameters({delta_amp: val}, inplace=False) for val in delta_amps]
return sched_p_assigned + sched_m_assigned
def fine_amp_cr(qubits, delta_amps, n_rep, cals):
delta_amp = circuit.Parameter("delta_amp")
qc, qt = qubits
sxcal_c = cals["sx0"]
sxcal_t = cals["sx1"]
crcal = cals["ecr"].copy()
_amp = (crcal["amp"] + delta_amp) * np.exp(1j*crcal.pop("phase", 0.))
crcal["amp"] = _amp
with pulse.build(backend, default_alignment="sequential") as sched_p:
u_chan = pulse.control_channels(*qubits)[0]
for _ in range (4 * n_rep):
pulse.play(pulse.GaussianSquare(**crcal), u_chan)
pulse.play(pulse.Drag(**sxcal_c), pulse.drive_channel(qc))
pulse.play(pulse.Drag(**sxcal_c), pulse.drive_channel(qc))
with pulse.phase_offset(np.pi, u_chan):
pulse.play(pulse.GaussianSquare(**crcal), u_chan)
pulse.play(pulse.Drag(**sxcal_c), pulse.drive_channel(qc))
pulse.play(pulse.Drag(**sxcal_c), pulse.drive_channel(qc))
pulse.play(pulse.Drag(**sxcal_t), pulse.drive_channel(qt))
pulse.measure([qt], [pulse.MemorySlot(0)])
with pulse.build(backend=backend, default_alignment="sequential") as sched_m:
u_chan = pulse.control_channels(*qubits)[0]
for _ in range (4 * n_rep):
with pulse.phase_offset(np.pi, u_chan):
pulse.play(pulse.GaussianSquare(**crcal), u_chan)
pulse.play(pulse.Drag(**sxcal_c), pulse.drive_channel(qc))
pulse.play(pulse.Drag(**sxcal_c), pulse.drive_channel(qc))
pulse.play(pulse.GaussianSquare(**crcal), u_chan)
pulse.play(pulse.Drag(**sxcal_c), pulse.drive_channel(qc))
pulse.play(pulse.Drag(**sxcal_c), pulse.drive_channel(qc))
pulse.play(pulse.Drag(**sxcal_t), pulse.drive_channel(qt))
pulse.measure([qt], [pulse.MemorySlot(0)])
sched_p_assigned = [sched_p.assign_parameters({delta_amp: val}, inplace=False) for val in delta_amps]
sched_m_assigned = [sched_m.assign_parameters({delta_amp: val}, inplace=False) for val in delta_amps]
return sched_p_assigned + sched_m_assigned
def fine_beta(qubits, delta_betas, n_rep, cals):
delta_beta = circuit.Parameter("beta")
with pulse.build(backend=backend, default_alignment="sequential") as sched_p:
with pulse.align_left():
for ind, q in enumerate(qubits):
sxcal = cals[f"sx{ind}"].copy()
sxcal["beta"] += delta_beta
sx_pulse = pulse.Drag(**sxcal)
pulse.play(sx_pulse, pulse.drive_channel(q))
for _ in range(n_rep):
pulse.play(sx_pulse, pulse.drive_channel(q))
with pulse.phase_offset(np.pi, pulse.drive_channel(q)):
pulse.play(sx_pulse, pulse.drive_channel(q))
with pulse.phase_offset(0.5 * np.pi, pulse.drive_channel(q)):
pulse.play(sx_pulse, pulse.drive_channel(q))
pulse.measure(qubits, [pulse.MemorySlot(ind) for ind in range(len(qubits))])
with pulse.build(backend=backend, default_alignment="sequential") as sched_m:
with pulse.align_left():
for ind, q in enumerate(qubits):
sxcal = cals[f"sx{ind}"].copy()
sxcal["beta"] += delta_beta
sx_pulse = pulse.Drag(**sxcal)
pulse.play(sx_pulse, pulse.drive_channel(q))
for _ in range(n_rep):
pulse.play(sx_pulse, pulse.drive_channel(q))
with pulse.phase_offset(np.pi, pulse.drive_channel(q)):
pulse.play(sx_pulse, pulse.drive_channel(q))
with pulse.phase_offset(-0.5 * np.pi, pulse.drive_channel(q)):
pulse.play(sx_pulse, pulse.drive_channel(q))
pulse.measure(qubits, [pulse.MemorySlot(ind) for ind in range(len(qubits))])
sched_p_assigned = [sched_p.assign_parameters({delta_beta: val}, inplace=False) for val in delta_betas]
sched_m_assigned = [sched_m.assign_parameters({delta_beta: val}, inplace=False) for val in delta_betas]
return sched_p_assigned + sched_m_assigned
def run(scheds, exp_name, **options):
fpstr = f"./{basename}_{exp_name}.json"
if os.path.isfile(fpstr):
with open(fpstr, "r") as fp:
cache = json.load(fp)
return Result.from_dict(cache)
job = backend.run(scheds, **options)
result = job.result(timeout=3600)
with open(fpstr, "w") as fp:
json.dump(result.to_dict(), fp, cls=DateTimeEncoder)
return result
def get_expval(result, ind, shots):
res = []
for circ_res in result.get_counts():
counts = 0
for key, count in circ_res.items():
if key[::-1][ind] == "1":
counts += count
res.append(counts/shots)
return 2 * (0.5 - np.asarray(res, dtype=float))
def find_cross_point(xdata, ydata1, ydata2, n=4, filt_dim=5):
ydata1 = signal.savgol_filter(ydata1, filt_dim, 1)
ydata2 = signal.savgol_filter(ydata2, filt_dim, 1)
cross_points = xdata[1:][np.diff(np.sign(ydata1 - ydata2)) != 0]
main_cross = cross_points[np.argmin(np.abs(cross_points))]
idx = np.argmin(np.abs(xdata - main_cross))
x_reduced = xdata[idx-n:idx+n]
y1_reduced = ydata1[idx-n:idx+n]
y2_reduced = ydata2[idx-n:idx+n]
p1 = np.polyfit(x_reduced, y1_reduced, 1)
p2 = np.polyfit(x_reduced, y2_reduced, 1)
cross_opt = (p2[1] - p1[1]) / (p1[0] - p2[0])
return cross_opt
params1 = get_params(*durs1)
params2 = get_params(*durs2)
amps = np.linspace(-0.2, 0.2, 31)
result = run(
rough_amp(qubits, amps, params1) + rough_amp(qubits, amps, params2),
"rough_amp",
shots=128
)
fig, axs = plt.subplots(2, 1, sharex=True)
fit_func = lambda x, a, b, f: a * np.cos(2 * np.pi * f * x) + b
bounds = (0, -1, 0), (1, 1, np.inf)
for qind, ax in enumerate(axs):
expvals = np.split(get_expval(result, qind, 128), 2)
for expval, params_dict, color in zip(expvals, (params1, params2), ("r", "b")):
# freq init guess
fft_data = np.fft.fft(expval - np.average(expval))
freqs = np.fft.fftfreq(len(amps), amps[1] - amps[0])
positive_freqs = freqs[freqs >= 0]
positive_fft_data = fft_data[freqs >= 0]
f0 = positive_freqs[np.argmax(np.abs(positive_fft_data))]
# fit
pcov, _ = opt.curve_fit(fit_func, amps, expval, p0=[1, 0, f0], bounds=bounds)
# plot
ax.plot(amps, expval, "o", color=color)
ax.plot(amps, fit_func(amps, *pcov), ":", color=color)
hpi_amp = 1/(2*pcov[2])/2
ax.axvline(hpi_amp, color=color)
# update parameters
print(f"qubit {qind} amp = {hpi_amp}")
params_dict[f"sx{qind}"]["amp"] = hpi_amp
delta_amps = np.linspace(-0.02, 0.02, 21)
result = run(
fine_amp(qubits, delta_amps, 1, params1) + fine_amp(qubits, delta_amps, 1, params2),
"fine_amp1",
shots=128
)
fig, axs = plt.subplots(2, 1, sharex=True)
for qind, ax in enumerate(axs):
expvals = np.split(get_expval(result, qind, 128), 2)
for expval, params_dict, color in zip(expvals, (params1, params2), ("red", "blue")):
yp, ym = np.split(expval, 2)
p = find_cross_point(delta_amps, yp, ym)
# plot
ax.plot(delta_amps, yp, "^", color=color)
ax.plot(delta_amps, ym, "v", color=color)
ax.axvline(p, color=color)
# update parameters
print(f"qubit {qind}, Δamp = {p}")
params_dict[f"sx{qind}"]["amp"] += p
delta_betas = np.linspace(-10, 10, 21)
result = run(
fine_beta(qubits, delta_betas, 3, params1) + fine_beta(qubits, delta_betas, 3, params2),
"fine_beta1",
shots=1024
)
fig, axs = plt.subplots(2, 1, sharex=True)
for qind, ax in enumerate(axs):
expvals = np.split(get_expval(result, qind, 1024), 2)
for expval, params_dict, color in zip(expvals, (params1, params2), ("red", "blue")):
yp, ym = np.split(expval, 2)
p = find_cross_point(delta_betas, yp, ym)
# plot
ax.plot(delta_betas, yp, "^", color=color)
ax.plot(delta_betas, ym, "v", color=color)
ax.axvline(p, color=color)
# update parameters
print(f"qubit {qind}, Δbeta = {p}")
params_dict[f"sx{qind}"]["beta"] += p
delta_amps = np.linspace(-0.005, 0.005, 21)
result = run(
fine_amp(qubits, delta_amps, 2, params1) + fine_amp(qubits, delta_amps, 2, params2),
"fine_amp2",
shots=128
)
fig, axs = plt.subplots(2, 1, sharex=True)
for qind, ax in enumerate(axs):
expvals = np.split(get_expval(result, qind, 128), 2)
for expval, params_dict, color in zip(expvals, (params1, params2), ("red", "blue")):
yp, ym = np.split(expval, 2)
p = find_cross_point(delta_amps, yp, ym)
# plot
ax.plot(delta_amps, yp, "^", color=color)
ax.plot(delta_amps, ym, "v", color=color)
ax.axvline(p, color=color)
# update parameters
print(f"qubit {qind}, amp = {p}")
params_dict[f"sx{qind}"]["amp"] += p
amps = np.linspace(-0.8, 0.8, 51)
result = run(
rough_amp_cr(qubits, amps, params1) + rough_amp_cr(qubits, amps, params2),
"rough_amp_cr",
shots=128
)
fit_func = lambda x, a, b, f: a * np.cos(2 * np.pi * f * x) + b
bounds = (0, -1, 0), (1, 1, np.inf)
expvals = np.split(get_expval(result, 0, 128), 2)
for expval, params_dict, color in zip(expvals, (params1, params2), ("r", "b")):
# freq init guess
fft_data = np.fft.fft(expval - np.average(expval))
freqs = np.fft.fftfreq(len(amps), amps[1] - amps[0])
positive_freqs = freqs[freqs >= 0]
positive_fft_data = fft_data[freqs >= 0]
f0 = positive_freqs[np.argmax(np.abs(positive_fft_data))]
# fit
pcov, _ = opt.curve_fit(
fit_func,
amps,
expval,
p0=[1, 0, f0],
bounds=bounds,
sigma=1/(1-np.abs(amps)) - 0.99,
absolute_sigma=True,
)
# plot
plt.plot(amps, expval, "o", color=color)
plt.plot(amps, fit_func(amps, *pcov), ":", color=color)
hpi_amp = 1/(2*pcov[2])/2
plt.axvline(hpi_amp, color=color)
# update parameters
print(f"ECR amp = {hpi_amp}")
params_dict["ecr"]["amp"] = hpi_amp
phases = np.linspace(-np.pi, np.pi, 31)
result = run(
phase_cr(qubits, phases, params1) + phase_cr(qubits, phases, params2),
"rough_phase_cr",
shots=128
)
fit_func = lambda x, a, b, phi: a * np.cos(x - phi) + b
bounds = (0, -1, -np.pi), (1, 1, np.pi)
expvals = np.split(get_expval(result, 0, 128), 2)
for expval, params_dict, color in zip(expvals, (params1, params2), ("r", "b")):
# fit
pcov, _ = opt.curve_fit(fit_func, phases, expval, p0=[1, 0, 0], bounds=bounds)
# plot
plt.plot(phases, expval, "o", color=color)
plt.plot(phases, fit_func(phases, *pcov), ":", color=color)
cr_phase = pcov[2] + np.pi
if cr_phase > np.pi:
cr_phase -= 2 * np.pi
plt.axvline(cr_phase, color=color)
# update parameters
print(f"ECR phase = {cr_phase}")
params_dict["ecr"]["phase"] = cr_phase
delta_amps = np.linspace(-0.05, 0.05, 21)
result = run(
fine_amp_cr(qubits, delta_amps, 1, params1) + fine_amp_cr(qubits, delta_amps, 1, params2),
"fine_amp_cr",
shots=128
)
expvals = np.split(get_expval(result, 0, 128), 2)
for expval, params_dict, color in zip(expvals, (params1, params2), ("red", "blue")):
yp, ym = np.split(expval, 2)
p = find_cross_point(delta_amps, yp, ym)
# plot
plt.plot(delta_amps, yp, "^", color=color)
plt.plot(delta_amps, ym, "v", color=color)
plt.axvline(p, color=color)
# update parameters
print(f"ECR Δamp = {p}")
params_dict[f"ecr"]["amp"] += p
params1
params2
from qiskit_experiments.calibration_management import BackendCalibrations
from qiskit_experiments.calibration_management.parameter_value import ParameterValue
from datetime import datetime
import pandas as pd
cal_manager = BackendCalibrations(backend=backend)
# add sx schedule
sx_amp = circuit.Parameter("amp")
sx_dur = circuit.Parameter("τ")
sx_beta = circuit.Parameter("β")
sx_sigma = circuit.Parameter("σ")
ch_d = pulse.DriveChannel(circuit.Parameter("ch0"))
with pulse.build(name="sx") as sx_sched:
pulse.play(
pulse.Drag(duration=sx_dur, amp=sx_amp, sigma=sx_sigma, beta=sx_beta),
ch_d
)
cal_manager.add_schedule(sx_sched)
# parameters for ecr
ecr_amp = circuit.Parameter("amp")
ecr_phase = circuit.Parameter("θ")
ecr_dur = circuit.Parameter("τ")
ecr_sigma = circuit.Parameter("σ")
ch_u = backend.configuration().control(qubits)[0]
with pulse.build(name="ecr", default_alignment="sequential") as ecr_sched:
with pulse.phase_offset(ecr_phase, ch_u):
pulse.play(
pulse.GaussianSquare(duration=ecr_dur, amp=ecr_amp, sigma=ecr_sigma, risefall_sigma_ratio=2),
ch_u
)
pulse.call(cal_manager.get_template("sx", qubits=(qubits[0], )))
pulse.call(cal_manager.get_template("sx", qubits=(qubits[0], )))
pulse.play(
pulse.GaussianSquare(duration=ecr_dur, amp=-ecr_amp, sigma=ecr_sigma, risefall_sigma_ratio=2),
ch_u
)
cal_manager.add_schedule(ecr_sched)
for ind, param in enumerate([params1, params2]):
group = ind + 1
# sx
for qind in qubits:
cal_manager.add_parameter_value(
value=ParameterValue(value=param[f"sx{qind}"]["duration"], date_time=datetime.now(), group=f"sf{group}"),
param=sx_dur,
qubits=qind,
schedule="sx",
)
cal_manager.add_parameter_value(
value=ParameterValue(value=param[f"sx{qind}"]["amp"], date_time=datetime.now(), group=f"sf{group}"),
param=sx_amp,
qubits=qind,
schedule="sx",
)
cal_manager.add_parameter_value(
value=ParameterValue(value=param[f"sx{qind}"]["sigma"], date_time=datetime.now(), group=f"sf{group}"),
param=sx_sigma,
qubits=qind,
schedule="sx",
)
cal_manager.add_parameter_value(
value=ParameterValue(value=param[f"sx{qind}"]["beta"], date_time=datetime.now(), group=f"sf{group}"),
param=sx_beta,
qubits=qind,
schedule="sx",
)
cal_manager.add_parameter_value(
value=ParameterValue(value=qind, date_time=datetime.now(), group=f"sf{group}"),
param=ch_d,
qubits=qind,
schedule="sx",
)
# ecr
cal_manager.add_parameter_value(
value=ParameterValue(value=param["ecr"]["duration"], date_time=datetime.now(), group=f"sf{group}"),
param=ecr_dur,
qubits=qubits,
schedule="ecr",
)
cal_manager.add_parameter_value(
value=ParameterValue(value=param["ecr"]["amp"], date_time=datetime.now(), group=f"sf{group}"),
param=ecr_amp,
qubits=qubits,
schedule="ecr",
)
cal_manager.add_parameter_value(
value=ParameterValue(value=param["ecr"]["phase"], date_time=datetime.now(), group=f"sf{group}"),
param=ecr_phase,
qubits=qubits,
schedule="ecr",
)
cal_manager.add_parameter_value(
value=ParameterValue(value=param["ecr"]["sigma"], date_time=datetime.now(), group=f"sf{group}"),
param=ecr_sigma,
qubits=qubits,
schedule="ecr",
)
cal_manager.add_parameter_value(
value=ParameterValue(value=qubits[0], date_time=datetime.now(), group=f"sf{group}"),
param=ch_d,
qubits=qubits[0],
schedule="ecr",
)
df = pd.DataFrame(cal_manager.parameters_table())
df[df["schedule"].notna()].sort_values(["group", "schedule"])
df.query("schedule == 'ecr' and parameter in ['amp', 'τ']").sort_values(["parameter"])
fig, axs = plt.subplots(2, 1, sharex=True, figsize=(13, 8))
cal_manager.get_schedule("ecr", qubits=qubits, group="sf1").draw(backend=backend, axis=axs[0], style=IQXDebugging(**{"formatter.margin.left_percent": 0.1}))
cal_manager.get_schedule("ecr", qubits=qubits, group="sf2").draw(backend=backend, axis=axs[1], style=IQXDebugging())
gates_to_output = {"sx": [0, 1], "ecr": [(0, 1)]}
sf1_backend = cal_manager.export_backend(
outputs=gates_to_output,
basis_gates=["sx", "rz", "ecr"],
coupling_map=[[0, 1]],
group="sf1",
)
sf2_backend = cal_manager.export_backend(
outputs=gates_to_output,
basis_gates=["sx", "rz", "ecr"],
coupling_map=[[0, 1]],
group="sf2",
)
sf1_backend.configuration().basis_gates
sf1_backend.configuration().coupling_map
ecr_sched_sf1 = sf1_backend.defaults().instruction_schedule_map.get("ecr", (0, 1))
ecr_sched_sf1.draw(backend=backend)
ecr_sched_sf1.metadata
sf1_backend.defaults().instruction_schedule_map.get("rz", (0,)).metadata
from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import ParityMapper
from qiskit.circuit.library import EfficientSU2
from qiskit.algorithms.optimizers import SPSA
from qiskit.algorithms import VQE
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver
from qiskit.utils import QuantumInstance
molecule = Molecule(
geometry=[['H', [0., 0., 0.]], ['H', [0., 0., 0.735]]],
charge=0,
multiplicity=1
)
driver = PySCFDriver(molecule = molecule, unit=UnitsType.ANGSTROM, basis='sto3g')
es_problem = ElectronicStructureProblem(driver)
qubit_converter = QubitConverter(ParityMapper(), two_qubit_reduction=True)
ansatz = EfficientSU2(num_qubits=2, reps=1, entanglement='linear')
optimizer = SPSA(maxiter=80)
np.random.seed(5)
initial_point = np.random.random(ansatz.num_parameters)
def run_vqe(quantum_instance):
local_vqe = VQE(
ansatz=ansatz,
optimizer=optimizer,
initial_point=initial_point,
quantum_instance=quantum_instance,
)
local_vqe_groundstate_solver = GroundStateEigensolver(qubit_converter, local_vqe)
res = local_vqe_groundstate_solver.solve(es_problem)
print(f"Energy = {np.real(res.eigenenergies + res.nuclear_repulsion_energy)[0]}")
return res, local_vqe.get_optimal_circuit()
quantum_instance_sf1 = QuantumInstance(backend=sf1_backend, initial_layout=qubits)
res_sf1, opt_circ_sf1 = run_vqe(quantum_instance_sf1)
quantum_instance_sf2 = QuantumInstance(backend=sf2_backend, initial_layout=qubits)
res_sf2, opt_circ_sf2 = run_vqe(quantum_instance_sf2)
from qiskit import transpile
transpiled_circ = transpile(opt_circ_sf1, sf1_backend); transpiled_circ.draw(output="mpl")
transpiled_circ.calibrations.keys()
from qiskit.algorithms import NumPyMinimumEigensolver
np_solver = NumPyMinimumEigensolver()
np_groundstate_solver = GroundStateEigensolver(qubit_converter, np_solver)
np_result = np_groundstate_solver.solve(es_problem)
target_energy = np.real(np_result.eigenenergies + np_result.nuclear_repulsion_energy)[0]
print('Energy:', target_energy)
get_ek = lambda res: np.real(res.eigenenergies + res.nuclear_repulsion_energy)[0]
cs = [2, -1]
extrapolate_energy = cs[0] * get_ek(res_sf1) + cs[1] * get_ek(res_sf2)
print('Energy:', extrapolate_energy)
print(res_sf1)
print(res_sf2)
import pickle
with open("res_sf1.pk", "wb") as fp:
pickle.dump(res_sf1, fp)
with open("res_sf2.pk", "wb") as fp:
pickle.dump(res_sf2, fp)
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.wrapper import available_backends, get_backend
from qiskit.wrapper import execute as q_execute
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.h(q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
z = 0.995004165 + 1j * 0.099833417
z = z / abs(z)
u_error = np.array([[1, 0], [0, z]])
noise_params = {'U':
{'gate_time': 1,
'p_depol': 0.001,
'p_pauli': [0, 0, 0.01],
'U_error': u_error
}
}
config = {"noise_params": noise_params}
ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config)
ret = ret.result()
print(ret.get_counts())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='pulse_programming_in') as pulse_prog:
pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3)
pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4)
pulse_prog.draw()
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# 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-docstring,invalid-name,no-member,broad-except
# pylint: disable=no-else-return, attribute-defined-outside-init
# pylint: disable=import-error
from qiskit_experiments.library import StateTomography
import qiskit
class StateTomographyBench:
params = [2, 3, 4, 5]
param_names = ["n_qubits"]
version = "0.3.0"
timeout = 120.0
def setup(self, _):
self.qasm_backend = qiskit.BasicAer.get_backend("qasm_simulator")
def time_state_tomography_bell(self, n_qubits):
meas_qubits = [n_qubits - 2, n_qubits - 1]
qr_full = qiskit.QuantumRegister(n_qubits)
bell = qiskit.QuantumCircuit(qr_full)
bell.h(qr_full[meas_qubits[0]])
bell.cx(qr_full[meas_qubits[0]], qr_full[meas_qubits[1]])
qst_exp = StateTomography(bell, measurement_qubits=meas_qubits)
expdata = qst_exp.run(self.qasm_backend, shots=5000).block_for_results()
expdata.analysis_results("state")
expdata.analysis_results("state_fidelity")
def time_state_tomography_cat(self, n_qubits):
qr = qiskit.QuantumRegister(n_qubits, "qr")
circ = qiskit.QuantumCircuit(qr, name="cat")
circ.h(qr[0])
for i in range(1, n_qubits):
circ.cx(qr[0], qr[i])
qst_exp = StateTomography(circ)
expdata = qst_exp.run(self.qasm_backend, shots=5000).block_for_results()
expdata.analysis_results("state")
expdata.analysis_results("state_fidelity")
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
# 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('mpl')
from qiskit.quantum_info import Statevector
# Set the intial 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.visualization import array_to_latex
#Alternative way of representing in latex
array_to_latex(state)
state.draw('qsphere')
state.draw('hinton')
from qiskit.quantum_info import Operator
U = Operator(circ)
# Show the results
U.data
# 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.
# Here the meas has to be first and front=True (putting it before)
# as compose must put a smaller circuit into a larger one.
qc = meas.compose(circ, range(3), front=True)
#drawing the circuit
qc.draw('mpl')
# Adding the transpiler to reduce the circuit to QASM instructions
# supported by the backend
from qiskit import transpile
# Use AerSimulator
from qiskit_aer import AerSimulator
backend = AerSimulator()
# First we have to transpile the quantum circuit
# to the low-level QASM instructions used by the
# backend
qc_compiled = transpile(qc, backend)
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = backend.run(qc_compiled, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc_compiled)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/drobiu/quantum-project
|
drobiu
|
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.circuit.library.standard_gates import XGate, HGate
from operator import *
n = 3
N = 8 #2**n
index_colour_table = {}
colour_hash_map = {}
index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"}
colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'}
def database_oracle(index_colour_table, colour_hash_map):
circ_database = QuantumCircuit(n + n)
for i in range(N):
circ_data = QuantumCircuit(n)
idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
# qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0
# we therefore reverse the index string -> q0, ..., qn
data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour)
circ_database.append(data_gate, list(range(n+n)))
return circ_database
# drawing the database oracle circuit
print("Database Encoding")
database_oracle(index_colour_table, colour_hash_map).draw()
circ_data = QuantumCircuit(n)
m = 4
idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
print("Internal colour encoding for the colour green (as an example)");
circ_data.draw()
def oracle_grover(database, data_entry):
circ_grover = QuantumCircuit(n + n + 1)
circ_grover.append(database, list(range(n+n)))
target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target")
# control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()'
# The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
circ_grover.append(target_reflection_gate, list(range(n, n+n+1)))
circ_grover.append(database, list(range(n+n)))
return circ_grover
print("Grover Oracle (target example: orange)")
oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw()
def mcz_gate(num_qubits):
num_controls = num_qubits - 1
mcz_gate = QuantumCircuit(num_qubits)
target_mcz = QuantumCircuit(1)
target_mcz.z(0)
target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ")
mcz_gate.append(target_mcz, list(range(num_qubits)))
return mcz_gate.reverse_bits()
print("Multi-controlled Z (MCZ) Gate")
mcz_gate(n).decompose().draw()
def diffusion_operator(num_qubits):
circ_diffusion = QuantumCircuit(num_qubits)
qubits_list = list(range(num_qubits))
# Layer of H^n gates
circ_diffusion.h(qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of Multi-controlled Z (MCZ) Gate
circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of H^n gates
circ_diffusion.h(qubits_list)
return circ_diffusion
print("Diffusion Circuit")
diffusion_operator(n).draw()
# Putting it all together ... !!!
item = "green"
print("Searching for the index of the colour", item)
circuit = QuantumCircuit(n + n + 1, n)
circuit.x(n + n)
circuit.barrier()
circuit.h(list(range(n)))
circuit.h(n+n)
circuit.barrier()
unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator")
unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator")
M = countOf(index_colour_table.values(), item)
Q = int(np.pi * np.sqrt(N/M) / 4)
for i in range(Q):
circuit.append(unitary_oracle, list(range(n + n + 1)))
circuit.append(unitary_diffuser, list(range(n)))
circuit.barrier()
circuit.measure(list(range(n)), list(range(n)))
circuit.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
if M==1:
print("Index of the colour", item, "is the index with most probable outcome")
else:
print("Indices of the colour", item, "are the indices the most probable outcomes")
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
import sys
sys.path.append("../..")
from qiskit.quantum_info.random import random_unitary, random_clifford
from qiskit import QuantumCircuit
from clonk.utils.transpiler_passes.pass_manager_v2 import level_0_pass_manager
from clonk.backend_utils import FakeAllToAll
from clonk.utils.riswap_gates.riswap import RiSwapGate
from clonk.utils.transpiler_passes.weyl_decompose import RootiSwapWeylDecomposition
from qiskit.transpiler.passes import CountOps
from qiskit.transpiler import PassManager
from qiskit.circuit.library import CXGate
N = 2000
basis_gate = RiSwapGate(0.5)
pm0 = PassManager()
pm0.append(RootiSwapWeylDecomposition(basis_gate=basis_gate))
pm0.append(CountOps())
res = 0
for _ in range(N):
qc = QuantumCircuit(2)
qc.append(random_clifford(2), [0, 1])
# random_unitary(dim=4)
pm0.run(qc)
res += pm0.property_set["count_ops"]["riswap"]
print(res / N)
N = 2000
basis_gate = CXGate()
pm0 = PassManager()
pm0.append(RootiSwapWeylDecomposition(basis_gate=basis_gate))
pm0.append(CountOps())
res = 0
for _ in range(N):
qc = QuantumCircuit(2)
qc.append(random_clifford(2), [0, 1])
# random_unitary(dim=4)
pm0.run(qc)
res += (
pm0.property_set["count_ops"]["cx"]
if "cx" in pm0.property_set["count_ops"].keys()
else 0
)
print(res / N)
from qiskit.circuit.library import CPhaseGate
import numpy as np
basis_gate = CXGate()
pm0 = PassManager()
pm0.append(RootiSwapWeylDecomposition(basis_gate=basis_gate))
pm0.append(CountOps())
qc = QuantumCircuit(2)
qc.append(CPhaseGate(np.pi / 2), [0, 1])
# random_unitary(dim=4)
transp = pm0.run(qc)
transp.draw(output="mpl")
from qiskit import transpile
transp = transpile(qc, basis_gates=["rz", "sx", "cx"], optimization_level=3)
print(transp.draw(output="latex_source"))
from qiskit.circuit.library import CPhaseGate
import numpy as np
basis_gate = RiSwapGate(0.5)
pm0 = PassManager()
pm0.append(RootiSwapWeylDecomposition(basis_gate=basis_gate))
pm0.append(CountOps())
qc = QuantumCircuit(2)
qc.append(CPhaseGate(np.pi / 2), [0, 1])
# random_unitary(dim=4)
transp = pm0.run(qc)
print(transp.draw(output="latex"))
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### added y gate ###
qc.cx(0, 1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
### added h gate ###
qc.h(0)
return qc
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit.providers.ibmq.managed import IBMQJobManager
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-education')
from qiskit import QuantumCircuit, execute, transpile, Aer
from qiskit.extensions import UnitaryGate, Initialize
from qiskit.quantum_info import Statevector
from qiskit.compiler import assemble
from qiskit.tools.visualization import plot_bloch_vector
from qiskit.tools.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
from time import sleep
import sys
sys.path.append("..")
from scipy.stats import unitary_group
import matplotlib.pyplot as plt
%matplotlib inline
from Modules.changed_SPEA import bundled_SPEA_alternate
q = QuantumCircuit(2)
q.cp(2*np.pi*(1/4), 0, 1)
q.draw('mpl')
spe = bundled_SPEA_alternate(q, resolution=30, error=3, max_iters=10)
jakarta = provider.get_backend('ibmq_jakarta')
bogota = provider.get_backend('ibmq_bogota')
thetas = []
for k in range(5):
result = spe.get_eigen_pair(
backend=jakarta, progress=True, randomize=True)
print("Result is :", result)
thetas.append(result['theta'])
thetas
plt.title("Plot for returned Eigenvalues", fontsize=16)
plt.xlabel("Experiment number")
plt.ylabel("Eigenvalues")
plt.plot([0, 6], [0, 0], color='black')
plt.plot([0, 6], [1, 1], color='black')
plt.plot([0, 6], [0.25, 0.25], color='black')
plt.plot(list(range(5)), thetas, label='Estimates',
color='cyan', linewidth=2, marker='s')
plt.legend()
plt.grid()
|
https://github.com/kuehnste/QiskitTutorial
|
kuehnste
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.visualization import *
from qiskit.quantum_info import state_fidelity
# Magic function to render plots in the notebook after the cell executing the plot command
%matplotlib inline
qc = QuantumCircuit(3)
qc.h(0)
qc.cnot(0,1)
qc.cnot(1,2)
qc.measure_active()
qc.draw(output='mpl')
# Loading your IBM Q account
IBMQ.load_account()
provider = IBMQ.get_provider(group='open')
# List the existing quantum devices and their number of qubits
device_list = provider.backends(simulator=False)
for dev in device_list:
print(dev.name() + ': ' + str(dev.configuration().n_qubits) + ' qubits')
# We choose one device which has enough qubits for our experiment and send the job to the device
num_shots_hardware = 1024
hardware_backend = provider.get_backend('ibmq_quito')
job = execute(qc, backend=hardware_backend, shots=num_shots_hardware)
result = job.result()
counts = result.get_counts()
plot_histogram(counts, title='Run on hardware')
simulator_backend = Aer.get_backend('qasm_simulator')
counts_simulator = list()
num_shots_simulator = [1024, 8192]
for num_shots in num_shots_simulator:
job = execute(qc, backend=simulator_backend, shots=num_shots)
result_simulator = job.result()
counts_simulator.append(result_simulator.get_counts())
# We plot a comparison between the different results
plot_histogram([counts] + counts_simulator, title='Hardware vs. simulator',
legend=['hardware ' + str(num_shots_hardware) + ' shots',
'simulator ' + str(num_shots_simulator[0]) + ' shots',
'simulator ' + str(num_shots_simulator[1]) + ' shots'])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
state = Statevector(qc)
plot_bloch_multivector(state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# External imports
from pylab import cm
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
# Qiskit imports
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterVector
from qiskit.visualization import circuit_drawer
from qiskit.algorithms.optimizers import SPSA
from qiskit.circuit.library import ZZFeatureMap
from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel
from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer
from qiskit_machine_learning.algorithms import QSVC
from qiskit_machine_learning.datasets import ad_hoc_data
class QKTCallback:
"""Callback wrapper class."""
def __init__(self) -> None:
self._data = [[] for i in range(5)]
def callback(self, x0, x1=None, x2=None, x3=None, x4=None):
"""
Args:
x0: number of function evaluations
x1: the parameters
x2: the function value
x3: the stepsize
x4: whether the step was accepted
"""
self._data[0].append(x0)
self._data[1].append(x1)
self._data[2].append(x2)
self._data[3].append(x3)
self._data[4].append(x4)
def get_callback_data(self):
return self._data
def clear_callback_data(self):
self._data = [[] for i in range(5)]
adhoc_dimension = 2
X_train, y_train, X_test, y_test, adhoc_total = ad_hoc_data(
training_size=20,
test_size=5,
n=adhoc_dimension,
gap=0.3,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
plt.scatter(
X_train[np.where(y_train[:] == 0), 0],
X_train[np.where(y_train[:] == 0), 1],
marker="s",
facecolors="w",
edgecolors="b",
label="A train",
)
plt.scatter(
X_train[np.where(y_train[:] == 1), 0],
X_train[np.where(y_train[:] == 1), 1],
marker="o",
facecolors="w",
edgecolors="r",
label="B train",
)
plt.scatter(
X_test[np.where(y_test[:] == 0), 0],
X_test[np.where(y_test[:] == 0), 1],
marker="s",
facecolors="b",
edgecolors="w",
label="A test",
)
plt.scatter(
X_test[np.where(y_test[:] == 1), 0],
X_test[np.where(y_test[:] == 1), 1],
marker="o",
facecolors="r",
edgecolors="w",
label="B test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for classification")
plt.show()
# Create a rotational layer to train. We will rotate each qubit the same amount.
training_params = ParameterVector("θ", 1)
fm0 = QuantumCircuit(2)
fm0.ry(training_params[0], 0)
fm0.ry(training_params[0], 1)
# Use ZZFeatureMap to represent input data
fm1 = ZZFeatureMap(2)
# Create the feature map, composed of our two circuits
fm = fm0.compose(fm1)
print(circuit_drawer(fm))
print(f"Trainable parameters: {training_params}")
# Instantiate quantum kernel
quant_kernel = TrainableFidelityQuantumKernel(feature_map=fm, training_parameters=training_params)
# Set up the optimizer
cb_qkt = QKTCallback()
spsa_opt = SPSA(maxiter=10, callback=cb_qkt.callback, learning_rate=0.05, perturbation=0.05)
# Instantiate a quantum kernel trainer.
qkt = QuantumKernelTrainer(
quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[np.pi / 2]
)
# Train the kernel using QKT directly
qka_results = qkt.fit(X_train, y_train)
optimized_kernel = qka_results.quantum_kernel
print(qka_results)
# Use QSVC for classification
qsvc = QSVC(quantum_kernel=optimized_kernel)
# Fit the QSVC
qsvc.fit(X_train, y_train)
# Predict the labels
labels_test = qsvc.predict(X_test)
# Evalaute the test accuracy
accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test)
print(f"accuracy test: {accuracy_test}")
plot_data = cb_qkt.get_callback_data() # callback data
K = optimized_kernel.evaluate(X_train) # kernel matrix evaluated on the training samples
plt.rcParams["font.size"] = 20
fig, ax = plt.subplots(1, 2, figsize=(14, 5))
ax[0].plot([i + 1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c="k", marker="o")
ax[0].set_xlabel("Iterations")
ax[0].set_ylabel("Loss")
ax[1].imshow(K, cmap=cm.get_cmap("bwr", 20))
fig.tight_layout()
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
import numpy as np
from qiskit.circuit.random import random_circuit
from qiskit.circuit import Parameter
from qiskit import IBMQ
from qiskit.compiler import transpile
from qiskit.converters import circuit_to_dag
from qiskit.tools.visualization import dag_drawer
IBMQ.load_account() # Load account from disk
provider = IBMQ.get_provider(hub='ibm-q')
n = 3 #number of qubits
def superpos(qc,qr):
for q in qr:
qc.h(q)
qreg_q = QuantumRegister(n, 'q')
creg_c = ClassicalRegister(n, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
paras = [Parameter('p'+str(i)) for i in range(n)]
superpos(circuit,qreg_q)
for p in paras:
circuit.rz(p,int(p.name[1:]))
algorithm = random_circuit(n,n)
circuit += algorithm
superpos(circuit,qreg_q)
circuit.measure(qreg_q,creg_c)
circuit.draw(output='mpl')
circuit_fixed = circuit.bind_parameters({p : np.pi * np.random.uniform(0, 2) for p in paras})
# note : compilation before binding has a better runtime
# transpile the circuit for backend chip
circuit_transpiled = transpile(circuit, backend=provider.get_backend('ibmq_16_melbourne'), optimization_level=3)
print('gates = ', circuit_transpiled.count_ops())
print('depth = ', circuit_transpiled.depth())
# use appropriate optimization level
for opt_lvl in range(4):
circuit_transpiled = transpile(circuit, backend=provider.get_backend('ibmq_santiago'), optimization_level=opt_lvl)
print("optimization level ",opt_lvl)
print('gates = ', circuit_transpiled.count_ops())
print('depth = ', circuit_transpiled.depth())
circuit_transpiled.draw(output = 'mpl')
dag = circuit_to_dag(circuit)
dag_drawer(dag)
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
excited = Statevector.from_int(1, 2)
plot_bloch_multivector(excited.data)
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_armonk')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
qubit = 0
# The Rabi sweep will be at the given qubit frequency.
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz
# warning: this will change in a future release
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
from qiskit import pulse, assemble # This is where we access all of our Pulse features!
from qiskit.pulse import Play
from qiskit.pulse import pulse_lib # This Pulse module helps us build sampled pulses for common pulse shapes
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=[0])
# Rabi experiment parameters
# Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75
num_rabi_points = 50
drive_amp_min = 0
drive_amp_max = 0.75
drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points)
# drive waveforms mush be in units of 16
drive_sigma = 80 # in dt
drive_samples = 8*drive_sigma # in dt
# Build the Rabi experiments:
# A drive pulse at the qubit frequency, followed by a measurement,
# where we vary the drive amplitude each time.
rabi_schedules = []
for drive_amp in drive_amps:
rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp,
sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}")
this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}")
this_schedule += Play(rabi_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
this_schedule += measure << this_schedule.duration
rabi_schedules.append(this_schedule)
rabi_schedules[-1].draw(label=True, scaling=1.0)
# assemble the schedules into a Qobj
num_shots_per_point = 1024
rabi_experiment_program = assemble(rabi_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_point,
schedule_los=[{drive_chan: center_frequency_Hz}]
* num_rabi_points)
# RUN the job on a real device
#job = backend.run(rabi_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive result from previous run
job = backend.retrieve_job("5ef3bf17dc3044001186c011")
rabi_results = job.result()
import matplotlib.pyplot as plt
plt.style.use('dark_background')
scale_factor = 1e-14
# center data around 0
def baseline_remove(values):
return np.array(values) - np.mean(values)
rabi_values = []
for i in range(num_rabi_points):
# Get the results for `qubit` from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor)
rabi_values = np.real(baseline_remove(rabi_values))
plt.xlabel("Drive amp [a.u.]")
plt.ylabel("Measured signal [a.u.]")
plt.scatter(drive_amps, rabi_values, color='white') # plot real part of Rabi values
plt.show()
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
fit_params, y_fit = fit_function(drive_amps,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B),
[10, 0.1, 0.6, 0])
plt.scatter(drive_amps, rabi_values, color='white')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] # get period of rabi oscillation
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.axvline(drive_period, color='red', linestyle='--')
plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red'))
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
pi_amp = abs(drive_period / 2)
print(f"Pi Amplitude = {pi_amp}")
# Drive parameters
# The drive amplitude for pi/2 is simply half the amplitude of the pi pulse
drive_amp = pi_amp / 2
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_samples,
amp=drive_amp,
sigma=drive_sigma,
name='x90_pulse')
# Ramsey experiment parameters
time_max_us = 1.8
time_step_us = 0.025
times_us = np.arange(0.1, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
# create schedules for Ramsey experiment
ramsey_schedules = []
for delay in delay_times_dt:
this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us")
this_schedule += Play(x90_pulse, drive_chan)
this_schedule += Play(x90_pulse, drive_chan) << this_schedule.duration + int(delay)
this_schedule += measure << this_schedule.duration
ramsey_schedules.append(this_schedule)
ramsey_schedules[-1].draw(label=True, scaling=1.0)
# Execution settings
num_shots = 256
detuning_MHz = 2
ramsey_frequency = round(center_frequency_Hz + detuning_MHz * MHz, 6) # need ramsey freq in Hz
ramsey_program = assemble(ramsey_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots,
schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules)
)
# RUN the job on a real device
#job = backend.run(ramsey_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive job from previous run
job = backend.retrieve_job('5ef3ed3a84b1b70012374317')
ramsey_results = job.result()
ramsey_values = []
for i in range(len(times_us)):
ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor)
fit_params, y_fit = fit_function(times_us, np.real(ramsey_values),
lambda x, A, del_f_MHz, C, B: (
A * np.cos(2*np.pi*del_f_MHz*x - C) + B
),
[5, 1./0.4, 0, 0.25]
)
# Off-resonance component
_, del_f_MHz, _, _, = fit_params # freq is MHz since times in us
plt.scatter(times_us, np.real(ramsey_values), color='white')
plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz")
plt.xlim(0, np.max(times_us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.translators import from_docplex_mp
# Make a Docplex model
from docplex.mp.model import Model
mdl = Model("docplex model")
x = mdl.binary_var("x")
y = mdl.integer_var(lb=-1, ub=5, name="y")
mdl.minimize(x + 2 * y)
mdl.add_constraint(x - y == 3)
mdl.add_constraint((x + y) * (x - y) <= 1)
print(mdl.export_as_lp_string())
# load from a Docplex model
mod = from_docplex_mp(mdl)
print(type(mod))
print()
print(mod.prettyprint())
# make an empty problem
mod = QuadraticProgram("my problem")
print(mod.prettyprint())
# Add variables
mod.binary_var(name="x")
mod.integer_var(name="y", lowerbound=-1, upperbound=5)
mod.continuous_var(name="z", lowerbound=-1, upperbound=5)
print(mod.prettyprint())
# Add objective function using dictionaries
mod.minimize(constant=3, linear={"x": 1}, quadratic={("x", "y"): 2, ("z", "z"): -1})
print(mod.prettyprint())
# Add objective function using lists/arrays
mod.minimize(constant=3, linear=[1, 0, 0], quadratic=[[0, 1, 0], [1, 0, 0], [0, 0, -1]])
print(mod.prettyprint())
print("constant:\t\t\t", mod.objective.constant)
print("linear dict:\t\t\t", mod.objective.linear.to_dict())
print("linear array:\t\t\t", mod.objective.linear.to_array())
print("linear array as sparse matrix:\n", mod.objective.linear.coefficients, "\n")
print("quadratic dict w/ index:\t", mod.objective.quadratic.to_dict())
print("quadratic dict w/ name:\t\t", mod.objective.quadratic.to_dict(use_name=True))
print(
"symmetric quadratic dict w/ name:\t",
mod.objective.quadratic.to_dict(use_name=True, symmetric=True),
)
print("quadratic matrix:\n", mod.objective.quadratic.to_array(), "\n")
print("symmetric quadratic matrix:\n", mod.objective.quadratic.to_array(symmetric=True), "\n")
print("quadratic matrix as sparse matrix:\n", mod.objective.quadratic.coefficients)
# Add linear constraints
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="==", rhs=3, name="lin_eq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="<=", rhs=3, name="lin_leq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense=">=", rhs=3, name="lin_geq")
print(mod.prettyprint())
# Add quadratic constraints
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="==",
rhs=1,
name="quad_eq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="<=",
rhs=1,
name="quad_leq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense=">=",
rhs=1,
name="quad_geq",
)
print(mod.prettyprint())
lin_geq = mod.get_linear_constraint("lin_geq")
print("lin_geq:", lin_geq.linear.to_dict(use_name=True), lin_geq.sense, lin_geq.rhs)
quad_geq = mod.get_quadratic_constraint("quad_geq")
print(
"quad_geq:",
quad_geq.linear.to_dict(use_name=True),
quad_geq.quadratic.to_dict(use_name=True),
quad_geq.sense,
lin_geq.rhs,
)
# Remove constraints
mod.remove_linear_constraint("lin_eq")
mod.remove_quadratic_constraint("quad_leq")
print(mod.prettyprint())
sub = mod.substitute_variables(constants={"x": 0}, variables={"y": ("z", -1)})
print(sub.prettyprint())
sub = mod.substitute_variables(constants={"x": -1})
print(sub.status)
from qiskit_optimization import QiskitOptimizationError
try:
sub = mod.substitute_variables(constants={"x": -1}, variables={"y": ("x", 1)})
except QiskitOptimizationError as e:
print("Error: {}".format(e))
mod = QuadraticProgram()
mod.binary_var(name="e")
mod.binary_var(name="f")
mod.continuous_var(name="g")
mod.minimize(linear=[1, 2, 3])
print(mod.export_as_lp_string())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.draw('mpl')
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" sparse state preparation """
import numpy as np
import qiskit
from qiskit import QuantumCircuit
from qclib.gates.initialize_sparse import InitializeSparse
from .lowrank import LowRankInitialize
# pylint: disable=maybe-no-member
class PivotInitialize(InitializeSparse):
"""Pivot State Preparation arXiv:2006.00016"""
def __init__(self, params, label=None, opt_params=None):
self._get_num_qubits(params)
default_aux = False
if opt_params is None:
self.aux = default_aux
else:
if opt_params.get("aux") is None:
self.aux = default_aux
else:
self.aux = opt_params.get("aux")
self.non_zero = len(params)
self.register = qiskit.QuantumRegister(self.num_qubits, name="q")
self.index_differ = None
self.ctrl_state = None
if label is None:
self.label = "PivotSP"
super().__init__("PivotInitialize", self.num_qubits, params.items(), label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
target_size = np.log2(self.non_zero)
target_size = np.ceil(target_size)
target_size = int(target_size)
if self.aux:
anc, n_anci, pivot_circuit = self._circuit_with_ancilla(target_size)
else:
pivot_circuit = qiskit.QuantumCircuit(self.register)
next_state = self.params.copy()
index_nonzero = self._get_index_nz(self.num_qubits - target_size, next_state)
while index_nonzero is not None:
index_zero = self._get_index_zero(self.non_zero, next_state)
circ, next_state = self._pivoting(
index_nonzero, target_size, index_zero, next_state
)
pivot_circuit.compose(circ, pivot_circuit.qubits, inplace=True)
index_nonzero = self._get_index_nz(
self.num_qubits - target_size, next_state
)
dense_state = np.zeros(2 ** target_size, dtype=complex)
for key, value in next_state:
dense_state[int(key, 2)] = value
if self.non_zero <= 2:
initialize_circ = qiskit.QuantumCircuit(1)
LowRankInitialize.initialize(initialize_circ, dense_state)
else:
initialize_circ = QuantumCircuit(target_size)
LowRankInitialize.initialize(initialize_circ, dense_state)
if self.aux:
circuit = qiskit.QuantumCircuit(anc, self.register)
nun_aux = n_anci - 1
circuit.compose(
initialize_circ,
circuit.qubits[nun_aux : nun_aux + target_size],
inplace=True,
)
circuit.barrier()
circuit.compose(pivot_circuit.reverse_bits().reverse_ops(), inplace=True)
else:
circuit = qiskit.QuantumCircuit(self.num_qubits)
circuit.compose(initialize_circ, circuit.qubits[:target_size], inplace=True)
circuit.compose(
pivot_circuit.reverse_bits().reverse_ops(), circuit.qubits, inplace=True
)
return circuit
def _circuit_with_ancilla(self, target_size):
remain = list(range(self.num_qubits - target_size, self.num_qubits))
n_anci = len(remain)
anc = qiskit.QuantumRegister(n_anci - 1, name="anc")
pivot_circuit = qiskit.QuantumCircuit(anc, self.register)
return anc, n_anci, pivot_circuit
def _next_state(
self, remain, target_cx, index_zero, next_state
):
tab = {"0": "1", "1": "0"}
new_state = {}
for index, amp in next_state:
if index[self.index_differ] == self.ctrl_state:
n_index = ""
for k, value in enumerate(index):
if k in target_cx:
n_index = n_index + tab[value]
else:
n_index = n_index + value
else:
n_index = index
if n_index[remain[0] :] == index_zero[remain[0] :]:
n_index = (
n_index[:self.index_differ]
+ tab[index[self.index_differ]]
+ n_index[self.index_differ + 1 :]
)
new_state[n_index] = amp
return new_state.items()
def _pivoting(self, index_nonzero, target_size, index_zero, next_state):
"""pivot amplitudes of index_nonzero and self.index_zero"""
target = list(range(self.num_qubits - target_size))
remain = list(range(self.num_qubits - target_size, self.num_qubits))
memory = qiskit.QuantumRegister(self.num_qubits)
anc, circuit = self._initialize_circuit(memory, remain)
self.index_differ = 0
for k in target:
if index_nonzero[k] != index_zero[k]:
self.index_differ = k
break
target_cx = []
self.ctrl_state = index_nonzero[self.index_differ]
for k in target:
if self.index_differ != k and index_nonzero[k] != index_zero[k]:
circuit.cx(self.index_differ, k, ctrl_state=self.ctrl_state)
target_cx.append(k)
for k in remain:
if index_nonzero[k] != index_zero[k]:
circuit.cx(self.index_differ, k, ctrl_state=self.ctrl_state)
target_cx.append(k)
for k in remain:
if index_zero[k] == "0":
circuit.x(k)
if self.aux:
# apply mcx using mode v-chain
self._mcxvchain(circuit, memory, anc, remain, self.index_differ)
else:
circuit.mcx(remain, self.index_differ)
for k in remain:
if index_zero[k] == "0":
circuit.x(k)
next_state = self._next_state(
remain, target_cx, index_zero, next_state
)
return circuit, next_state
def _initialize_circuit(self, memory, remain):
if self.aux:
n_anci = len(remain)
anc = qiskit.QuantumRegister(n_anci - 1, name="anc")
circuit = qiskit.QuantumCircuit(memory, anc)
else:
circuit = qiskit.QuantumCircuit(memory)
anc = None
return anc, circuit
def _get_index_zero(self, non_zero, state):
index_zero = None
for k in range(2**non_zero):
index = f"{k:0{self.num_qubits}b}"
not_exists = sum(1 for v in state if v[0] == index) == 0
if not_exists:
index_zero = index
break
return index_zero
@staticmethod
def _get_index_nz(target_size, next_state):
index_nonzero = None
for index, _ in next_state:
if index[:target_size] != target_size * "0":
index_nonzero = index
break
return index_nonzero
@staticmethod
def _mcxvchain(circuit, memory, anc, lst_ctrl, tgt):
"""multi-controlled x gate with working qubits"""
circuit.rccx(memory[lst_ctrl[0]], memory[lst_ctrl[1]], anc[0])
for j in range(2, len(lst_ctrl)):
circuit.rccx(memory[lst_ctrl[j]], anc[j - 2], anc[j - 1])
circuit.cx(anc[len(lst_ctrl) - 2], tgt)
for j in reversed(range(2, len(lst_ctrl))):
circuit.rccx(memory[lst_ctrl[j]], anc[j - 2], anc[j - 1])
circuit.rccx(memory[lst_ctrl[0]], memory[lst_ctrl[1]], anc[0])
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
if qubits is None:
q_circuit.append(
PivotInitialize(state, opt_params=opt_params), q_circuit.qubits
)
else:
q_circuit.append(PivotInitialize(state, opt_params=opt_params), qubits)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Quantum Operation Mixin."""
from abc import ABC, abstractmethod
class Operation(ABC):
"""Quantum Operation Interface Class.
For objects that can be added to a :class:`~qiskit.circuit.QuantumCircuit`.
These objects include :class:`~qiskit.circuit.Gate`, :class:`~qiskit.circuit.Reset`,
:class:`~qiskit.circuit.Barrier`, :class:`~qiskit.circuit.Measure`,
and operators such as :class:`~qiskit.quantum_info.Clifford`.
The main purpose is to add an :class:`~qiskit.circuit.Operation` to a
:class:`~qiskit.circuit.QuantumCircuit` without synthesizing it before the transpilation.
Example:
Add a Clifford and a Toffoli gate to a QuantumCircuit.
.. plot::
:include-source:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford, random_clifford
qc = QuantumCircuit(3)
cliff = random_clifford(2)
qc.append(cliff, [0, 1])
qc.ccx(0, 1, 2)
qc.draw('mpl')
"""
__slots__ = ()
@property
@abstractmethod
def name(self):
"""Unique string identifier for operation type."""
raise NotImplementedError
@property
@abstractmethod
def num_qubits(self):
"""Number of qubits."""
raise NotImplementedError
@property
@abstractmethod
def num_clbits(self):
"""Number of classical bits."""
raise NotImplementedError
|
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/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
# import randrange for random choices
from random import randrange
n = 5
m = 4
values_of_qubits = [] # we keep a record of the qubits also in a list
qreg1 = QuantumRegister(n) # quantum register with n qubits
creg1 = ClassicalRegister(n) # classical register with n bits
mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuit with quantum and classical registers
# set each qubit to |1>
for i in range(n):
mycircuit1.x(qreg1[i]) # apply x-gate (NOT operator)
values_of_qubits.append(1) # the value of each qubit is set to 1
# randomly pick m pairs of qubits
for i in range(m):
controller_qubit = randrange(n)
target_qubit = randrange(n)
# controller and target qubits should be different
while controller_qubit == target_qubit: # if they are the same, we pick the target_qubit again
target_qubit = randrange(n)
# print our picked qubits
print("the indices of the controller and target qubits are",controller_qubit,target_qubit)
# apply cx-gate (CNOT operator)
mycircuit1.cx(qreg1[controller_qubit],qreg1[target_qubit])
# we also trace the results
if values_of_qubits[controller_qubit] == 1: # if the value of the controller qubit is 1,
values_of_qubits[target_qubit] = 1 - values_of_qubits[target_qubit] # then flips the value of the target qubit
# remark that 1-x gives the negation of x
# measure the quantum register
mycircuit1.measure(qreg1,creg1)
print("Everything looks fine, let's continue ...")
# draw the circuit
drawer(mycircuit1)
# re-execute this cell if you DO NOT see the circuit diagram
# execute the circuit 100 times in the local simulator
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit1)
# print the reverse of the outcome
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
# the value of the qubits should be as follows based on our own calculation
print(values_of_qubits)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
all_inputs=['00','01','10','11']
for input in all_inputs:
qreg2 = QuantumRegister(2) # quantum register with 2 qubits
creg2 = ClassicalRegister(2) # classical register with 2 bits
mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers
#initialize the inputs
if input[0]=='1':
mycircuit2.x(qreg2[0]) # set the state of the first qubit to |1>
if input[1]=='1':
mycircuit2.x(qreg2[1]) # set the state of the second qubit to |1>
# apply h-gate to both qubits
mycircuit2.h(qreg2[0])
mycircuit2.h(qreg2[1])
# apply cx(first-qubit,second-qubit)
mycircuit2.cx(qreg2[0],qreg2[1])
# apply h-gate to both qubits
mycircuit2.h(qreg2[0])
mycircuit2.h(qreg2[1])
# measure both qubits
mycircuit2.measure(qreg2,creg2)
# execute the circuit 100 times in the local simulator
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit2)
for outcome in counts: # print the reverse of the outcomes
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print("our input is",input,"and",reverse_outcome,"is observed",counts[outcome],"times")
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
all_inputs=['00','01','10','11']
for input in all_inputs:
qreg3 = QuantumRegister(2) # quantum register with 2 qubits
creg3 = ClassicalRegister(2) # classical register with 2 bits
mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers
#initialize the inputs
if input[0]=='1':
mycircuit3.x(qreg3[0]) # set the value of the first qubit to |1>
if input[1]=='1':
mycircuit3.x(qreg3[1]) # set the value of the second qubit to |1>
# apply cx(first-qubit,second-qubit)
mycircuit3.cx(qreg3[0],qreg3[1])
# apply cx(second-qubit,first-qubit)
mycircuit3.cx(qreg3[1],qreg3[0])
# apply cx(first-qubit,second-qubit)
mycircuit3.cx(qreg3[0],qreg3[1])
mycircuit3.measure(qreg3,creg3)
# execute the circuit 100 times in the local simulator
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit3)
for outcome in counts: # print the reverse of the outcomes
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print("our input is",input,"and",reverse_outcome,"is observed",counts[outcome],"times")
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import numpy as np
zero_ket = np.array([[1], [0]])
print("|0> ket:\n", zero_ket)
print("<0| bra:\n", zero_ket.T.conj())
zero_ket.T.conj() @ zero_ket
one_ket = np.array([[0], [1]])
zero_ket.T.conj() @ one_ket
zero_ket @ zero_ket.T.conj()
ψ = np.array([[1], [0]])/np.sqrt(2)
Π_0 = zero_ket @ zero_ket.T.conj()
ψ.T.conj() @ Π_0 @ ψ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram
from qiskit.primitives import BackendEstimator, BackendSampler
backend = AerSimulator()
sampler = BackendSampler(backend)
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.measure(q, c)
job = sampler.run(circuit, shots=100)
result = job.result()
counts = result.quasi_dists[0]
plot_histogram(counts)
ψ = np.array([[np.sqrt(2)/2], [np.sqrt(2)/2]])
Π_0 = zero_ket @ zero_ket.T.conj()
probability_0 = ψ.T.conj() @ Π_0 @ ψ
Π_0 @ ψ/np.sqrt(probability_0)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.measure(q[0], c[0])
circuit.measure(q[0], c[1])
job = sampler.run(circuit, shots=100)
result = job.result()
counts = result.quasi_dists[0]
plot_histogram(counts)
q = QuantumRegister(2)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.measure(q, c)
job = sampler.run(circuit, shots=100)
result = job.result()
counts = result.quasi_dists[0]
plot_histogram(counts)
q = QuantumRegister(2)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.cx(q[0], q[1])
circuit.measure(q, c)
job = sampler.run(circuit, shots=100)
result = job.result()
counts = result.quasi_dists[0]
plot_histogram(counts)
ψ = np.array([[1], [1]])/np.sqrt(2)
ρ = ψ @ ψ.T.conj()
Π_0 = zero_ket @ zero_ket.T.conj()
np.trace(Π_0 @ ρ)
probability_0 = np.trace(Π_0 @ ρ)
Π_0 @ ρ @ Π_0/probability_0
zero_ket = np.array([[1], [0]])
one_ket = np.array([[0], [1]])
ψ = (zero_ket + one_ket)/np.sqrt(2)
print("Density matrix of the equal superposition")
print(ψ @ ψ.T.conj())
print("Density matrix of the equally mixed state of |0><0| and |1><1|")
print((zero_ket @ zero_ket.T.conj()+one_ket @ one_ket.T.conj())/2)
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit.opflow.primitive_ops import PrimitiveOp
from qiskit.quantum_info import Pauli
primop_piXZ = PrimitiveOp(Pauli('-XZ'))
print(primop_piXZ)
print(type(primop_piXZ))
from qiskit.opflow import X, Z
pauli_piXZ = -(X ^ Z)
print(type(pauli_piXZ))
print(primop_piXZ.primitive
.equiv(pauli_piXZ.primitive))
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qc.h([0,1,2])
h_primop = PrimitiveOp(qc)
print(h_primop)
print(type(h_primop))
from qiskit.opflow import H
hgates = H^3
print(hgates)
print(type(hgates))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, BasicAer, IBMQ
# Creating registers
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circuits = []
# Creating the circuits
phase_vector = range(0,100)
for phase_index in phase_vector:
phase_shift = phase_index-50
phase = 2*np.pi*phase_shift/50
circuit_name = "phase_gate_%d"%phase_index
qc_phase_gate = QuantumCircuit(qr, cr, name=circuit_name)
qc_phase_gate.h(qr)
qc_phase_gate.u1(phase, qr)
qc_phase_gate.h(qr)
qc_phase_gate.measure(qr[0], cr[0])
circuits.append(qc_phase_gate)
# Visualising one of the circuits as an example
circuits[25].draw(output='mpl')
# To run using qasm simulator
backend = BasicAer.get_backend('qasm_simulator')
# the number of shots in the experiment
shots = 1024
result = execute(circuits, backend=backend, shots=shots).result()
probz = []
phase_value = []
for phase_index in phase_vector:
phase_shift = phase_index - 50
phase_value.append(2*phase_shift/50)
if '0' in result.get_counts(circuits[phase_index]):
probz.append(2*result.get_counts(circuits[phase_index]).get('0')/shots-1)
else:
probz.append(-1)
plt.plot(phase_value, probz, 'b',0.25,1/np.sqrt(2),'ro',0.5,0,'ko',1,-1,'go',-0.25,1/np.sqrt(2),'rx',-0.5,0,'kx',-1,-1,'gx')
plt.xlabel('Phase value (Pi)')
plt.ylabel('Eigenvalue of X')
plt.show()
# Creating registers
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circuits = []
# Creating the circuits
phase_vector = range(0,100)
for phase_index in phase_vector:
phase_shift = phase_index-50
phase = 2*np.pi*phase_shift/50
circuit_name = "phase_gate_%d"%phase_index
qc_phase_gate = QuantumCircuit(qr, cr, name=circuit_name)
qc_phase_gate.u3(phase,0,np.pi, qr)
qc_phase_gate.measure(qr[0], cr[0])
circuits.append(qc_phase_gate)
# Visualising one of the circuits as an example
circuits[75].draw(output='mpl')
# To run of qasm simulator
backend = BasicAer.get_backend('qasm_simulator')
# the number of shots in the experiment
shots = 1024
result = execute(circuits, backend=backend, shots=shots).result()
probz = []
phase_value = []
for phase_index in phase_vector:
phase_shift = phase_index - 50
phase_value.append(2*phase_shift/50)
if '0' in result.get_counts(circuits[phase_index]):
probz.append(2*result.get_counts(circuits[phase_index]).get('0')/shots-1)
else:
probz.append(-1)
plt.plot(phase_value, probz, 'b',0.5,0,'ko',1,-1,'go',-0.5,0,'kx',-1,-1,'gx')
plt.xlabel('Phase value (Pi)')
plt.ylabel('Eigenvalue of Z')
plt.show()
|
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/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Functions used for the analysis of randomized benchmarking results.
"""
from scipy.optimize import curve_fit
import numpy as np
from qiskit import QiskitError
from ..tomography import marginal_counts
from ...characterization.fitters import build_counts_dict_from_list
try:
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
class RBFitter:
"""
Class for fitters for randomized benchmarking
"""
def __init__(self, backend_result, cliff_lengths,
rb_pattern=None):
"""
Args:
backend_result: list of results (qiskit.Result).
cliff_lengths: the Clifford lengths, 2D list i x j where i is the
number of patterns, j is the number of cliffords lengths
rb_pattern: the pattern for the rb sequences.
"""
if rb_pattern is None:
rb_pattern = [[0]]
self._cliff_lengths = cliff_lengths
self._rb_pattern = rb_pattern
self._raw_data = []
self._ydata = []
self._fit = []
self._nseeds = 0
self._result_list = []
self.add_data(backend_result)
@property
def raw_data(self):
"""Return raw data."""
return self._raw_data
@property
def cliff_lengths(self):
"""Return clifford lengths."""
return self.cliff_lengths
@property
def ydata(self):
"""Return ydata (means and std devs)."""
return self._ydata
@property
def fit(self):
"""Return fit."""
return self._fit
@property
def seeds(self):
"""Return the number of loaded seeds."""
return self._nseeds
@property
def results(self):
"""Return all the results."""
return self._result_list
def add_data(self, new_backend_result, rerun_fit=True):
"""
Add a new result. Re calculate the raw data, means and
fit.
Args:
new_backend_result: list of rb results
rerun_fit: re caculate the means and fit the result
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
if new_backend_result is None:
return
if not isinstance(new_backend_result, list):
new_backend_result = [new_backend_result]
for result in new_backend_result:
self._result_list.append(result)
# update the number of seeds *if* new ones
# added. Note, no checking if we've done all the
# cliffords
for rbcirc in result.results:
nseeds_circ = int(rbcirc.header.name.split('_')[-1])
if (nseeds_circ+1) > self._nseeds:
self._nseeds = nseeds_circ+1
for result in self._result_list:
if not len(result.results) == len(self._cliff_lengths[0]):
raise ValueError(
"The number of clifford lengths must match the number of "
"results")
if rerun_fit:
self.calc_data()
self.calc_statistics()
self.fit_data()
@staticmethod
def _rb_fit_fun(x, a, alpha, b):
"""Function used to fit rb."""
# pylint: disable=invalid-name
return a * alpha ** x + b
def calc_data(self):
"""
Retrieve probabilities of success from execution results. Outputs
results into an internal variable _raw_data which is a 3-dimensional
list, where item (i,j,k) is the probability to measure the ground state
for the set of qubits in pattern "i" for seed no. j and vector length
self._cliff_lengths[i][k].
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
circ_counts = {}
circ_shots = {}
for seedidx in range(self._nseeds):
for circ, _ in enumerate(self._cliff_lengths[0]):
circ_name = 'rb_length_%d_seed_%d' % (circ, seedidx)
count_list = []
for result in self._result_list:
try:
count_list.append(result.get_counts(circ_name))
except (QiskitError, KeyError):
pass
circ_counts[circ_name] = \
build_counts_dict_from_list(count_list)
circ_shots[circ_name] = sum(circ_counts[circ_name].values())
self._raw_data = []
startind = 0
for patt_ind in range(len(self._rb_pattern)):
string_of_0s = ''
string_of_0s = string_of_0s.zfill(len(self._rb_pattern[patt_ind]))
self._raw_data.append([])
endind = startind+len(self._rb_pattern[patt_ind])
for i in range(self._nseeds):
self._raw_data[-1].append([])
for k, _ in enumerate(self._cliff_lengths[patt_ind]):
circ_name = 'rb_length_%d_seed_%d' % (k, i)
counts_subspace = marginal_counts(
circ_counts[circ_name],
np.arange(startind, endind))
self._raw_data[-1][i].append(
counts_subspace.get(string_of_0s, 0)
/ circ_shots[circ_name])
startind += (endind)
def calc_statistics(self):
"""
Extract averages and std dev from the raw data (self._raw_data).
Assumes that self._calc_data has been run. Output into internal
_ydata variable:
ydata is a list of dictionaries (length number of patterns).
Dictionary ydata[i]:
ydata[i]['mean'] is a numpy_array of length n;
entry j of this array contains the mean probability of
success over seeds, for vector length
self._cliff_lengths[i][j].
And ydata[i]['std'] is a numpy_array of length n;
entry j of this array contains the std
of the probability of success over seeds,
for vector length self._cliff_lengths[i][j].
"""
self._ydata = []
for patt_ind in range(len(self._rb_pattern)):
self._ydata.append({})
self._ydata[-1]['mean'] = np.mean(self._raw_data[patt_ind], 0)
if len(self._raw_data[patt_ind]) == 1: # 1 seed
self._ydata[-1]['std'] = None
else:
self._ydata[-1]['std'] = np.std(self._raw_data[patt_ind], 0)
def fit_data(self):
"""
Fit the RB results to an exponential curve.
Fit each of the patterns
Puts the results into a list of fit dictionaries:
where each dictionary corresponds to a pattern and has fields:
'params' - three parameters of rb_fit_fun. The middle one is the
exponent.
'err' - the error limits of the parameters.
'epc' - error per Clifford
"""
self._fit = []
for patt_ind, (lens, qubits) in enumerate(zip(self._cliff_lengths,
self._rb_pattern)):
# if at least one of the std values is zero, then sigma is replaced
# by None
if not self._ydata[patt_ind]['std'] is None:
sigma = self._ydata[patt_ind]['std'].copy()
if len(sigma) - np.count_nonzero(sigma) > 0:
sigma = None
else:
sigma = None
params, pcov = curve_fit(self._rb_fit_fun, lens,
self._ydata[patt_ind]['mean'],
sigma=sigma,
p0=(1.0, 0.95, 0.0),
bounds=([-2, 0, -2], [2, 1, 2]))
alpha = params[1] # exponent
params_err = np.sqrt(np.diag(pcov))
alpha_err = params_err[1]
nrb = 2 ** len(qubits)
epc = (nrb-1)/nrb*(1-alpha)
epc_err = epc*alpha_err/alpha
self._fit.append({'params': params, 'params_err': params_err,
'epc': epc, 'epc_err': epc_err})
def plot_rb_data(self, pattern_index=0, ax=None,
add_label=True, show_plt=True):
"""
Plot randomized benchmarking data of a single pattern.
Args:
pattern_index: which RB pattern to plot
ax (Axes or None): plot axis (if passed in).
add_label (bool): Add an EPC label
show_plt (bool): display the plot.
Raises:
ImportError: If matplotlib is not installed.
"""
fit_function = self._rb_fit_fun
if not HAS_MATPLOTLIB:
raise ImportError('The function plot_rb_data needs matplotlib. '
'Run "pip install matplotlib" before.')
if ax is None:
plt.figure()
ax = plt.gca()
xdata = self._cliff_lengths[pattern_index]
# Plot the result for each sequence
for one_seed_data in self._raw_data[pattern_index]:
ax.plot(xdata, one_seed_data, color='gray', linestyle='none',
marker='x')
# Plot the mean with error bars
ax.errorbar(xdata, self._ydata[pattern_index]['mean'],
yerr=self._ydata[pattern_index]['std'],
color='r', linestyle='--', linewidth=3)
# Plot the fit
ax.plot(xdata,
fit_function(xdata, *self._fit[pattern_index]['params']),
color='blue', linestyle='-', linewidth=2)
ax.tick_params(labelsize=14)
ax.set_xlabel('Clifford Length', fontsize=16)
ax.set_ylabel('Ground State Population', fontsize=16)
ax.grid(True)
if add_label:
bbox_props = dict(boxstyle="round,pad=0.3",
fc="white", ec="black", lw=2)
ax.text(0.6, 0.9,
"alpha: %.3f(%.1e) EPC: %.3e(%.1e)" %
(self._fit[pattern_index]['params'][1],
self._fit[pattern_index]['params_err'][1],
self._fit[pattern_index]['epc'],
self._fit[pattern_index]['epc_err']),
ha="center", va="center", size=14,
bbox=bbox_props, transform=ax.transAxes)
if show_plt:
plt.show()
|
https://github.com/lynnlangit/learning-quantum
|
lynnlangit
|
import numpy as np
from qiskit.algorithms.linear_solvers.numpy_linear_solver import NumPyLinearSolver
from qiskit.algorithms.linear_solvers.hhl import HHL
matrix = np.array([[1, -1/3], [-1/3, 1]])
vector = np.array([1, 0])
naive_hhl_solution = HHL().solve(matrix, vector)
classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector))
from qiskit.algorithms.linear_solvers.matrices.tridiagonal_toeplitz import TridiagonalToeplitz
tridi_matrix = TridiagonalToeplitz(1, 1, -1 / 3)
tridi_solution = HHL().solve(tridi_matrix, vector)
print('classical state:', classical_solution.state)
print('naive state:')
print(naive_hhl_solution.state)
print('tridiagonal state:')
print(tridi_solution.state)
print('classical Euclidean norm:', classical_solution.euclidean_norm)
print('naive Euclidean norm:', naive_hhl_solution.euclidean_norm)
print('tridiagonal Euclidean norm:', tridi_solution.euclidean_norm)
from qiskit.quantum_info import Statevector
naive_sv = Statevector(naive_hhl_solution.state).data
tridi_sv = Statevector(tridi_solution.state).data
# Extract the right vector components. 1000 corresponds to the index 8 and 1001 corresponds to the index 9
naive_full_vector = np.array([naive_sv[8], naive_sv[9]])
tridi_full_vector = np.array([tridi_sv[8], tridi_sv[9]])
print('naive raw solution vector:', naive_full_vector)
print('tridi raw solution vector:', tridi_full_vector)
naive_full_vector = np.real(naive_full_vector)
tridi_full_vector = np.real(tridi_full_vector)
print('full naive solution vector:', naive_hhl_solution.euclidean_norm*naive_full_vector/np.linalg.norm(naive_full_vector))
print('full tridi solution vector:', tridi_solution.euclidean_norm*tridi_full_vector/np.linalg.norm(tridi_full_vector))
print('classical state:', classical_solution.state)
from scipy.sparse import diags
num_qubits = 2
matrix_size = 2 ** num_qubits
# entries of the tridiagonal Toeplitz symmetric matrix
a = 1
b = -1/3
matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray()
vector = np.array([1] + [0]*(matrix_size - 1))
# run the algorithms
classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector))
naive_hhl_solution = HHL().solve(matrix, vector)
tridi_matrix = TridiagonalToeplitz(num_qubits, a, b)
tridi_solution = HHL().solve(tridi_matrix, vector)
print('classical euclidean norm:', classical_solution.euclidean_norm)
print('naive euclidean norm:', naive_hhl_solution.euclidean_norm)
print('tridiagonal euclidean norm:', tridi_solution.euclidean_norm)
from qiskit import transpile
num_qubits = list(range(1,5))
a = 1
b = -1/3
i=1
# calculate the circuit depths for different number of qubits to compare the use of resources
naive_depths = []
tridi_depths = []
for nb in num_qubits:
matrix = diags([b, a, b], [-1, 0, 1], shape=(2**nb, 2**nb)).toarray()
vector = np.array([1] + [0]*(2**nb -1))
naive_hhl_solution = HHL().solve(matrix, vector)
tridi_matrix = TridiagonalToeplitz(nb, a, b)
tridi_solution = HHL().solve(tridi_matrix, vector)
naive_qc = transpile(naive_hhl_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx'])
tridi_qc = transpile(tridi_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx'])
naive_depths.append(naive_qc.depth())
tridi_depths.append(tridi_qc.depth())
i +=1
sizes = [str(2**nb)+"x"+str(2**nb) for nb in num_qubits]
columns = ['size of the system', 'quantum_solution depth', 'tridi_solution depth']
data = np.array([sizes, naive_depths, tridi_depths])
row_format ="{:>23}" * (len(columns) + 2)
for team, row in zip(columns, data):
print(row_format.format(team, *row))
print('excess:', [naive_depths[i] - tridi_depths[i] for i in range(0, len(naive_depths))])
from qiskit.algorithms.linear_solvers.observables import AbsoluteAverage, MatrixFunctional
num_qubits = 1
matrix_size = 2 ** num_qubits
# entries of the tridiagonal Toeplitz symmetric matrix
a = 1
b = -1/3
matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray()
vector = np.array([1] + [0]*(matrix_size - 1))
tridi_matrix = TridiagonalToeplitz(1, a, b)
average_solution = HHL().solve(tridi_matrix, vector, AbsoluteAverage())
classical_average = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), AbsoluteAverage())
print('quantum average:', average_solution.observable)
print('classical average:', classical_average.observable)
print('quantum circuit results:', average_solution.circuit_results)
observable = MatrixFunctional(1, 1 / 2)
functional_solution = HHL().solve(tridi_matrix, vector, observable)
classical_functional = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), observable)
print('quantum functional:', functional_solution.observable)
print('classical functional:', classical_functional.observable)
print('quantum circuit results:', functional_solution.circuit_results)
from qiskit import BasicAer
backend = BasicAer.get_backend('qasm_simulator')
hhl = HHL(1e-3, quantum_instance=backend)
accurate_solution = hhl.solve(matrix, vector)
classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector))
print(accurate_solution.euclidean_norm)
print(classical_solution.euclidean_norm)
from qiskit import QuantumRegister, QuantumCircuit
import numpy as np
t = 2 # This is not optimal; As an exercise, set this to the
# value that will get the best results. See section 8 for solution.
nqubits = 4 # Total number of qubits
nb = 1 # Number of qubits representing the solution
nl = 2 # Number of qubits representing the eigenvalues
theta = 0 # Angle defining |b>
a = 1 # Matrix diagonal
b = -1/3 # Matrix off-diagonal
# Initialize the quantum and classical registers
qr = QuantumRegister(nqubits)
# Create a Quantum Circuit
qc = QuantumCircuit(qr)
qrb = qr[0:nb]
qrl = qr[nb:nb+nl]
qra = qr[nb+nl:nb+nl+1]
# State preparation.
qc.ry(2*theta, qrb[0])
# QPE with e^{iAt}
for qu in qrl:
qc.h(qu)
qc.p(a*t, qrl[0])
qc.p(a*t*2, qrl[1])
qc.u(b*t, -np.pi/2, np.pi/2, qrb[0])
# Controlled e^{iAt} on \lambda_{1}:
params=b*t
qc.p(np.pi/2,qrb[0])
qc.cx(qrl[0],qrb[0])
qc.ry(params,qrb[0])
qc.cx(qrl[0],qrb[0])
qc.ry(-params,qrb[0])
qc.p(3*np.pi/2,qrb[0])
# Controlled e^{2iAt} on \lambda_{2}:
params = b*t*2
qc.p(np.pi/2,qrb[0])
qc.cx(qrl[1],qrb[0])
qc.ry(params,qrb[0])
qc.cx(qrl[1],qrb[0])
qc.ry(-params,qrb[0])
qc.p(3*np.pi/2,qrb[0])
# Inverse QFT
qc.h(qrl[1])
qc.rz(-np.pi/4,qrl[1])
qc.cx(qrl[0],qrl[1])
qc.rz(np.pi/4,qrl[1])
qc.cx(qrl[0],qrl[1])
qc.rz(-np.pi/4,qrl[0])
qc.h(qrl[0])
# Eigenvalue rotation
t1=(-np.pi +np.pi/3 - 2*np.arcsin(1/3))/4
t2=(-np.pi -np.pi/3 + 2*np.arcsin(1/3))/4
t3=(np.pi -np.pi/3 - 2*np.arcsin(1/3))/4
t4=(np.pi +np.pi/3 + 2*np.arcsin(1/3))/4
qc.cx(qrl[1],qra[0])
qc.ry(t1,qra[0])
qc.cx(qrl[0],qra[0])
qc.ry(t2,qra[0])
qc.cx(qrl[1],qra[0])
qc.ry(t3,qra[0])
qc.cx(qrl[0],qra[0])
qc.ry(t4,qra[0])
qc.measure_all()
print("Depth: %i" % qc.depth())
print("CNOTS: %i" % qc.count_ops()['cx'])
qc.draw(fold=-1)
from qiskit import BasicAer, ClassicalRegister, IBMQ
from qiskit.compiler import transpile
from qiskit.ignis.mitigation.measurement import (complete_meas_cal, # Measurement error mitigation functions
CompleteMeasFitter,
MeasurementFilter)
provider = IBMQ.load_account()
backend = provider.get_backend('ibmqx2') # calibrate using real hardware
layout = [2,3,0,4]
chip_qubits = 5
# Transpiled circuit for the real hardware
qc_qa_cx = transpile(qc, backend=backend, initial_layout=layout)
meas_cals, state_labels = complete_meas_cal(qubit_list=layout, qr=QuantumRegister(chip_qubits))
qcs = meas_cals + [qc_qa_cx]
job = backend.run(qcs, shots=10)
|
https://github.com/Dpbm/scientific-research-1-quantum-oracles
|
Dpbm
|
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit import QuantumCircuit, transpile, assemble, Aer
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(3)
qc.h(2)
qc.cp(pi/2, 1, 2)
qc.cp(pi/4, 0, 2)
qc.h(1)
qc.cp(pi/2, 0, 1)
qc.h(0)
qc.swap(0, 2)
qc.draw()
def qft_rotations(circuit, n):
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
qft_rotations(circuit, n)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
qc = QuantumCircuit(4)
qft(qc,4)
qc.draw()
# Create the circuit
qc = QuantumCircuit(3)
# Encode the state 5 (101 in binary)
qc.x(0)
qc.x(2)
qc.draw()
sim = Aer.get_backend("aer_simulator")
qc_init = qc.copy()
qc_init.save_statevector()
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
qft(qc, 3)
qc.draw()
qc.save_statevector()
statevector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(statevector)
|
https://github.com/samuraigab/Quantum-Basic-Algorithms
|
samuraigab
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ,execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
# Criando um circuito de n qubits
n = 4
qc = QuantumCircuit(n)
#Desenhando o circuito
qc.draw()
backend = Aer.get_backend('statevector_simulator')
results = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(qc)
import matplotlib.pyplot as plt
from IPython.display import display, Latex
n = 1
qc = QuantumCircuit(n)
print('Com probabilidade máxima (igual 1) o qubit se econtra no estado 0.')
backend = Aer.get_backend('statevector_simulator')
results = execute(qc,backend).result().get_counts()
display(plot_histogram(results, figsize = (2,2)))
state = execute(qc,backend).result().get_statevector()
plot_bloch_multivector(state)
# Colocando em superposição
qc = QuantumCircuit(n)
qc.h(0)
display(qc.draw())
state = execute(qc,backend).result().get_statevector()
plot_bloch_multivector(state)
# print('--- O resultado abaixo mostra que temos um qubit em superposição.')
# print("--- Apesar termos 50% de chance de medir o estado 0 ou 1, só conseguimos extrair um bit \
# de informação do sistema. O número de bits (clássicos) de informação extraídos \
# do sistema será, no máximo, igual ao número qubits")
# print("--- O nosso resultado será 0 ou 1")
qc = QuantumCircuit(n,1)
qc.h(0)
qc.measure(0,0)
backend = Aer.get_backend('qasm_simulator')
results = execute(qc,backend, shots=10000).result().get_counts()
plot_histogram(results, figsize=(2,2))
n = 4
qc = QuantumCircuit(n)
qc.id(0) # nao faz nada no qubit 0
qc.x(1) # flipa o qubit 1 --- 0->1
qc.h(2) # coloca o qubit 2 em superposição: |0> = |0> + |1>
qc.x(3) # flipa o qubit 3 --- |0> -> |1>
qc.h(3) # coloca o qubit 3 em superposção: |1> = |0> - |1>
qc.draw()
print("--------- Mostra a posição de cada um dos qubits na esfera de Bloch ---------")
backend = Aer.get_backend('statevector_simulator')
results = execute(qc,backend).result().get_statevector()
plot_bloch_multivector(results)
n = 1
qc = QuantumCircuit(n,1)
qc.h(0)
qc.measure(0,0)
display(qc.draw())
# |0> ---> H ----->|0> + |1>
print('----------O resultado da medida de um qubit em superposição.---------\n')
shots = 10000
backend = Aer.get_backend('qasm_simulator')
results = execute(qc,backend, shots=shots).result().get_counts()
display(plot_histogram(results,figsize = (3,3)))
state0 = results['0']
state1 = results['1']
print(f'Ao rodar {shots} vezes experimento, o resultado 0 apareceu {state0} \
vezes e resultado 1 ocorreu {state1} vezes')
print("\n\n------ Visualização da medida do experimento rodando quatro vezes ------\n")
for i in range(4):
results = execute(qc,backend, shots = 1).result().get_counts()
display(plot_histogram(results, figsize=(2,2)))
# Run the code in this cell to see the widget
from qiskit_textbook.widgets import gate_demo
gate_demo(gates='pauli+h+rz')
n = 2
qc = QuantumCircuit(n)
qc.h(0)
qc.h(1)
# qc.measure(range(n), range(n))
display(qc.draw())
#|0> -> H -> |0> + |1>
#|00> -> H|0>*Id|0> = (|0> + |1>)(|0>) = (|00> + |10>) Estado nao emaranhado
backend = Aer.get_backend('statevector_simulator')
results = execute(qc,backend).result().get_counts()
plot_histogram(results, figsize = (3,3))
n = 2
qc = QuantumCircuit(n)
qc.h(0)
qc.cx(0,1)
# qc.measure(0,0)
# qc.measure(1,1)
qc.draw()
backend = Aer.get_backend('statevector_simulator')
results = execute(qc,backend).result().get_counts()
plot_histogram(results, figsize = (3,3))
#|0> -> H -> |0> + |1>
#|00> -> H|0>*Id|0> = (|0> + |1>)(|0>) = (|00> + |10>) aplicar CNOT (|00> + |11>) - Estado Emaranhado
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
p = 0.2
import numpy as np
from qiskit.circuit import QuantumCircuit
class BernoulliA(QuantumCircuit):
"""A circuit representing the Bernoulli A operator."""
def __init__(self, probability):
super().__init__(1) # circuit on 1 qubit
theta_p = 2 * np.arcsin(np.sqrt(probability))
self.ry(theta_p, 0)
class BernoulliQ(QuantumCircuit):
"""A circuit representing the Bernoulli Q operator."""
def __init__(self, probability):
super().__init__(1) # circuit on 1 qubit
self._theta_p = 2 * np.arcsin(np.sqrt(probability))
self.ry(2 * self._theta_p, 0)
def power(self, k):
# implement the efficient power of Q
q_k = QuantumCircuit(1)
q_k.ry(2 * k * self._theta_p, 0)
return q_k
A = BernoulliA(p)
Q = BernoulliQ(p)
from qiskit.algorithms import EstimationProblem
problem = EstimationProblem(
state_preparation=A, # A operator
grover_operator=Q, # Q operator
objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0
)
from qiskit.primitives import Sampler
sampler = Sampler()
from qiskit.algorithms import AmplitudeEstimation
ae = AmplitudeEstimation(
num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy
sampler=sampler,
)
ae_result = ae.estimate(problem)
print(ae_result.estimation)
import matplotlib.pyplot as plt
# plot estimated values
gridpoints = list(ae_result.samples.keys())
probabilities = list(ae_result.samples.values())
plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities))
plt.axvline(p, color="r", ls="--")
plt.xticks(size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title("Estimated Values", size=15)
plt.ylabel("Probability", size=15)
plt.xlabel(r"Amplitude $a$", size=15)
plt.ylim((0, 1))
plt.grid()
plt.show()
print("Interpolated MLE estimator:", ae_result.mle)
ae_circuit = ae.construct_circuit(problem)
ae_circuit.decompose().draw(
"mpl", style="iqx"
) # decompose 1 level: exposes the Phase estimation circuit!
from qiskit import transpile
basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"]
transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx")
from qiskit.algorithms import IterativeAmplitudeEstimation
iae = IterativeAmplitudeEstimation(
epsilon_target=0.01, # target accuracy
alpha=0.05, # width of the confidence interval
sampler=sampler,
)
iae_result = iae.estimate(problem)
print("Estimate:", iae_result.estimation)
iae_circuit = iae.construct_circuit(problem, k=3)
iae_circuit.draw("mpl", style="iqx")
from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation
mlae = MaximumLikelihoodAmplitudeEstimation(
evaluation_schedule=3, # log2 of the maximal Grover power
sampler=sampler,
)
mlae_result = mlae.estimate(problem)
print("Estimate:", mlae_result.estimation)
from qiskit.algorithms import FasterAmplitudeEstimation
fae = FasterAmplitudeEstimation(
delta=0.01, # target accuracy
maxiter=3, # determines the maximal power of the Grover operator
sampler=sampler,
)
fae_result = fae.estimate(problem)
print("Estimate:", fae_result.estimation)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from math import pi
import numpy as np
import rustworkx as rx
from qiskit_nature.second_q.hamiltonians.lattices import (
BoundaryCondition,
HyperCubicLattice,
Lattice,
LatticeDrawStyle,
LineLattice,
SquareLattice,
TriangularLattice,
)
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
num_nodes = 11
boundary_condition = BoundaryCondition.OPEN
line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition)
line_lattice.draw()
num_nodes = 11
boundary_condition = BoundaryCondition.PERIODIC
line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition)
line_lattice.draw()
line_lattice.draw_without_boundary()
num_nodes = 11
boundary_condition = BoundaryCondition.PERIODIC
edge_parameter = 1.0 + 1.0j
onsite_parameter = 1.0
line_lattice = LineLattice(
num_nodes=num_nodes,
edge_parameter=edge_parameter,
onsite_parameter=onsite_parameter,
boundary_condition=boundary_condition,
)
set(line_lattice.graph.weighted_edge_list())
line_lattice.to_adjacency_matrix()
line_lattice.to_adjacency_matrix(weighted=True)
rows = 5
cols = 4
boundary_condition = BoundaryCondition.OPEN
square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition)
square_lattice.draw()
rows = 5
cols = 4
boundary_condition = (
BoundaryCondition.OPEN,
BoundaryCondition.PERIODIC,
) # open in the x-direction, periodic in the y-direction
square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition)
square_lattice.draw()
rows = 5
cols = 4
edge_parameter = (1.0, 1.0 + 1.0j)
boundary_condition = (
BoundaryCondition.OPEN,
BoundaryCondition.PERIODIC,
) # open in the x-direction, periodic in the y-direction
onsite_parameter = 1.0
square_lattice = SquareLattice(
rows=rows,
cols=cols,
edge_parameter=edge_parameter,
onsite_parameter=onsite_parameter,
boundary_condition=boundary_condition,
)
set(square_lattice.graph.weighted_edge_list())
size = (3, 4, 5)
boundary_condition = (
BoundaryCondition.OPEN,
BoundaryCondition.OPEN,
BoundaryCondition.OPEN,
)
cubic_lattice = HyperCubicLattice(size=size, boundary_condition=boundary_condition)
# function for setting the positions
def indextocoord_3d(index: int, size: tuple, angle) -> list:
z = index // (size[0] * size[1])
a = index % (size[0] * size[1])
y = a // size[0]
x = a % size[0]
vec_x = np.array([1, 0])
vec_y = np.array([np.cos(angle), np.sin(angle)])
vec_z = np.array([0, 1])
return_coord = x * vec_x + y * vec_y + z * vec_z
return return_coord.tolist()
pos = dict([(index, indextocoord_3d(index, size, angle=pi / 4)) for index in range(np.prod(size))])
cubic_lattice.draw(style=LatticeDrawStyle(pos=pos))
rows = 4
cols = 3
boundary_condition = BoundaryCondition.OPEN
triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition)
triangular_lattice.draw()
rows = 4
cols = 3
boundary_condition = BoundaryCondition.PERIODIC
triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition)
triangular_lattice.draw()
graph = rx.PyGraph(multigraph=False) # multigraph shoud be False
graph.add_nodes_from(range(6))
weighted_edge_list = [
(0, 1, 1.0 + 1.0j),
(0, 2, -1.0),
(2, 3, 2.0),
(4, 2, -1.0 + 2.0j),
(4, 4, 3.0),
(2, 5, -1.0),
]
graph.add_edges_from(weighted_edge_list)
# make a lattice
general_lattice = Lattice(graph)
set(general_lattice.graph.weighted_edge_list())
general_lattice.draw()
general_lattice.draw(self_loop=True)
general_lattice.draw(self_loop=True, style=LatticeDrawStyle(with_labels=True))
square_lattice = SquareLattice(rows=5, cols=4, boundary_condition=BoundaryCondition.PERIODIC)
t = -1.0 # the interaction parameter
v = 0.0 # the onsite potential
u = 5.0 # the interaction parameter U
fhm = FermiHubbardModel(
square_lattice.uniform_parameters(
uniform_interaction=t,
uniform_onsite_potential=v,
),
onsite_interaction=u,
)
ham = fhm.second_q_op().simplify()
print(ham)
graph = rx.PyGraph(multigraph=False) # multiigraph shoud be False
graph.add_nodes_from(range(6))
weighted_edge_list = [
(0, 1, 1.0 + 1.0j),
(0, 2, -1.0),
(2, 3, 2.0),
(4, 2, -1.0 + 2.0j),
(4, 4, 3.0),
(2, 5, -1.0),
]
graph.add_edges_from(weighted_edge_list)
general_lattice = Lattice(graph) # the lattice whose weights are seen as the interaction matrix.
u = 5.0 # the interaction parameter U
fhm = FermiHubbardModel(lattice=general_lattice, onsite_interaction=u)
ham = fhm.second_q_op().simplify()
print(ham)
from qiskit_nature.second_q.problems import LatticeModelProblem
num_nodes = 4
boundary_condition = BoundaryCondition.OPEN
line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition)
fhm = FermiHubbardModel(
line_lattice.uniform_parameters(
uniform_interaction=t,
uniform_onsite_potential=v,
),
onsite_interaction=u,
)
lmp = LatticeModelProblem(fhm)
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import JordanWignerMapper
numpy_solver = NumPyMinimumEigensolver()
qubit_mapper = JordanWignerMapper()
calc = GroundStateEigensolver(qubit_mapper, numpy_solver)
res = calc.solve(lmp)
print(res)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
print('\n Superdense Coding')
print('--------------------------\n')
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.enable_account('ENTER API TOKEN')
provider = IBMQ.get_provider(hub='ibm-q')
q = QuantumRegister(2,'q')
c = ClassicalRegister(2,'c')
backend = provider.get_backend('ibmq_qasm_simulator')
print('Provider: ',backend)
#################### 00 ###########################
circuit = QuantumCircuit(q,c)
circuit.h(q[0]) # Hadamard gate applied to q0
circuit.cx(q[0],q[1]) # CNOT gate applied
circuit.cx(q[0],q[1])
circuit.h(q[0])
circuit.measure(q,c) # Qubits measured
job = execute(circuit, backend, shots=10)
print('Executing Job...\n')
job_monitor(job)
counts = job.result().get_counts()
print('RESULT: ',counts,'\n')
#################### 10 ###########################
circuit = QuantumCircuit(q,c)
circuit.h(q[0])
circuit.cx(q[0],q[1])
circuit.x(q[0]) # X-gate applied
circuit.cx(q[0],q[1])
circuit.h(q[0])
circuit.measure(q,c)
job = execute(circuit, backend, shots=10)
print('Executing Job...\n')
job_monitor(job)
counts = job.result().get_counts()
print('RESULT: ',counts,'\n')
#################### 01 ###########################
circuit = QuantumCircuit(q,c)
circuit.h(q[0])
circuit.cx(q[0],q[1])
circuit.z(q[0]) # Z-gate applied to q0
circuit.cx(q[0],q[1])
circuit.h(q[0])
circuit.measure(q,c)
job = execute(circuit, backend, shots=10)
print('Executing Job...\n')
job_monitor(job)
counts = job.result().get_counts()
print('RESULT: ',counts,'\n')
#################### 11 ###########################
circuit = QuantumCircuit(q,c)
circuit.h(q[0])
circuit.cx(q[0],q[1])
circuit.z(q[0]) # Z-gate applied
circuit.x(q[0]) # X-gate applied
circuit.cx(q[0],q[1])
circuit.h(q[0])
circuit.measure(q,c)
job = execute(circuit, backend, shots=10)
print('Executing Job...\n')
job_monitor(job)
counts = job.result().get_counts()
print('RESULT: ',counts,'\n')
print('Press any key to close')
input()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver()
problem = driver.run()
print(problem)
from qiskit_nature.second_q.problems import ElectronicBasis
driver.run_pyscf()
problem = driver.to_problem(basis=ElectronicBasis.MO, include_dipole=True)
print(problem.basis)
ao_problem = driver.to_problem(basis=ElectronicBasis.AO)
print(ao_problem.basis)
from qiskit_nature.second_q.formats.qcschema_translator import qcschema_to_problem
qcschema = driver.to_qcschema()
ao_problem = qcschema_to_problem(qcschema, basis=ElectronicBasis.AO)
from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema
basis_transformer = get_ao_to_mo_from_qcschema(qcschema)
mo_problem = basis_transformer.transform(ao_problem)
print(mo_problem.basis)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/rubenandrebarreiro/summer-school-on-quantum-computing-software-for-near-term-quantum-devices-2020
|
rubenandrebarreiro
|
# import common packages
import numpy as np
from qiskit import Aer
# lib from Qiskit Aqua
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.aqua.operators import Z2Symmetries
from qiskit.aqua.components.optimizers import COBYLA
# lib from Qiskit Aqua Chemistry
from qiskit.chemistry import FermionicOperator
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.components.initial_states import HartreeFock
# using driver to get fermionic Hamiltonian
# PySCF example
driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
# please be aware that the idx here with respective to original idx
freeze_list = [0]
remove_list = [-3, -2] # negative number denotes the reverse order
map_type = 'parity'
h1 = molecule.one_body_integrals
h2 = molecule.two_body_integrals
nuclear_repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
print("HF energy: {}".format(molecule.hf_energy - molecule.nuclear_repulsion_energy))
print("# of electrons: {}".format(num_particles))
print("# of spin orbitals: {}".format(num_spin_orbitals))
# prepare full idx of freeze_list and remove_list
# convert all negative idx to positive
remove_list = [x % molecule.num_orbitals for x in remove_list]
freeze_list = [x % molecule.num_orbitals for x in freeze_list]
# update the idx in remove_list of the idx after frozen, since the idx of orbitals are changed after freezing
remove_list = [x - len(freeze_list) for x in remove_list]
remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list]
freeze_list += [x + molecule.num_orbitals for x in freeze_list]
# prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian
# and if PARITY mapping is selected, reduction qubits
energy_shift = 0.0
qubit_reduction = True if map_type == 'parity' else False
ferOp = FermionicOperator(h1=h1, h2=h2)
if len(freeze_list) > 0:
ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list)
num_spin_orbitals -= len(freeze_list)
num_particles -= len(freeze_list)
if len(remove_list) > 0:
ferOp = ferOp.fermion_mode_elimination(remove_list)
num_spin_orbitals -= len(remove_list)
qubitOp = ferOp.mapping(map_type=map_type, threshold=0.00000001)
qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) if qubit_reduction else qubitOp
qubitOp.chop(10**-10)
print(qubitOp.print_details())
print(qubitOp)
# Using exact eigensolver to get the smallest eigenvalue
exact_eigensolver = NumPyMinimumEigensolver(qubitOp)
ret = exact_eigensolver.run()
print('The computed energy is: {:.12f}'.format(ret.eigenvalue.real))
print('The total ground state energy is: {:.12f}'.format(ret.eigenvalue.real + energy_shift + nuclear_repulsion_energy))
# from qiskit import IBMQ
# provider = IBMQ.load_account()
backend = Aer.get_backend('statevector_simulator')
# setup COBYLA optimizer
max_eval = 200
cobyla = COBYLA(maxiter=max_eval)
# setup HartreeFock state
HF_state = HartreeFock(num_spin_orbitals, num_particles, map_type,
qubit_reduction)
# setup UCCSD variational form
var_form = UCCSD(num_orbitals=num_spin_orbitals, num_particles=num_particles,
active_occupied=[0], active_unoccupied=[0, 1],
initial_state=HF_state, qubit_mapping=map_type,
two_qubit_reduction=qubit_reduction, num_time_slices=1)
# setup VQE
vqe = VQE(qubitOp, var_form, cobyla)
quantum_instance = QuantumInstance(backend=backend)
results = vqe.run(quantum_instance)
print('The computed ground state energy is: {:.12f}'.format(results.eigenvalue.real))
print('The total ground state energy is: {:.12f}'.format(results.eigenvalue.real + energy_shift + nuclear_repulsion_energy))
print("Parameters: {}".format(results.optimal_point))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/COFAlumni-USB/qiskit-fall-2022
|
COFAlumni-USB
|
#For Python and advanced manipulation import these packages
try:
import numpy as np
except:
!pip install numpy
import numpy as np
try:
import qiskit
except:
!pip install qiskit
import qiskit
try:
!pip install pylatexenc
estilo = 'mpl'
QuantumCircuit(1).draw(estilo)
except:
estilo = 'text'
#Libraries for quantum circuits
from qiskit import QuantumCircuit, execute
#For calibration
from qiskit import pulse, transpile
from qiskit.pulse.library import Gaussian
#Personalized gates
from qiskit.circuit import Gate
from qiskit import QiskitError
#For information
import qiskit.tools.jupyter
from qiskit import IBMQ
#Load our IBM Quantum account
provider = IBMQ.enable_account("c8440457d4ccb10786816758f1ffd909ea528ea12c2ac744598dd73ec90d1476ffa9f58251d0db77b256bcb655f85be37e3163e5548178ed618bc2ec2c57fbf4")
provider.backends()
from qiskit.providers.ibmq import least_busy
#This searches for the least busy backend, with 5 qubits
small_devices = provider.backends(filters=lambda x: x.configuration().n_qubits == 5
and not x.configuration().simulator)
least_busy(small_devices)
#Once we saw which backend was lest busy, we choose it with .get_backend()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_belem')
backend_config = backend.configuration()
print(backend_config)
#Sampling time of the pulses
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
#Timing constraint of the backend
backend.configuration().timing_constraints
#We get those values and save it in a variable
acquire_alignment = backend.configuration().timing_constraints['acquire_alignment']
granularity = backend.configuration().timing_constraints['granularity']
pulse_alignment = backend.configuration().timing_constraints['pulse_alignment']
lcm = np.lcm(acquire_alignment, pulse_alignment)
print(f"Least common multiple of acquire_alignment and pulse_alignment: {lcm}")
backend_defaults = backend.defaults()
#Finding qubit's frequency
#Defining units
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
#We will work with the following qubit
qubit = 0
#Center the sweep in a qubit estimated frequency in Hz
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit]
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
# scale factor to remove factors of 10 from the data
scale_factor = 1e-7
#Sweep 40 MHz around the estimated frequency
frequency_span_Hz = 40 * MHz
#With 1MHz steps
frequency_step_Hz = 1 * MHz
#Sweep 20 MHz above and 20 MHz below the estimated frequency
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
#Array of the frequencies
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \
in steps of {frequency_step_Hz / MHz} MHz.")
#This function returns the closest multiple between two values
def get_closest_multiple_of(value, base_number):
return int(value + base_number/2) - (int(value + base_number/2) % base_number)
#Lenght of the pulse: it has to be multiple of 16 (granularity)
def get_closest_multiple_of_16(num):
return get_closest_multiple_of(num, granularity)
#Lenght of the delay, converts s to dt
def get_dt_from(sec):
return get_closest_multiple_of(sec/dt, lcm)
from qiskit.circuit import Parameter
from qiskit.circuit import QuantumCircuit, Gate
#Drive pulse parameters (us = microseconds)
#Determines width of the Gaussian, but I need it for drive_duration
drive_sigma_sec = 0.015 * us
#Truncating parameter
"""Changed this parameter because I was getting three pulses
in Measured Signal. With this new duration I get the envelope
of the three pulses. This happens because the transitions of
the qubit states (0/1) are not perfectly populated,
so we get a mix of the other states."""
drive_duration_sec = drive_sigma_sec * 3.5
# For qubit frequency estimate from 5.09021 GHz to 5.09035 GHz use:
# drive_duration_sec = drive_sigma_sec * 4
#Pulse's amplitude
drive_amp = 0.05
#Base schedule
freq = Parameter('freq')
with pulse.build(backend=backend, default_alignment='sequential', name='Frequency sweep') as sweep_sched:
#seconds_to_samples(s) gets the number of samples that will elapse in seconds on the active backend.
drive_duration = get_closest_multiple_of_16(pulse.seconds_to_samples(drive_duration_sec))
#sigma is not required for Constant pulse
#drive_sigma = pulse.seconds_to_samples(drive_sigma_sec)
#Returns the qubit's DriveChannel on the active backend
#Drive channels transmit signals to qubits which enact gate operations
drive_chan = pulse.drive_channel(qubit)
pulse.set_frequency(freq, drive_chan)
#Drive pulse samples
pulse.play(pulse.Constant(duration=drive_duration,
amp=drive_amp,
name='freq_sweep_excitation_pulse'), drive_chan)
#Plot the pulse
sweep_sched.draw()
#Gate(name, num_qubits, params) creates a new gate
sweep_gate = Gate("sweep", 1, [freq])
#Create the quantum circuit, 1 qubit, 1 bit
qc_sweep = QuantumCircuit(1, 1)
#Add our new gate sweep_gate to the quantum circuit
qc_sweep.append(sweep_gate, [0])
qc_sweep.measure(0, 0)
"""This command: add_calibration(gate, qubits, schedule, params=None)
registers a low-level, custom pulse definition for the given gate"""
qc_sweep.add_calibration(sweep_gate, (0,), sweep_sched, [freq])
#Frequency settings for the sweep (MUST BE IN HZ)
frequencies_Hz = frequencies_GHz*GHz #convert to Hz
"""This command: assign_parameters(parameters, inplace=False)
assigns parameters to new parameters or values"""
exp_sweep_circs = [qc_sweep.assign_parameters({freq: f}, inplace=False) for f in frequencies_Hz]
from qiskit import schedule
#schedule(circuits, backend) to schedule a circuit to a pulse Schedule, using the backend
sweep_schedule = schedule(exp_sweep_circs[0], backend)
#To show the schedule
sweep_schedule.draw(backend=backend)
#Each schedule will be repeated num_shots_per_frequency times
num_shots_per_frequency = 1024
job = backend.run(exp_sweep_circs,
meas_level=1, #kerneled data
meas_return='avg',
shots=num_shots_per_frequency)
from qiskit.tools.monitor import job_monitor
#Monitor the job status
job_monitor(job)
#Retrieve the results
frequency_sweep_results = job.result(timeout=1200)
#Plotting the results with matplotlib
import matplotlib.pyplot as plt
sweep_values = []
for i in range(len(frequency_sweep_results.results)):
# Get the results from the ith experiment
res = frequency_sweep_results.get_memory(i)*scale_factor
# Get the results for `qubit` from this experiment
sweep_values.append(res[qubit])
#Plot frequencies vs. real part of sweep values
plt.scatter(frequencies_GHz, np.real(sweep_values), color='black')
# plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured signal [a.u.]")
plt.show()
#Using scipy for the curve fitting
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
#Fitting the curve. We use a Gaussian function for the fit
"""We need to assign the correct initial parameters for our data
A is related to the height of the curve,
B is related to the width of the Gaussian,
C is the cut with the Y axis and
q_freq is the estimated peak frequency of the curve."""
fit_params, y_fit = fit_function(frequencies_GHz,
np.real(sweep_values),
lambda x, A, q_freq, B, C: A*np.exp(-(x - q_freq) ** 2 / (2*B**2)) + C,
[1.75e8, 5.090, 0.02, 0] # initial parameters for curve_fit
)
#Plotting the data
plt.scatter(frequencies_GHz, np.real(sweep_values), color='black')
#and plotting the fit
plt.plot(frequencies_GHz, y_fit, color='red')
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
A, rough_qubit_frequency, B, C = fit_params
rough_qubit_frequency = rough_qubit_frequency*GHz # make sure qubit freq is in Hz
print(f"We've updated our qubit frequency estimate from "
f"{round(backend_defaults.qubit_freq_est[qubit] / GHz, 5)} GHz to {round(rough_qubit_frequency/GHz, 5)} GHz.")
#Calibrating using a pi pulse
#Pi pulses takes a qubit from |0> to |1> (X gate)
#Rabi experiment parameters
num_rabi_points = 50
#Drive amplitude values to iterate over
#50 amplitudes evenly spaced from 0 to 0.75 using linspace
drive_amp_min = 0
drive_amp_max = 0.55 #Changed this parameter
drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points)
# Build the Rabi experiments:
"""A drive pulse at the qubit frequency, followed by a measurement,
where we vary the drive amplitude each time"""
#This is similar to the frequency sweep schedule
drive_amp = Parameter('drive_amp')
with pulse.build(backend=backend, default_alignment='sequential', name='Rabi Experiment') as rabi_sched:
drive_duration = get_closest_multiple_of_16(pulse.seconds_to_samples(drive_duration_sec))
# drive_sigma = pulse.seconds_to_samples(drive_sigma_sec)
drive_chan = pulse.drive_channel(qubit)
#With the rough_qubit_frequency found before
pulse.set_frequency(rough_qubit_frequency, drive_chan)
pulse.play(pulse.Constant(duration=drive_duration,
amp=drive_amp,
name='Rabi Pulse'), drive_chan)
#New rabi gate
rabi_gate = Gate("rabi", 1, [drive_amp])
#New quantum circuit for Rabi Experiment
qc_rabi = QuantumCircuit(1, 1)
#Add the rabi_gate we just defined
qc_rabi.append(rabi_gate, [0])
#Measure the QC
qc_rabi.measure(0, 0)
#Add calibration to the rabi_gate
qc_rabi.add_calibration(rabi_gate, (0,), rabi_sched, [drive_amp])
exp_rabi_circs = [qc_rabi.assign_parameters({drive_amp: a}, inplace=False) for a in drive_amps]
#Create our schedule and draw it
rabi_schedule = schedule(exp_rabi_circs[-1], backend)
rabi_schedule.draw(backend=backend)
num_shots_per_point = 1024
job = backend.run(exp_rabi_circs,
meas_level=1,
meas_return='avg',
shots=num_shots_per_point)
job_monitor(job)
#Get the results
rabi_results = job.result(timeout=120)
"""We need to extract the results and fit them to a sinusoidal curve
The range of amplitudes we got will rotate (hopefully) the qubit several times
around the Bloch sphere. We need to find the drive amplitude needed for the
signal to oscillate from a maximum to a minimum (all |0> to all |1>)
That's exactly what gives us the calibrated amplitud represented by the pi pulse
"""
#First we center the data around 0
def baseline_remove(values):
return np.array(values) - np.mean(values)
#Empty array for Rabi values
rabi_values = []
#Remember we defined num_rabi_points initially at 50
for i in range(num_rabi_points):
#Get the results for 'qubit' from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[qubit] * scale_factor)
#We get the real values from the centered rabi_values
rabi_values = np.real(baseline_remove(rabi_values))
#Plot the results
plt.xlabel("Drive amp [a.u.]")
plt.ylabel("Measured signal [a.u.]")
#Plotting amplitudes vs Rabi values
plt.scatter(drive_amps, rabi_values, color='black')
plt.show()
#Now we fit the curve, similarly to the frequencies fit
#THIS PARAMETERS ARE FOR IBQM QUITO AND BELEM
fit_params, y_fit = fit_function(drive_amps,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B),
[1.4e8, 0, 0.16, 0])
plt.scatter(drive_amps, rabi_values, color='black')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] #get period of rabi oscillation
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
#Pi pulse's amplitude needed for the signal to oscillate from maximum to minimum
pi_amp = abs(drive_period / 2)
print(f"Pi Amplitude = {pi_amp}")
#We can define our pi pulse now
with pulse.build(backend) as pi_pulse:
drive_duration = get_closest_multiple_of_16(pulse.seconds_to_samples(drive_duration_sec))
# drive_sigma = pulse.seconds_to_samples(drive_sigma_sec)
drive_chan = pulse.drive_channel(qubit)
pulse.play(pulse.Constant(duration=drive_duration,
amp=pi_amp,
name='pi_pulse'), drive_chan)
pi_pulse.draw()
#Now we create a ground state to try our pi pulse
qc_gnd = QuantumCircuit(1, 1)
qc_gnd.measure(0, 0)
#And its ground schedule
gnd_schedule = schedule(qc_gnd, backend)
gnd_schedule.draw(backend=backend)
#We create the excited state
with pulse.build(backend=backend, default_alignment='sequential', name='excited state') as exc_schedule:
drive_chan = pulse.drive_channel(qubit)
pulse.set_frequency(rough_qubit_frequency, drive_chan)
pulse.call(pi_pulse)
#And another QC for the excited state
qc_exc = QuantumCircuit(1, 1)
#Apply X gate to qubit 0
qc_exc.x(0)
#And measure it
qc_exc.measure(0, 0)
#Then we add the calibration from the excited state's sched
qc_exc.add_calibration("x", (0,), exc_schedule, [])
#Now execute the exc state's schedule
exec_schedule = schedule(qc_exc, backend)
exec_schedule.draw(backend=backend)
#Preparation schedules for the ground and excited states
num_shots = 1024
job = backend.run([qc_gnd, qc_exc],
#Choosing meas_level 1 for kerneled data
meas_level=1,
meas_return='single',
shots=num_shots)
job_monitor(job)
gnd_exc_results = job.result(timeout=120)
#Getting the ground and excited state's results
gnd_results = gnd_exc_results.get_memory(0)[:, qubit]*scale_factor
exc_results = gnd_exc_results.get_memory(1)[:, qubit]*scale_factor
#Plotting results
plt.figure()
#Ground state in blue
plt.scatter(np.real(gnd_results), np.imag(gnd_results),
s=5, cmap='viridis', c='blue', alpha=0.5, label='Gnd state')
#Excited state in red
plt.scatter(np.real(exc_results), np.imag(exc_results),
s=5, cmap='viridis', c='red', alpha=0.5, label='Exc state')
plt.axis('square')
#Plot a large black dot for the average result of the 0 and 1 states
#Mean of real and imaginary parts of results
mean_gnd = np.mean(gnd_results)
mean_exc = np.mean(exc_results)
plt.scatter(np.real(mean_gnd), np.imag(mean_gnd),
s=100, cmap='viridis', c='black',alpha=1.0, label='Mean')
plt.scatter(np.real(mean_exc), np.imag(mean_exc),
s=100, cmap='viridis', c='black',alpha=1.0)
plt.ylabel('Im [a.u.]', fontsize=15)
plt.xlabel('Q (Real) [a.u.]', fontsize=15)
plt.title("0-1 discrimination", fontsize=15)
plt.legend()
plt.show()
"""The mean value of the excited state is not in the center of the big red circle,
this is due to the population of excited states (red dots) not being
perfectly together, but several red dots are in the blue area."""
"""Setting up a classifier function:
returns 0 if a given point is closer to the mean of ground state results
and returns 1 if the point is closer to the avg exc state results"""
import math
#This functions classifies the given state as |0> or |1>.
def classify(point: complex):
def distance(a, b):
return math.sqrt((np.real(a) - np.real(b))**2 + (np.imag(a) - np.imag(b))**2)
return int(distance(point, mean_exc) < distance(point, mean_gnd))
#T1 time: time it takes for a qubit to decay from exc_state to gnd_state
"""To measure T1 we use the pi pulse we've calibrated, then a measure pulse.
But first we have to insert a delay"""
#T1 experiment parameters
time_max_sec = 450 * us
time_step_sec = 6.5 * us
delay_times_sec = np.arange(1 * us, time_max_sec, time_step_sec)
#We define the delay
delay = Parameter('delay')
#Create another quantum circuit
qc_t1 = QuantumCircuit(1, 1)
#X Gate
qc_t1.x(0)
#Delay
qc_t1.delay(delay, 0)
#Measurement
qc_t1.measure(0, 0)
#Calibration on X gate with our pi pulse
qc_t1.add_calibration("x", (0,), pi_pulse)
exp_t1_circs = [qc_t1.assign_parameters({delay: get_dt_from(d)}, inplace=False) for d in delay_times_sec]
#Schedule for T1
sched_idx = -1
t1_schedule = schedule(exp_t1_circs[sched_idx], backend)
t1_schedule.draw(backend=backend)
#Execution settings
num_shots = 256
job = backend.run(exp_t1_circs,
meas_level=1,
meas_return='single',
shots=num_shots)
job_monitor(job)
t1_results = job.result(timeout=120)
#Getting the results to plot
t1_values = []
for i in range(len(delay_times_sec)):
iq_data = t1_results.get_memory(i)[:,qubit] * scale_factor
#sum() returns the sum of all items.
#map() returns a map object of the result after applying a given
#function (sum) to each item of a given iterable.
t1_values.append(sum(map(classify, iq_data)) / num_shots)
plt.scatter(delay_times_sec/us, t1_values, color='black')
plt.title("$T_1$ Experiment", fontsize=15)
plt.xlabel('Delay before measurement [$\mu$s]', fontsize=15)
plt.ylabel('Signal [a.u.]', fontsize=15)
plt.show()
#Fitting data with an exponential curve
fit_params, y_fit = fit_function(delay_times_sec/us, t1_values,
lambda x, A, C, T1: (A * np.exp(-x / T1) + C),
[-3, 3, 100]
)
_, _, T1 = fit_params
plt.scatter(delay_times_sec/us, t1_values, color='black')
plt.plot(delay_times_sec/us, y_fit, color='red', label=f"T1 = {T1:.2f} us")
plt.xlim(0, np.max(delay_times_sec/us))
plt.title("$T_1$ Experiment", fontsize=15)
plt.xlabel('Delay before measurement [$\mu$s]', fontsize=15)
plt.ylabel('Signal [a.u.]', fontsize=15)
plt.legend()
plt.show()
#Measure qubit frequency (precisely) with Ramsey Experiment
#Apply a pi/2 pulse, wait some time, and then anothe pi/2 pulse.
#Ramsey experiment parameters
time_max_sec = 1.8 * us
time_step_sec = 0.025 * us
delay_times_sec = np.arange(0.1 * us, time_max_sec, time_step_sec)
#Drive parameters
#Drive amplitude for pi/2 is simply half the amplitude of the pi pulse
drive_amp = pi_amp / 2
#Build the x_90 pulse, which is an X rotation of 90 degrees, a pi/2 rotation
with pulse.build(backend) as x90_pulse:
drive_duration = get_closest_multiple_of_16(pulse.seconds_to_samples(drive_duration_sec))
drive_sigma = pulse.seconds_to_samples(drive_sigma_sec)
drive_chan = pulse.drive_channel(qubit)
pulse.play(pulse.Constant(duration=drive_duration,
amp=drive_amp,
name='x90_pulse'), drive_chan)
#Now we have to drive the pulses off-resonance an amount detuning_MHz
detuning_MHz = 2
ramsey_frequency = round(rough_qubit_frequency + detuning_MHz * MHz, 6) #Ramsey freq in Hz
#Pulse for Ramsey experiment
delay = Parameter('delay')
with pulse.build(backend=backend, default_alignment='sequential', name="Ramsey delay Experiment") as ramsey_schedule:
drive_chan = pulse.drive_channel(qubit)
pulse.set_frequency(ramsey_frequency, drive_chan)
#X pulse, Delay, X pulse
pulse.call(x90_pulse)
pulse.delay(delay, drive_chan)
pulse.call(x90_pulse)
#Ramsey gate
ramsey_gate = Gate("ramsey", 1, [delay])
#Another QC for Ramsey experiment
qc_ramsey = QuantumCircuit(1, 1)
#Adding the gate to the circuit
qc_ramsey.append(ramsey_gate, [0])
qc_ramsey.measure(0, 0)
qc_ramsey.add_calibration(ramsey_gate, (0,), ramsey_schedule, [delay])
exp_ramsey_circs = [qc_ramsey.assign_parameters({delay: get_dt_from(d)}, inplace=False) for d in delay_times_sec]
ramsey_schedule = schedule(exp_ramsey_circs[2], backend)
ramsey_schedule.draw(backend=backend)
#Execution settings for Ramsey experimet
num_shots = 256
job = backend.run(exp_ramsey_circs,
meas_level=1,
meas_return='single',
shots=num_shots)
job_monitor(job)
ramsey_results = job.result(timeout=120)
#Array for the results
ramsey_values = []
for i in range(len(delay_times_sec)):
iq_data = ramsey_results.get_memory(i)[:,qubit] * scale_factor
ramsey_values.append(sum(map(classify, iq_data)) / num_shots)
#Plotting the results
plt.scatter(delay_times_sec/us, np.real(ramsey_values), color='black')
plt.xlim(0, np.max(delay_times_sec/us))
plt.title("Ramsey Experiment", fontsize=15)
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.show()
#Fitting data to a sinusoid
fit_params, y_fit = fit_function(delay_times_sec/us, np.real(ramsey_values),
lambda x, A, del_f_MHz, C, B: (
A * np.cos(2*np.pi*del_f_MHz*x - C) + B
),
[5, 1.5, 0, 0.25]
)
# Off-resonance component
_, del_f_MHz, _, _, = fit_params # freq is MHz since times in us
plt.scatter(delay_times_sec/us, np.real(ramsey_values), color='black')
plt.plot(delay_times_sec/us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz")
plt.xlim(0, np.max(delay_times_sec/us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend()
plt.show()
precise_qubit_freq = rough_qubit_frequency + (detuning_MHz - del_f_MHz) * MHz # get new freq in Hz
print(f"Our updated qubit frequency is now {round(precise_qubit_freq/GHz, 6)} GHz. "
f"It used to be {round(rough_qubit_frequency / GHz, 6)} GHz")
#Measuring coherence time (T2) with Hahn Echoes experiment
#It's the same as Ramsey's experiment, with a pi pulse between the pi/2
#T2 experiment parameters
tau_max_sec = 200 * us
tau_step_sec = 4 * us
delay_times_sec = np.arange(2 * us, tau_max_sec, tau_step_sec)
#Define the delay and build the pulse for T2
delay = Parameter('delay')
with pulse.build(backend=backend, default_alignment='sequential', name="T2 delay Experiment") as t2_schedule:
drive_chan = pulse.drive_channel(qubit)
pulse.set_frequency(precise_qubit_freq, drive_chan)
#X pulse, delay, pi pulse, delay, X pulse
pulse.call(x90_pulse)
pulse.delay(delay, drive_chan)
pulse.call(pi_pulse)
pulse.delay(delay, drive_chan)
pulse.call(x90_pulse)
#Define T2 gate
t2_gate = Gate("t2", 1, [delay])
#QC for T2
qc_t2 = QuantumCircuit(1, 1)
#Add T2 gate
qc_t2.append(t2_gate, [0])
qc_t2.measure(0, 0)
#Add calibration with delay
qc_t2.add_calibration(t2_gate, (0,), t2_schedule, [delay])
exp_t2_circs = [qc_t2.assign_parameters({delay: get_dt_from(d)}, inplace=False) for d in delay_times_sec]
#Schedule for T2 and show it
t2_schedule = schedule(exp_t2_circs[-1], backend)
t2_schedule.draw(backend=backend)
#Execution settings
num_shots_per_point = 512
job = backend.run(exp_t2_circs,
meas_level=1, #Kerneled data
meas_return='single',
shots=num_shots_per_point)
job_monitor(job)
#Getting results
t2_results = job.result(timeout=120)
#T2 empty array
t2_values = []
#Retrieving results and adding them classified to the array
for i in range(len(delay_times_sec)):
iq_data = t2_results.get_memory(i)[:,qubit] * scale_factor
t2_values.append(sum(map(classify, iq_data)) / num_shots_per_point)
#Plot ressults for Hanh Echo experiment
plt.scatter(2*delay_times_sec/us, t2_values, color='black')
plt.xlabel('Delay between X90 pulse and $\pi$ pulse [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Hahn Echo Experiment', fontsize=15)
plt.show()
#Fitting data with an exponential function
fit_params, y_fit = fit_function(2*delay_times_sec/us, t2_values,
lambda x, A, B, T2: (A * np.exp(-x / T2) + B),
[-3, 0, 100])
_, _, T2 = fit_params
#Plotting results and fit curve
plt.scatter(2*delay_times_sec/us, t2_values, color='black')
plt.plot(2*delay_times_sec/us, y_fit, color='red', label=f"T2 = {T2:.2f} us")
plt.xlim(0, np.max(2*delay_times_sec/us))
plt.xlabel('Delay between X90 pulse and $\pi$ pulse [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Hahn Echo Experiment', fontsize=15)
plt.legend()
plt.show()
#Dynamical decoupling technique
#Used to extract longer coherence times from qubits
#Experiment parameters
tau_sec_min = 1 * us
tau_sec_max = 180 * us
tau_step_sec = 4 * us
taus_sec = np.arange(tau_sec_min, tau_sec_max, tau_step_sec)
num_sequence = 1
print(f"Total time ranges from {2.*num_sequence*taus_sec[0] / us} to {2.*num_sequence*taus_sec[-1] / us} us")
#This schedule is different from the others...
delay = Parameter('delay')
with pulse.build(backend=backend, default_alignment='sequential', name="T2DD delay Experiment") as T2DD_schedule:
drive_chan = pulse.drive_channel(qubit)
pulse.set_frequency(precise_qubit_freq, drive_chan)
#X Pulse and Delay
pulse.call(x90_pulse)
pulse.delay(delay/2, drive_chan)
for loop_counts in range(num_sequence):
pulse.call(pi_pulse)
pulse.delay(delay, drive_chan)
with pulse.phase_offset(np.pi/2, pulse.drive_channel(qubit)):
pulse.call(pi_pulse)
pulse.delay(delay, drive_chan)
pulse.call(pi_pulse)
pulse.delay(delay, drive_chan)
with pulse.phase_offset(np.pi/2, pulse.drive_channel(qubit)):
pulse.call(pi_pulse)
if loop_counts != num_sequence-1:
pulse.delay(delay, drive_chan)
pulse.delay(delay/2, drive_chan)
pulse.call(x90_pulse)
#Create new gate for T2 Dynamical Decouling
T2DD_gate = Gate("T2DD", 1, [delay])
#Another QC
qc_T2DD = QuantumCircuit(1, 1)
qc_T2DD.append(T2DD_gate, [0])
qc_T2DD.measure(0, 0)
qc_T2DD.add_calibration(T2DD_gate, (0,), T2DD_schedule, [delay])
exp_T2DD_circs = [qc_T2DD.assign_parameters({delay: get_dt_from(d)}, inplace=False) for d in taus_sec]
#Schedule fot T2 D.D.
T2DD_schedule = schedule(exp_T2DD_circs[-1], backend)
T2DD_schedule.draw(backend=backend)
num_shots_per_point = 1024
job = backend.run(exp_T2DD_circs,
meas_level=1,
meas_return='single',
shots=num_shots_per_point)
job_monitor(job)
T2DD_results = job.result(timeout=120)
times_sec = 4*num_sequence*taus_sec
DD_values = []
for i in range(len(times_sec)):
iq_data = T2DD_results.get_memory(i)[:,qubit] * scale_factor
DD_values.append(sum(map(classify, iq_data)) / num_shots_per_point)
plt.scatter(times_sec/us, DD_values, color='black')
plt.xlim(0, np.max(times_sec/us))
plt.xlabel('Total time before measurement [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Dynamical Decoupling Experiment', fontsize=15)
plt.show()
# Fit the data
fit_func = lambda x, A, B, T2DD: (A * np.exp(-x / T2DD) + B)
fitparams, conv = curve_fit(fit_func, times_sec/us, DD_values, [3.5, 0.8, 150])
_, _, T2DD = fitparams
plt.scatter(times_sec/us, DD_values, color='black')
plt.plot(times_sec/us, fit_func(times_sec/us, *fitparams), color='red', label=f"T2DD = {T2DD:.2f} us")
plt.xlim([0, np.max(times_sec/us)])
plt.xlabel('Total time before measurement [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Dynamical Decoupling Experiment', fontsize=15)
plt.legend()
plt.show()
"""That little oscillation in the DD experiment graph
means that my qubit is not totally in resonance,
it's still oscillating between two states.
It can be fixed by adjusting parameters in every experiment,
and improving the curve fittings."""
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
input_3sat_instance = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
import os
import tempfile
from qiskit.exceptions import MissingOptionalLibraryError
from qiskit.circuit.library.phase_oracle import PhaseOracle
fp = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
fp.write(input_3sat_instance)
file_name = fp.name
fp.close()
oracle = None
try:
oracle = PhaseOracle.from_dimacs_file(file_name)
except MissingOptionalLibraryError as ex:
print(ex)
finally:
os.remove(file_name)
from qiskit.algorithms import AmplificationProblem
problem = None
if oracle is not None:
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
from qiskit.algorithms import Grover
from qiskit.primitives import Sampler
grover = Grover(sampler=Sampler())
result = None
if problem is not None:
result = grover.amplify(problem)
print(result.assignment)
from qiskit.tools.visualization import plot_histogram
if result is not None:
display(plot_histogram(result.circuit_results[0]))
expression = '(w ^ x) & ~(y ^ z) & (x & y & z)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring)
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
display(plot_histogram(result.circuit_results[0]))
except MissingOptionalLibraryError as ex:
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/ho0-kim/Hamiltonian_Cycle_Problem_with_QC
|
ho0-kim
|
import numpy as np
# QC-related libraries
from qiskit import Aer, IBMQ, execute
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram
# from qiskit.tools.visualization import plot_histogram
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import aqua_globals
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.optimization.algorithms import MinimumEigenOptimizer
from qiskit.optimization import QuadraticProgram
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.axes as axes
from docplex.mp.model import Model
from qiskit.optimization.applications.ising.docplex import get_operator
def not_in_edge( n, Edge ):
set_edge = set()
for i in range( n ):
for k in range( n ):
if ( i, k ) in Edge or ( k, i ) in Edge:
continue
else:
set_edge.add( ( i, k ) )
return set_edge
Vertex = { 0, 1, 2 }
Edge = {(0,1), (1,2), (2,0) }
n = len(Vertex)
G = nx.Graph()
G.add_nodes_from( np.arange( 0, n ) )
eList = list( Edge ) # (i,j): edge
G.add_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=.8, ax=default_axes, pos=pos)
nx.draw_networkx_edges(G, pos=pos )
draw_graph(G, colors, pos)
# Create an instance of a model and variables with DOcplex.
mdl = Model( name='HamiltonCycle' )
x = { ( i, p ): mdl.binary_var( name= 'x_{0}_{1}'.format( i, p ) ) for i in range( n ) for p in range( n ) }
# Generate cost funciton
P1 = 0
P2 = 0
H = 0
for i in range(n):
P1 += ( 1 - mdl.sum( x[(i,j)] for j in range(n) ) ) ** 2
for j in range(n):
P2 += ( 1 - mdl.sum( x[(i,j)] for i in range(n) ) ) ** 2
for ( i1, i2 ) in not_in_edge( n, Edge ):
H += x[(i1,0)] * x[(i2,n-1)]
H += mdl.sum( x[(i1,j)] * x[(i2,j+1)] for j in range(n-1) )
HamiltonCycleFunc = H + P1 + P2 # Set HamiltonCycleFunc to be minimized
mdl.minimize( HamiltonCycleFunc )
qubitOp, offset = get_operator(mdl)
print('Offset:', offset)
# print('Ising Hamiltonian:')
# print(qubitOp.print_details())
# mapping Ising Hamiltonian to Quadratic Program
qp = QuadraticProgram()
qp.from_ising(qubitOp, offset)
#qp.to_docplex().prettyprint()
# solving Quadratic Program using exact classical eigensolver
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
result = exact.solve(qp)
print(result)
#Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver(qubitOp)
result = ee.run()
x = sample_most_likely(result.eigenstate)
print('energy:', result.eigenvalue.real)
print('hamiltonian-cycle objective:', result.eigenvalue.real + offset)
provider = IBMQ.load_account()
simulator_backend = provider.get_backend("ibmq_qasm_simulator")
aqua_globals.random_seed = np.random.default_rng(123)
seed = 10598
backend = Aer.get_backend("qasm_simulator")
quantum_instance = QuantumInstance(simulator_backend, shots=1024, seed_simulator=seed, seed_transpiler=seed)
# construct VQE
spsa = SPSA(maxiter=1000)
ansatz = TwoLocal( qubitOp.num_qubits, rotation_blocks='ry', entanglement_blocks='cx', reps=2, entanglement='linear' )
vqe = VQE(operator=qubitOp, var_form=ansatz, optimizer=spsa, quantum_instance=quantum_instance)
# run VQE
result = vqe.run()
# print results
x = sample_most_likely(result.eigenstate)
print('energy:', result.eigenvalue.real)
print('time:', result.optimizer_time)
print('hamiltonian-cycle objective:', result.eigenvalue.real + offset)
print('solution:', x)
# create minimum eigen optimizer based on VQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result)
|
https://github.com/andre-juan/dicke_states_preparation
|
andre-juan
|
import numpy as np
import matplotlib.pyplot as plt
import scipy
# main classes and functions
from qiskit import QuantumRegister, QuantumCircuit, Aer, execute
# gates
from qiskit.circuit.library import RYGate
# visualization stuff
from qiskit.visualization import plot_histogram
def show_figure(fig):
'''
auxiliar function to display plot
even if it's not the last command of the cell
from: https://github.com/Qiskit/qiskit-terra/issues/1682
'''
new_fig = plt.figure()
new_mngr = new_fig.canvas.manager
new_mngr.canvas.figure = fig
fig.set_canvas(new_mngr.canvas)
plt.show(fig)
def test_circuit_qasm(qc, figsize=(12, 4)):
'''
auxiliar function to simulate the execution of a quantum circuit
using the qasm simulator.
the quantum circuit to be simulates (qc) must
have no measurements or classical registers.
'''
# meausring
qc.measure_all()
#################################
backend = Aer.get_backend("qasm_simulator")
job = execute(qc, backend, shots=1e5, seed_simulator=42)
results = job.result()
counts = results.get_counts()
print(f"\nNumber of elements in result superposition: {len(counts)}\n")
return plot_histogram(counts, title="Results", figsize=figsize)
def test_circuit_sv(qc, print_stuff=False, figsize=(12, 4)):
'''
auxiliar function to simulate the execution of a quantum circuit
using the state vector simulator.
optionally, prints the statevector components as well as the probabilities.
'''
backend = Aer.get_backend("statevector_simulator")
job = execute(qc, backend, seed_simulator=42)
results = job.result()
counts = results.get_counts()
if print_stuff:
sv = results.data(0)['statevector']
probs = sv**2
print(f"Statevector:\t{sv}\n")
print(f"Probabilities:\t{probs}")
print(f"\nNumber of elements in result superposition: {len(counts)}\n")
return plot_histogram(counts, title="Results", figsize=figsize)
def gate_i(n, draw=False):
'''
returns the 2-qubit gate (i), introduced in Sec. 2.2
this gate is simply a cR_y between 2 CNOTs, with
rotation angle given by 2*np.arccos(np.sqrt(1/n))
args:
- `n`: int, defining the rotation angle;
- `draw` : bool, determines if the circuit is drawn.
'''
qc_i = QuantumCircuit(2)
qc_i.cnot(0, 1)
theta = 2*np.arccos(np.sqrt(1/n))
cry = RYGate(theta).control(ctrl_state="1")
qc_i.append(cry, [1, 0])
qc_i.cnot(0, 1)
####################################
gate_i = qc_i.to_gate()
gate_i.name = "$(i)$"
####################################
if draw:
show_figure(qc_i.draw("mpl"))
return gate_i
def gate_ii_l(l, n, draw=False):
'''
returns the 2-qubit gate (ii)_l, introduced in Sec. 2.2
this gate is simply a ccR_y between 2 CNOTs, with
rotation angle given by 2*np.arccos(np.sqrt(l/n))
args:
- `l`: int, defining the rotation angle;
- `n`: int, defining the rotation angle;
- `draw` : bool, determines if the circuit is drawn.
'''
qc_ii = QuantumCircuit(3)
qc_ii.cnot(0, 2)
theta = 2*np.arccos(np.sqrt(l/n))
ccry = RYGate(theta).control(num_ctrl_qubits = 2, ctrl_state="11")
qc_ii.append(ccry, [2, 1, 0])
qc_ii.cnot(0, 2)
####################################
gate_ii = qc_ii.to_gate()
gate_ii.name = f"$(ii)_{l}$"
####################################
if draw:
show_figure(qc_ii.draw("mpl"))
return gate_ii
def gate_scs_nk(n, k, draw=False):
'''
returns the SCS_{n,k} gate, which is introduced in Definition 3 and
if built of one 2-qubits (i) gate and k+1 3-qubits gates (ii)_l
args:
- `n`: int, used as argument of `gate_i()` and `gate_ii_l()`;
- `k`: int, defines the size of the gate, as well as its topology;
- `draw` : bool, determines if the circuit is drawn.
'''
qc_scs = QuantumCircuit(k+1)
qc_scs.append(gate_i(n), [k-1, k])
for l in range(2, k+1):
qc_scs.append(gate_ii_l(l, n), [k-l, k-l+1, k])
####################################
gate_scs = qc_scs.to_gate()
gate_scs.name = "SCS$_{" + f"{n},{k}" + "}$"
####################################
if draw:
show_figure(qc_scs.decompose().draw("mpl"))
return gate_scs
def first_block(n, k, l, draw=False):
'''
returns the first block of unitaries products in Lemma 2.
args:
- `n`: int, used to calculate indices and as argument of `gate_scs_nk()`;
- `k`: int, used to calculate indices and as argument of `gate_scs_nk()`;
- `l`: int, used to calculate indices and as argument of `gate_scs_nk()`;
- `draw` : bool, determines if the circuit is drawn.
'''
qr = QuantumRegister(n)
qc_first_block = QuantumCircuit(qr)
# indices of qubits to which we append identities.
n_first = l-k-1
n_last = n-l
# this will be a list with the qubits indices to which
# we append the SCS_{n,k} gate.
idxs_scs = list(range(n))
# only if ther is an identity to append to first registers
if n_first != 0:
# correcting the qubits indices to which we apply SCS_{n, k}
idxs_scs = idxs_scs[n_first:]
# applying identity to first qubits
qc_first_block.i(qr[:n_first])
if n_last !=0:
idxs_scs = idxs_scs[:-n_last]
# appending SCS_{n, k} to appropriate indices
qc_first_block.append(gate_scs_nk(l, k), idxs_scs)
# applying identity to last qubits
qc_first_block.i(qr[-n_last:])
else:
# appending SCS_{n, k} to appropriate indices
qc_first_block.append(gate_scs_nk(l, k), idxs_scs)
# string with the operator, to be used as gate label
str_operator = "$1^{\otimes " + f'{n_first}' + "} \otimes$ SCS$_{" + f"{l},{k}" + "} \otimes 1^{\otimes " + f"{n_last}" + "}$"
####################################
gate_first_block = qc_first_block.to_gate()
gate_first_block.name = str_operator
####################################
if draw:
show_figure(qc_first_block.decompose().draw("mpl"))
return gate_first_block
def second_block(n, k, l, draw=False):
'''
returns the second block of unitaries products in Lemma 2.
args:
- `n`: int, used to calculate indices and as argument of `gate_scs_nk()`;
- `k`: int, used to calculate indices and as argument of `gate_scs_nk()`;
- `l`: int, used to calculate indices and as argument of `gate_scs_nk()`;
- `draw` : bool, determines if the circuit is drawn.
'''
qr = QuantumRegister(n)
qc_second_block = QuantumCircuit(qr)
# here we only have identities added to last registers, so it's a bit simpler
n_last = n-l
idxs_scs = list(range(n))
if n_last !=0:
idxs_scs = idxs_scs[:-n_last]
# appending SCS_{n, k} to appropriate indices
qc_second_block.append(gate_scs_nk(l, l-1), idxs_scs)
qc_second_block.i(qr[-n_last:])
else:
# appending SCS_{n, k} to appropriate indices
qc_second_block.append(gate_scs_nk(l, l-1), idxs_scs)
str_operator = "SCS$_{" + f"{l},{l-1}" + "} \otimes 1^{\otimes " + f"{n_last}" + "}$"
####################################
gate_second_block = qc_second_block.to_gate()
gate_second_block.name = str_operator
####################################
if draw:
show_figure(qc_second_block.decompose().draw("mpl"))
return gate_second_block
def dicke_state(n, k, draw=False, barrier=False, only_decomposed=False):
'''
returns a quantum circuit with to prepare a Dicke state with arbitrary n, k
this function essentially calls previous functions, wrapping the products in Lemma 2
within the appropriate for loops for the construction of U_{n, k}, which is
applied to the initial state as prescribed.
args:
- `n`: int, number of qubits for the Dicke state;
- `k`: int, hamming weight of states to be included in the superposition;
- `draw` : bool, determines if the circuit is drawn;
- `barrier` : bool, determines if barriers are added to the circuit;
- `only_decomposed` : bool, determines if only the 3-fold decomposed circuit is drawn.
'''
qr = QuantumRegister(n)
qc = QuantumCircuit(qr)
########################################
# initial state
qc.x(qr[-k:])
if barrier:
qc.barrier()
########################################
# applying U_{n, k}
# I didn't create a function to generate a U_{n, k} gate
# because I wanted to keep the possibility of adding barriers,
# which are quite nice for visualizing the circuit and its elements.
# apply first term in Lemma 2
# notice how this range captures exactly the product bounds.
# also, it's very important to invert the range, for the gates
# to be applied in the correct order!!
for l in range(k+1, n+1)[::-1]:
qc.append(first_block(n, k, l), range(n))
if barrier:
qc.barrier()
# apply second term in Lemma 2
for l in range(2, k+1)[::-1]:
qc.append(second_block(n, k, l), range(n))
if barrier:
qc.barrier()
########################################
# drawing
if draw:
# draws only the 3-fold decomposed circuit.
# this opens up to (i) and (ii)_l into its components.
if only_decomposed:
show_figure(qc.decompose().decompose().decompose().draw("mpl"))
else:
show_figure(qc.draw("mpl"))
print()
show_figure(qc.decompose().draw("mpl"))
print()
show_figure(qc.decompose().decompose().draw("mpl"))
print()
show_figure(qc.decompose().decompose().decompose().draw("mpl"))
return qc
n, k = 4, 2
qc = dicke_state(n, k, barrier=True, draw=True, only_decomposed=False)
print(f"\nExpected number of elements in superposition: {scipy.special.comb(n, k):.0f}\n")
test_circuit_sv(qc)
n, k = 5, 3
qc = dicke_state(n, k, barrier=True, draw=True, only_decomposed=False)
print(f"\nExpected number of elements in superposition: {scipy.special.comb(n, k):.0f}\n")
test_circuit_sv(qc)
n, k = 6, 4
qc = dicke_state(n, k, barrier=True, draw=True, only_decomposed=True)
print(f"\nExpected number of elements in superposition: {scipy.special.comb(n, k):.0f}\n")
test_circuit_sv(qc)
n, k = 6, 2
qc = dicke_state(n, k, barrier=True, draw=True, only_decomposed=True)
print(f"\nExpected number of elements in superposition: {scipy.special.comb(n, k):.0f}\n")
test_circuit_sv(qc)
n, k = 7, 4
qc = dicke_state(n, k, barrier=True, draw=True, only_decomposed=True)
print(f"\nExpected number of elements in superposition: {scipy.special.comb(n, k):.0f}\n")
test_circuit_sv(qc, figsize=(16, 4))
|
https://github.com/alexao8/QC-Qiskit
|
alexao8
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
get_ipython().run_line_magic('matplotlib', 'inline')
# Importing standard Qiskit libraries
from qiskit import *
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# In[2]:
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from numpy import pi
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
# In[3]:
circuit.draw(output = 'mpl')
# In[4]:
circuit.h(qr[0])
# In[5]:
circuit.draw(output = 'mpl')
# In[6]:
circuit.cx(qr[0], qr[1])
# In[7]:
circuit.measure(qr,cr)
# In[8]:
circuit.draw(output = 'mpl')
# In[9]:
simulator = Aer.get_backend('qasm_simulator')
# In[10]:
result = execute(circuit, backend = simulator).result()
# In[11]:
plot_histogram(result.get_counts(circuit))
# In[12]:
provider = IBMQ.get_provider('ibm-q')
# In[14]:
qcomp = provider.get_backend('ibmq_16_melbourne')
# In[15]:
job = execute(circuit, backend = qcomp)
# In[ ]:
job_monitor(job)
|
https://github.com/NTU-ALComLab/SliQSim-Qiskit-Interface
|
NTU-ALComLab
|
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Exception for errors raised by SliQSim simulator.
"""
from qiskit import QiskitError
class SliQSimError(QiskitError):
"""Class for errors raised by the SliQSim simulator."""
def __init__(self, *message):
"""Set the error message."""
super().__init__(*message)
self.message = ' '.join(message)
def __str__(self):
"""Return the message."""
return repr(self.message)
|
https://github.com/msramalho/Teach-Me-Quantum
|
msramalho
|
from qiskit_aqua_chemistry import AquaChemistry
from qiskit import IBMQ
IBMQ.load_accounts()
# Input dictionary to configure Qiskit AQUA Chemistry for the chemistry problem.
aqua_chemistry_dict = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': '0.7_sto-3g.hdf5'},
'operator': {'name': 'hamiltonian'},
'algorithm': {'name': 'VQE'},
'optimizer': {'name': 'COBYLA'},
'variational_form': {'name': 'UCCSD'},
'initial_state': {'name': 'HartreeFock'},
'backend': {'name': 'statevector_simulator'}
}
solver = AquaChemistry()
result = solver.run(aqua_chemistry_dict)
print('Ground state energy: {}'.format(result['energy']))
for line in result['printable']:
print(line)
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 14:12:30 2022
@author: pejmanjouzdani
"""
import numpy as np
import pandas as pd
from qiskit import QuantumCircuit
from BasicFunctions.functions import timing, getBinary, getGateStats
from MultiQubitGate.functions import multiqubit
class UpdateCircuit:
def __init__(self,):
pass
def __call__(self, list_j, list_y_j, circ,):
self.circ_new, self.multigate_gate_stat = self.updateCirc(list_j, list_y_j, circ)
# return self.circ_new, self.multigate_gate_stat
@staticmethod
def updateCirc(list_j, list_y_j, circ,):
nspins = circ.num_qubits
circ_P = QuantumCircuit(nspins)
multigate_gate_stat = pd.DataFrame()
for im in range(len(list_j)):
# print('\n8888888888888888 ')
####### imag
m=list_j[im]
h = getBinary(m, nspins)
### imag part
y_j= list_y_j[im].imag
if np.round(y_j, 4)==0:
pass
else:
mult_gate, op_count = multiqubit(h, y_j)
circ_P = circ_P.compose(mult_gate)
####### REAL
### replace 3 1 with Y
y_j= -list_y_j[im].real
h[np.nonzero(h)[0][0]]=2
if np.round(y_j, 4)==0:
pass
else:
mult_gate, op_count =multiqubit(h, y_j)
####### statistics
multigate_gate_stat = pd.concat((multigate_gate_stat,
pd.DataFrame([op_count], index=[m])) )
circ_P = circ_P.compose(mult_gate)
circ_new = circ_P.compose(circ)
return circ_new, multigate_gate_stat
|
https://github.com/ACDuriez/Ising-VQE
|
ACDuriez
|
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from tqdm import tqdm
from scipy.optimize import minimize
from dataclasses import dataclass
from qiskit.providers.fake_provider import FakeManila,FakeQuito,FakeLima,FakeKolkata,FakeNairobi
from qiskit.transpiler import CouplingMap
from qiskit.circuit import QuantumCircuit,ParameterVector,Parameter
from qiskit.circuit.library import EfficientSU2
from qiskit.quantum_info import SparsePauliOp
#from qiskit.opflow import PauliSumOp
from qiskit.primitives import Estimator,Sampler,BackendEstimator
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import SLSQP,COBYLA,L_BFGS_B,QNSPSA,SPSA
from qiskit_aer.noise import NoiseModel
from qiskit_ibm_runtime import Session,Options,QiskitRuntimeService
from qiskit_ibm_runtime import Estimator as IBM_Estimator
from qiskit_ibm_runtime import Sampler as IBM_Sampler
from qiskit_aer.primitives import Estimator as AerEstimator
J = 1
h = 0.5
n_qubits = 4
def get_line_graph(n_qubits):
"""This function creates a linear lattice with
open boundary conditions for a given number of qubits"""
graph_line = nx.Graph()
graph_line.add_nodes_from(range(n_qubits))
edge_list = []
for i in graph_line.nodes:
if i < n_qubits-1:
edge_list.append((i,i+1))
# Generate graph from the list of edges
graph_line.add_edges_from(edge_list)
return graph_line
graph = get_line_graph(n_qubits)
nx.draw_networkx(graph) #plotting the graph
def get_h_op(graph,J=1.,hx=0.5,hz=0.,ap=0.):
"""Creates a general Ising hamiltonian for
given values of the coupling, transverse field,
longitudinal field and antiparallel field
Args:
graph: networkx graph of the lattice
J: uniform coupling between first neighbors
hx: transverse field parameter
hz: longitudinal field parameter
ap: antiparallel field at the boundaries"""
num_qubits = len(graph.nodes())
sparse_list = []
# Uniform Z and X fields
for qubit in graph.nodes():
# X field
coeff = ('X',[qubit],-1*hx)
sparse_list.append(coeff)
# Z field
coeff = ('Z',[qubit],-1*hz)
sparse_list.append(coeff)
# Anti-paralel field at the borders
coeff = ('Z',[0],ap) #this is the positive field (order reversed)
sparse_list.append(coeff)
coeff = ('Z',[num_qubits-1],-1*ap)
sparse_list.append(coeff)
#Interaction field (ZZ)
for i,j in graph.edges():
coeff = ('ZZ',[i,j],-1*J)
sparse_list.append(coeff)
hamiltonian = SparsePauliOp.from_sparse_list(sparse_list,num_qubits=num_qubits).simplify()
return hamiltonian
def get_kk_op(graph):
"""Creates the number of kinks operator"""
sparse_list = []
for i,j in graph.edges():
coeff = ('II',[i,j],0.5)
sparse_list.append(coeff)
coeff = ('ZZ',[i,j],-0.5)
sparse_list.append(coeff)
kk_op = SparsePauliOp.from_sparse_list(sparse_list,num_qubits=len(graph.nodes))
return kk_op
# We show the Hamiltonian with the crittical boundary field as well as
# the number of kinks
print(get_h_op(graph,J,h,ap=np.sqrt(1-h)))
print(get_kk_op(graph))
exact_steps = 70
g_i = 0.
g_f = 1.6
exact_g_values = np.linspace(g_i,g_f,exact_steps)
def get_numpy_results(graph,J,h,g_values):
"""Returns the exact values of the energy and number of kinks
for a given lattice, coupling, transverse field and values of
the boundary field"""
n_qubits = len(graph.nodes())
numpy_solver = NumPyMinimumEigensolver()
E_values = []
kk_values = []
kk_op = get_kk_op(graph) #getting the (g-independent) number of kinks operator
for g in g_values:
h_op = get_h_op(graph,J,h,ap=g) #getting the hamiltonian operator for each g value
result = numpy_solver.compute_minimum_eigenvalue(operator=h_op,aux_operators=[kk_op])
E_values.append(result.eigenvalue)
kk_values.append(np.real(result.aux_operators_evaluated[0][0]))
return E_values,kk_values
exact_E,exact_kk = get_numpy_results(graph,J,h,exact_g_values) # getting the exact energy and number of kinks
#Plotting
f,ax = plt.subplots()
plt.plot(exact_g_values,exact_E)
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
inset_ax = f.add_axes([0.25, 0.3, 0.27, 0.27])# [left, bottom, width, height]
inset_ax.plot(exact_g_values,exact_kk)
inset_ax.set_ylabel('$<N_k>$')
inset_ax.set_xlabel('boundary field')
inset_ax.axvline(x=np.sqrt(1-h), color='red', linestyle='dashed') #indicating the critical boundary field
plt.show()
#Initialize runtime
service = QiskitRuntimeService(
channel='ibm_quantum',
instance='ibm-q/open/main',
token='your_token'
)
backend = service.backend("ibmq_qasm_simulator")
shots = 2**14 # shots for noisy simulations
def get_ansatz_hva(graph, theta_list):
"""Creates the hamiltonian variaitonal ansatz for a given
lattice graph and list of parameters. The parameters list must have a
lenght of 3*n_layers, and must have a form (coupling_i,transverse_i,boundary_i)
Args:
graph: lattice graph
theta_list: list of parameters
"""
n_qubits = len(graph.nodes())
n_layers = len(theta_list)//3
qc = QuantumCircuit(n_qubits)
even_edges = [edge for edge in graph.edges() if edge[0]%2==0]
odd_edges = [edge for edge in graph.edges() if edge[0]%2!=0]
# initial_state
qc.h(range(n_qubits))
for layer_index in range(n_layers):
# Coupling term
for pair in even_edges:
qc.rzz(2 * theta_list[3*layer_index],pair[0],pair[1])
for pair in odd_edges:
qc.rzz(2 * theta_list[3*layer_index],pair[0],pair[1])
# boundary field term
qc.rz(2 *theta_list[3*layer_index+2],0)
qc.rz(-2 * theta_list[3*layer_index+2], n_qubits-1)
# transverse field term
qc.rx(2 * theta_list[3*layer_index+1], range(n_qubits))
return qc
layers_hva = 4
theta_list_hva = ParameterVector('θ',3*layers_hva)
ansatz_hva = get_ansatz_hva(graph,theta_list_hva)
ansatz_hva.draw('mpl',style='iqx')
def get_ansatz_hea(graph,theta_list):
"""Creates the hardware efficient ansatz for a given
lattice graph and list of parameters. The parameters list must have a
lenght of 2*n_qubits_n_layers
Args:
graph: lattice graph
theta_list: list of parameters
"""
nqubits = len(graph.nodes())
n_layers = len(theta_list)//(2*nqubits)
assert len(theta_list)==2*n_qubits*n_layers, "The list of parameters does not have the correct size"
qc = QuantumCircuit(nqubits)
even_edges = [edge for edge in graph.edges() if edge[0]%2==0]
odd_edges = [edge for edge in graph.edges() if edge[0]%2!=0]
reversed_edges = [edge for edge in graph.edges()][::-1]
for layer_index in range(n_layers):
for qubit in range(nqubits):
qc.ry(theta_list[2*(nqubits)*layer_index+qubit], qubit)
# for pair in reversed_edges:
# qc.cnot(pair[0],pair[1])
for pair in even_edges:
qc.cnot(pair[0],pair[1])
for pair in odd_edges:
qc.cnot(pair[0],pair[1])
for qubit in range(nqubits):
qc.ry(theta_list[nqubits+2*(nqubits)*layer_index+qubit], qubit)
return qc
def get_ansatz_hea_ZNE(graph,theta_list):
"""Creates the folded version of hardware efficient ansatz for a given
lattice graph and list of parameters. The parameters list must have a
lenght of 2*n_qubits_n_layers. Used in the ZNE error mitigation protocol
Args:
graph: lattice graph
theta_list: list of parameters
"""
nqubits = len(graph.nodes())
n_layers = len(theta_list)//(2*nqubits)
assert len(theta_list)==2*n_qubits*n_layers, "The list of parameters does not have the correct size"
qc = QuantumCircuit(nqubits)
even_edges = [edge for edge in graph.edges() if edge[0]%2==0]
odd_edges = [edge for edge in graph.edges() if edge[0]%2!=0]
reversed_edges = [edge for edge in graph.edges()][::-1]
for layer_index in range(n_layers):
for qubit in range(nqubits):
qc.ry(theta_list[2*(nqubits)*layer_index+qubit], qubit)
# for pair in reversed_edges:
# qc.cnot(pair[0],pair[1])
#folding even edges
for pair in even_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for pair in even_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for pair in even_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
#folding odd edges
for pair in odd_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for pair in odd_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for pair in odd_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for qubit in range(nqubits):
qc.ry(theta_list[nqubits+2*(nqubits)*layer_index+qubit], qubit)
return qc
# Here we define and show the circuit for the HEA
layers_hea = 1
theta_list = ParameterVector('t',2*n_qubits*layers_hea) # The list of parameters must
ansatz_hea = get_ansatz_hea(graph,theta_list)
ansatz_hea.draw('mpl', style="iqx")
# Here is the folded version of the HEA ansatz for the ZNE
ansatz_hea = get_ansatz_hea_ZNE(graph,theta_list)
ansatz_hea.draw('mpl', style="iqx")
def get_estimator(session,
server='qasm',
shots=2**14,
device=FakeKolkata(),
options_rtm=Options(),
seed=170):
"""Defines an estimator. Set 'qasm' for noiseless, 'noisy' for
backend estimator and 'rtm' for the runtime estimator"""
if server =='qasm':
estimator = Estimator(options={'shots':shots,'seed':seed})
elif server == 'noisy':
estimator = BackendEstimator(device,options={'shots':shots,'seed':seed})
elif server == 'rtm':
estimator = IBM_Estimator(session=session,options=options_rtm)
return estimator
def get_extrapolation(value_k1,value_k2,extrap='lin'):
"""Returns the exponential extrapolation given the
values for k=1 and k=2 noise factors"""
k_values = [1.,2.]
if extrap =='lin':
y_values = [value_k1,value_k2]
# Fit a linear regression model (polynomial of degree 1)
coefficients = np.polyfit(k_values, y_values, 1)
# The coefficients represent the slope (m) and y-intercept (b) of the line
slope, intercept = coefficients
extrapolation = intercept
if extrap == 'exp':
y_values = [np.abs(value_k1/value_k2),1.]
ln_y = np.log(y_values)
# Fit a linear regression model (polynomial of degree 1)
coefficients_exp = np.polyfit(k_values, ln_y, 1)
# The coefficients represent the slope (m) and y-intercept (b) of the line
slope_exp, intercept_exp = coefficients_exp
extrapolation = np.exp(intercept_exp)*value_k2
return extrapolation
def vqe_opt_scipy(graph,
service,
backend,
g=0.7071067811865476,
h=0.5,
ansatz_str='hea',
layers=1,
optimizer='SLSQP',
maxiter=50,
ftol=0.,
reps=1,
zne=False,
extrap='exp',
shots=None,
server='qasm',
device=FakeNairobi(),
options=Options()):
"""Runs the vqe for the Ising model with boundary fields for
a single value of the boundary field, using the scipy optimization function.
It gives data for the convergence of the optimization, which is the logs for
each sampling, the mean and standart deviation of these samplings, and also the
number of function evaluations
Args:
graph: networkx lattice graph
service: service for runtime
backend: backend for runtime (can include quantum backends)
g: value of the boundary field
h: value of the transverse field
ansatz_str: choice of ansatz, 'hea' for HEA and 'hva' for HVA
layers: number of layers for the ansatz
optimizer: optimization algorithm, as string for scipy
maxiter: maximum iterations for the optimization
ftol: tolerance for convergence, for scipy
reps: (int) number of initial parameters samplings
zne: (bool) zne option
extrap: type of extrapolation
shots: number of shots, set to None for statevector simulations
server: 'qasm' for noiseless, 'noisy' for aer, 'rtm' for runtime
device: noise model for noisy simulations
options: Options() class for runtime
"""
n_qubits = len(graph.nodes())
if ansatz_str == 'hea':
theta_list = ParameterVector('θ',2*n_qubits*layers)
ansatz = get_ansatz_hea(graph,theta_list)
ansatz_k2 = get_ansatz_hea_ZNE(graph,theta_list)
elif ansatz_str == 'hva':
theta_list = ParameterVector('θ',3*layers)
ansatz = get_ansatz_hva(graph,theta_list)
ansatz_k2 = get_ansatz_hva(graph,theta_list)
cost_operator = get_h_op(graph,hx=h,ap=g) #Defining Hamiltonian
# Now we set the cost function, with no mitigation, linear or exp extrapolation
if zne == False:
def cost_function_vqe(theta):
job = estimator.run(ansatz, cost_operator, theta)
values = job.result().values[0]
return values
if zne == True:
def cost_function_vqe(theta):
job = estimator.run([ansatz,ansatz_k2], 2*[cost_operator], 2*[theta])
value_k1 = job.result().values[0]
value_k2 = job.result().values[1]
extrapolation = get_extrapolation(value_k1=value_k1,value_k2=value_k2,extrap=extrap)
return extrapolation
log_list = []
nfev_list = []
with Session(service=service,backend=backend) as session:
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
for i in tqdm(range(reps)):
random_point = np.random.random(ansatz.num_parameters)
iter_list = []
result_sample = minimize(cost_function_vqe,
x0=random_point,
method=optimizer,
callback=lambda xk: iter_list.append(list(xk)),
options={'maxiter':maxiter,'disp':False,'ftol':ftol})
iters = len(iter_list)
energy_list = estimator.run(iters*[ansatz],iters*[cost_operator],iter_list).result().values
nfev_list.append(int(result_sample.nfev))
log_list.append(list(energy_list))
session.close()
max_length = max(len(sublist) for sublist in log_list) # Finding the length of the largest list
for sublist in log_list:
if len(sublist) < max_length:
last_element = sublist[-1] # Extracting the last element
sublist.extend([last_element] * (max_length - len(sublist))) # Filling with the last element
mean_list = []
std_list = []
for i in range(len(log_list[0])):
values_list = [l[i] for l in log_list]
mean_list.append(np.mean(values_list))
std_list.append(np.std(values_list))
return log_list,mean_list,std_list,nfev_list
g_mag = 0.2
g_knk = 1.2
E_mag = NumPyMinimumEigensolver().compute_minimum_eigenvalue(get_h_op(graph,ap=g_mag)).eigenvalue
E_knk = NumPyMinimumEigensolver().compute_minimum_eigenvalue(get_h_op(graph,ap=g_knk)).eigenvalue
reps = 5 # we define the number of initial parameters samplings
logs_hva_mag,avgs_hva_mag,stds_hva_mag,nfevs_hva_mag = vqe_opt_scipy(graph=graph,
service=service,
backend=backend,
server='qasm',
g=g_mag,
layers=layers_hva,
ansatz_str='hva',
reps=reps,
maxiter=300,
shots=None,
ftol=1e-16)
avgs_list = avgs_hva_mag
stds_list = stds_hva_mag
g_value = g_mag
exact_energy = E_mag
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
plt.xlim((0,40))
x_lim = 60
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -10, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
logs_hva_knk,avgs_hva_knk,stds_hva_knk,nfevs_hva_knk = vqe_opt_scipy(graph=graph,
service=service,
backend=backend,
server='qasm',
g=g_knk,
layers=layers_hva,
ansatz_str='hva',
reps=reps,
maxiter=300,
shots=None,
ftol=1e-16)
avgs_list = avgs_hva_knk
stds_list = stds_hva_knk
g_value = g_knk
exact_energy = E_knk
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
plt.xlim((0,40))
x_lim = 60
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -10, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
# Here we define a different callback which is suited for the SPSA implementation of qiskit
intermediate_info = {
'nfev': [],
'parameters': [],
'energy': [],
'step_size': [],
'step_sucesss': []
}
def callback(nfev, parameters, energy, step_size,step_sucess):
intermediate_info['nfev'].append(nfev)
intermediate_info['parameters'].append(parameters)
intermediate_info['energy'].append(energy)
intermediate_info['step_size'].append(step_size)
intermediate_info['step_sucess'].append(step_sucess)
@dataclass
class VQELog:
values: list
parameters: list
def update(self, count, parameters, mean, step_size, step_sucess):
self.values.append(mean)
self.parameters.append(parameters)
print(f"Running circuit {count}", end="\r", flush=True)
# Here is the main function
def vqe_critical_spsa(graph,
service,
backend,
device=FakeKolkata(),
g=0.7071067811865476,
layers=1,
server='qasm',
learning_rate=0.07,
perturbation=0.1,
maxiter=200,
hx=0.5,
options=Options(),
zne=False,
extrap='exp',
reps=1,
shots=2**14,
ansatz_str='hea'):
"""Runs the vqe for the Ising model with boundary fields for
a single value of the boundary field, using the scipy optimization function.
It gives data for the convergence of the optimization, which is the logs for
each sampling, the mean and standart deviation of these samplings, and also the
number of function evaluations
Args:
graph: networkx lattice graph
service: service for runtime
backend: backend for runtime (can include quantum backends)
g: value of the boundary field
h: value of the transverse field
ansatz_str: choice of ansatz, 'hea' for HEA and 'hva' for HVA
layers: number of layers for the ansatz
maxiter: maximum iterations for the optimization
learning_rate: learning rate for the SPSA optimizer
perturbation: perturbation for the SPSA optimizer
reps: (int) number of initial parameters samplings
zne: (bool) zne option
extrap: type of extrapolation
shots: number of shots, set to None for statevector simulations
server: 'qasm' for noiseless, 'noisy' for aer, 'rtm' for runtime
device: noise model for noisy simulations
options: Options() class for runtime
"""
n_qubits = len(graph.nodes())
if ansatz_str == 'hea':
theta_list = ParameterVector('θ',2*n_qubits*layers)
ansatz = get_ansatz_hea(graph,theta_list)
ansatz_k2 = get_ansatz_hea_ZNE(graph,theta_list)
elif ansatz_str == 'hva':
theta_list = ParameterVector('θ',3*layers)
ansatz = get_ansatz_hva(graph,theta_list)
ansatz_k2 = get_ansatz_hva(graph,theta_list)
cost_operator = get_h_op(graph,hx=hx,ap=g) #Defining Hamiltonian
# Now we set the cost function, with no mitigation, linear or exp extrapolation
if zne == False:
def cost_function_vqe(theta):
job = estimator.run(ansatz, cost_operator, theta)
values = job.result().values[0]
return values
if zne == True:
def cost_function_vqe(theta):
job = estimator.run([ansatz,ansatz_k2], 2*[cost_operator], 2*[theta])
value_k1 = job.result().values[0]
value_k2 = job.result().values[1]
return get_extrapolation(value_k1=value_k1,value_k2=value_k2,extrap=extrap)
log_list = []
nfev_list = []
with Session(service=service,backend=backend) as session:
# estimator = BackendEstimator(FakeNairobiV2(),options={'shots':shots})
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
for i in tqdm(range(reps)):
log = VQELog([], [])
spsa = SPSA(maxiter=maxiter,
trust_region=True,
learning_rate=learning_rate,
perturbation=perturbation,
callback=log.update)
random_point = np.random.random(ansatz.num_parameters)
result_sample = spsa.minimize(cost_function_vqe,x0=random_point)
log_list.append(log)
nfev_list.append(result_sample.nfev)
session.close()
max_length = max(len(sublist.values) for sublist in log_list) # Finding the length of the largest list
for sublist in log_list:
if len(sublist.values) < max_length:
last_element = sublist[-1] # Extracting the last element
sublist = list(sublist)[:].extend([last_element] * (max_length - len(sublist))) # Filling with the last element
mean_list = []
std_list = []
for i in range(len(log_list[0].values)):
values_list = [log.values[i] for log in log_list]
mean_list.append(np.mean(values_list))
std_list.append(np.std(values_list))
return log_list,mean_list,std_list,nfev_list
logs_hea_noisy_mag,avgs_hea_noisy_mag,stds_hea_noisy_mag,nfevs_hea_noisy_mag = vqe_critical_spsa(graph=graph,
service=service,
backend=backend,
device=FakeKolkata(),
g=g_mag,
server='noisy',
layers=1,
maxiter=170,
ansatz_str='hea',
reps=5,
zne=False,
shots = shots
)
avgs_list = avgs_hea_noisy_mag
stds_list = stds_hea_noisy_mag
g_value = g_mag
exact_energy = E_mag
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization noisy g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -3, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
reps = 3
logs_hea_zne_mag,avgs_hea_zne_mag,stds_hea_zne_mag,nfevs_hea_zne_mag = vqe_critical_spsa(graph=graph,
service=service,
backend=backend,
device=FakeKolkata(),
g=g_mag,
server='noisy',
layers=1,
maxiter=170,
ansatz_str='hea',
reps=reps,
zne=True,
extrap='exp',
shots=shots
)
avgs_list = avgs_hea_zne_mag
stds_list = stds_hea_zne_mag
g_value = g_mag
exact_energy = E_mag
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
x_lim = 60
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization mitigated g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -3, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
logs_hea_noisy_knk,avgs_hea_noisy_knk,stds_hea_noisy_knk,nfevs_hea_noisy_knk = vqe_critical_spsa(graph=graph,
service=service,
backend=backend,
device=FakeKolkata(),
g=g_knk,
server='noisy',
layers=1,
maxiter=170,
ansatz_str='hea',
reps=reps,
zne=False,
shots=shots
)
avgs_list = avgs_hea_noisy_knk
stds_list = stds_hea_noisy_knk
g_value = g_knk
exact_energy = E_knk
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
x_lim = 60
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization noisy g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -3, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
reps = 3
logs_hea_zne_knk,avgs_hea_zne_knk,stds_hea_zne_knk,nfevs_hea_zne_knk = vqe_critical_spsa(graph=graph,
service=service,
backend=backend,
device=FakeKolkata(),
g=g_knk,
server='noisy',
layers=1,
maxiter=170,
ansatz_str='hea',
reps=reps,
zne=True,
extrap='exp',
shots=shots
)
avgs_list = avgs_hea_zne_knk
stds_list = stds_hea_zne_knk
g_value = g_knk
exact_energy = E_knk
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization mitigated g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -3, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
def vqe_phase_diagram(graph,
g_values,
optimizer,
init_optimizer,
service,
backend,
server='qasm',
device=FakeNairobi(),
angles_dict = {},
layers=1,
hx=0.5,
options=Options(),
zne=False,
extrap='exp',
init_reps=1,
shots=2**14,
ansatz_str='hea'):
"""Runs the vqe to simulate the antiparallel model in
the hardware efficient ansatz for different values of
the antiparallel field. Returns the list of energies as
well as a dictionary with the optimal angles for each
value of the boundary field.
Args:
graph: networkx lattice graph
g_values: list of values for the boundary field
angles_dict: dictionary of angles
optimizer: qiskit optimizer class
init_optimizer: optimizer for the first point
layers: layers for the ansatz
service: service for runtime
backend: backend for runtime (can include quantum backends)
h: value of the transverse field
ansatz_str: choice of ansatz, 'hea' for HEA and 'hva' for HVA
reps: number of initial parameters samplings for the first point
zne: (bool) zne option
extrap: type of extrapolation
shots: number of shots, set to None for statevector simulations
server: 'qasm' for noiseless, 'noisy' for aer, 'rtm' for runtime
device: noise model for noisy simulations
options: Options() class for runtime
"""
n_qubits = len(graph.nodes())
if ansatz_str == 'hea':
theta_list = ParameterVector('θ',2*n_qubits*layers)
ansatz = get_ansatz_hea(graph,theta_list)
ansatz_k2 = get_ansatz_hea_ZNE(graph,theta_list)
elif ansatz_str == 'hva':
theta_list = ParameterVector('θ',3*layers)
ansatz = get_ansatz_hva(graph,theta_list)
ansatz_k2 = get_ansatz_hva(graph,theta_list)
E_values = []
rev_g_values = g_values[::-1]
for i,g in enumerate(tqdm(rev_g_values)):
cost_operator = get_h_op(graph,hx=hx,ap=g) #Defining Hamiltonian
# Now we set the cost function, with no mitigation, linear or exp extrapolation
if zne == False:
def cost_function_vqe(theta):
job = estimator.run(ansatz, cost_operator, theta)
values = job.result().values[0]
return values
if zne == True:
def cost_function_vqe(theta):
job = estimator.run([ansatz,ansatz_k2], 2*[cost_operator], 2*[theta])
value_k1 = job.result().values[0]
value_k2 = job.result().values[1]
return get_extrapolation(value_k1=value_k1,value_k2=value_k2,extrap=extrap)
if i == 0:
sample = 0.
for j in range(init_reps): #Performs sampling of initial parameters for the first point
initial_point = np.random.uniform(0., 2*np.pi, size=ansatz.num_parameters)
with Session(service=service,backend=backend) as session:
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
result_sample = init_optimizer.minimize(fun=cost_function_vqe,
x0=initial_point)
session.close()
if result_sample.fun < sample:
sample = result_sample.fun
result = result_sample
initial_point = result.x
else:
with Session(service=service,backend=backend) as session:
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
result = optimizer.minimize(fun=cost_function_vqe,
x0=initial_point)
session.close()
E_values.append(result.fun)
#optimal angles storage
angles = list(result.x)
angles_dict[str(round(g,5))] = angles
return E_values,angles_dict
def vqe_optimal(graph,
service,
backend,
angles_opt,
server='qasm',
device=FakeNairobi(),
layers=1,
hx=0.5,
options=Options(),
zne=False,
extrap='lin',
shots=2**14,
ansatz_str='hea'):
""" Receives the optimal parameters for each value of
the boundary field and runs the circuits to compute the
energy as well as the number of kinks
Args:
graph: networkx lattice graph
g_values: list of values for the boundary field
angles_opt: dictionary of optimal angles
service: service for runtime
backend: backend for runtime (can include quantum backends)
h: value of the transverse field
ansatz_str: choice of ansatz, 'hea' for HEA and 'hva' for HVA
layers: layers for the ansatz
reps: number of initial parameters samplings for the first point
zne: (bool) zne option
extrap: type of extrapolation
shots: number of shots, set to None for statevector simulations
server: 'qasm' for noiseless, 'noisy' for aer, 'rtm' for runtime
device: noise model for noisy simulations
options: Options() class for runtime
Returns:
The values of the energy, number of kinks, and the associated values
of g to facilitate plotting
"""
n_qubits = len(graph.nodes())
g_values = [float(k) for k in angles_opt.keys()]
n_points = len(g_values)
# Setting the ansatz
if ansatz_str == 'hea':
theta_list = ParameterVector('θ',2*n_qubits*layers)
ansatz = get_ansatz_hea(graph,theta_list)
ansatz_k2 = get_ansatz_hea_ZNE(graph,theta_list)
elif ansatz_str == 'hva':
theta_list = ParameterVector('θ',3*layers)
ansatz = get_ansatz_hva(graph,theta_list)
ansatz_k2 = get_ansatz_hva(graph,theta_list)
# Getting the list of angles and hamiltonians
angles_list = []
h_list = []
g_list = []
kk_op = get_kk_op(graph)
E_values = []
kk_values = []
for g_str,angles in angles_opt.items():
g = float(g_str)
g_list.append(g)
h_list.append(get_h_op(graph,hx=hx,ap=g))
angles_list.append(angles)
with Session(service=service,backend=backend) as session:
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
result_h = estimator.run(n_points*[ansatz],h_list,angles_list).result()
result_kk = estimator.run(n_points*[ansatz],n_points*[kk_op],angles_list).result()
if zne == False:
E_values = list(result_h.values)
kk_values = list(result_kk.values)
else:
result_h_k2 = estimator.run(n_points*[ansatz_k2],h_list,angles_list).result()
result_kk_k2 = estimator.run(n_points*[ansatz_k2],n_points*[kk_op],angles_list).result()
for i in range(n_points):
E_values.append(get_extrapolation(result_h.values[i],result_h_k2.values[i],extrap))
kk_values.append(get_extrapolation(result_kk.values[i],result_kk_k2.values[i],extrap))
session.close()
return E_values,kk_values,g_list
# We define the range of values of g used for the VQE implentation
g_values = np.linspace(g_i,g_f,25)
init_reps = 5
slsqp = SLSQP(150)
init_slsqp = SLSQP(150) # We consider more iterations for the first point
E_hva,angles_hva = vqe_phase_diagram(graph=graph,
g_values=g_values,
ansatz_str='hva',
backend=backend,
layers=layers_hva,
optimizer=slsqp,
init_optimizer=init_slsqp,
service=service,
server='qasm',
shots=None,
init_reps=init_reps)
# Now we run the circuits one last time with the optimal parameters
E_hva,kk_hva,g_hva = vqe_optimal(graph=graph,
service=service,
server='qasm',
angles_opt=angles_hva,
ansatz_str='hva',
layers=layers_hva,
backend=backend)
#Plotting
f,ax = plt.subplots()
#plt.plot(g_values,E_3,'ro')
plt.plot(exact_g_values,exact_E,label='exact')
plt.plot(g_hva,E_hva,'ro',label='VQE')
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
plt.legend()
inset_ax = f.add_axes([0.24, 0.22, 0.3, 0.3]) # [left, bottom, width, height]
plt.plot(exact_g_values,exact_kk)
plt.plot(g_hva,kk_hva,'ro',markersize=4)
inset_ax.set_xlabel('boundary field')
inset_ax.set_ylabel("$<N_k>$")
plt.show()
init_reps = 2
spsa = SPSA(maxiter=300,trust_region=True,learning_rate=0.07,perturbation=0.1)
init_spsa = SPSA(maxiter=300,trust_region=True,learning_rate=0.07,perturbation=0.1) # We consider more iterations for the first point
# To perform the whole optimization using ZNE, just set zne = True
# This step took 207 minutes to run on my machine
E_hea_noisy,angles_hea_noisy = vqe_phase_diagram(graph=graph,
g_values=g_values,
ansatz_str='hea',
backend=backend,
layers=layers_hea,
optimizer=spsa,
init_optimizer=init_spsa,
service=service,
server='noisy',
device=FakeKolkata(),
zne=False,
shots=shots,
init_reps=init_reps)
# Now we run the circuits one last time with the optimal parameters
E_opt_hea_noisy,kk_opt_hea_noisy,g_hea = vqe_optimal(graph=graph,
service=service,
server='noisy',
angles_opt=angles_hea_noisy,
device=FakeKolkata(),
ansatz_str='hea',
layers=layers_hea,
zne=False,
backend=backend,
shots=shots)
#Plotting
f,ax = plt.subplots()
#plt.plot(g_values,E_3,'ro')
plt.plot(exact_g_values,exact_E,label='exact')
plt.plot(g_hea,E_opt_hea_noisy,'o',label='noisy')
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
plt.legend()
inset_ax = f.add_axes([0.24, 0.22, 0.3, 0.3]) # [left, bottom, width, height]
plt.plot(exact_g_values,exact_kk)
plt.plot(g_hea,kk_opt_hea_noisy,'o',markersize=4)
inset_ax.set_xlabel('boundary field')
inset_ax.set_ylabel("$<N_k>$")
plt.show()
# Now we run the circuits now using ZNE
E_opt_hea_mitigated,kk_opt_hea_mitigated,g_hea = vqe_optimal(graph=graph,
service=service,
server='noisy',
angles_opt=angles_hea_noisy,
device=FakeKolkata(),
ansatz_str='hea',
layers=layers_hea,
zne=True,
extrap='exp',
backend=backend,
shots=shots)
#Plotting
f,ax = plt.subplots()
#plt.plot(g_values,E_3,'ro')
plt.plot(exact_g_values,exact_E,label='exact')
plt.plot(g_hea,E_opt_hea_noisy,'o',label='noisy')
plt.plot(g_hea,E_opt_hea_mitigated,'o',label='mitigated')
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
plt.legend()
inset_ax = f.add_axes([0.24, 0.22, 0.3, 0.3]) # [left, bottom, width, height]
plt.plot(exact_g_values,exact_kk)
plt.plot(g_hea,kk_opt_hea_noisy,'o',markersize=4)
plt.plot(g_hea,kk_opt_hea_mitigated,'o',markersize=4)
inset_ax.set_xlabel('boundary field')
inset_ax.set_ylabel("$<N_k>$")
plt.show()
# First we get the optimal parameters with statevector simulations
E_hea_noiseless,angles_hea_noiseless = vqe_phase_diagram(graph=graph,
g_values=g_values,
ansatz_str='hea',
backend=backend,
layers=layers_hea,
optimizer=spsa,
init_optimizer=init_spsa,
service=service,
server='qasm',
shots=None,
init_reps=init_reps)
# Setting options for runtime
# Noisy options
fake_device = FakeKolkata()
noise_model = NoiseModel.from_backend(fake_device)
options_noisy = Options()
options_noisy.execution.shots = shots
options_noisy.simulator = {
"noise_model": noise_model,
"basis_gates": fake_device.configuration().basis_gates,
"coupling_map": fake_device.configuration().coupling_map,
"seed_simulator": 42
}
options_noisy.optimization_level = 3 # no optimization
options_noisy.resilience_level = 0 # M3 for Sampler and T-REx for Estimator
# Mitigated options
options_mitigated = Options()
options_mitigated.execution.shots = shots
options_mitigated.simulator = {
"noise_model": noise_model,
"basis_gates": fake_device.configuration().basis_gates,
"coupling_map": fake_device.configuration().coupling_map
}
# Set number of shots, optimization_level and resilience_level
options_mitigated.optimization_level = 3
options_mitigated.resilience_level = 1 # setting T-REX
# Now we run the circuits in runtime with the optimal parameters
# To run on runtime we set server = 'rtm'
# First we run the unmitigated results
E_opt_hea_noisy_rtm,kk_opt_hea_noisy_rtm,g_hea = vqe_optimal(graph=graph,
service=service,
server='rtm',
options = options_noisy,
angles_opt=angles_hea_noiseless,
ansatz_str='hea',
layers=layers_hea,
zne=False,
extrap='exp',
backend=backend,
shots=shots)
# Now we run using ZNE and ZNE+T-REX
# ZNE
E_opt_hea_mitigated1_rtm,kk_opt_hea_mitigated1_rtm,g_hea = vqe_optimal(graph=graph,
service=service,
server='rtm',
options = options_noisy,
angles_opt=angles_hea_noiseless,
ansatz_str='hea',
layers=layers_hea,
zne=True,
extrap='exp',
backend=backend,
shots=shots)
# ZNE + T-REX
E_opt_hea_mitigated2_rtm,kk_opt_hea_mitigated2_rtm,g_hea = vqe_optimal(graph=graph,
service=service,
server='rtm',
options = options_mitigated,
angles_opt=angles_hea_noiseless,
ansatz_str='hea',
layers=layers_hea,
zne=True,
extrap='exp',
backend=backend,
shots=shots)
#Plotting
f,ax = plt.subplots()
#plt.plot(g_values,E_3,'ro')
plt.plot(exact_g_values,exact_E,label='exact')
plt.plot(g_hea,E_opt_hea_noisy_rtm,'o',label='noisy')
plt.plot(g_hea,E_opt_hea_mitigated1_rtm,'o',label='ZNE')
plt.plot(g_hea,E_opt_hea_mitigated2_rtm,'o',label='ZNE+T-REX')
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
plt.legend()
inset_ax = f.add_axes([0.24, 0.22, 0.3, 0.3]) # [left, bottom, width, height]
plt.plot(exact_g_values,exact_kk)
plt.plot(g_hea,kk_opt_hea_noisy_rtm,'o',markersize=4)
plt.plot(g_hea,kk_opt_hea_mitigated1_rtm,'o',markersize=4)
plt.plot(g_hea,kk_opt_hea_mitigated2_rtm,'o',markersize=4)
inset_ax.set_xlabel('boundary field')
inset_ax.set_ylabel("$<N_k>$")
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw
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)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
%run qlatvia.py
draw_qubit()
# line of reflection for Hadamard
from matplotlib.pyplot import arrow
arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red')
sqrttwo=2**0.5
draw_quantum_state(0,1,"")
draw_quantum_state(1/sqrttwo,-1/sqrttwo,"|->")
%run qlatvia.py
draw_qubit()
# line of reflection for Hadamard
from matplotlib.pyplot import arrow
arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red')
sqrttwo=2**0.5
draw_quantum_state(-1,0,"")
draw_quantum_state(-1/sqrttwo,-1/sqrttwo,"-|+>")
%run qlatvia.py
draw_qubit()
# line of reflection for Hadamard
from matplotlib.pyplot import arrow
arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red')
sqrttwo=2**0.5
draw_quantum_state(0,-1,"")
draw_quantum_state(-1/sqrttwo,1/sqrttwo,"-|->")
# randomly create a 2-dimensional quantum state
from math import cos, sin, pi
from random import randrange
def random_quantum_state2():
angle_degree = randrange(360)
angle_radian = 2*pi*angle_degree/360
return [cos(angle_radian),sin(angle_radian)]
%run qlatvia.py
draw_qubit()
# line of reflection for Hadamard
from matplotlib.pyplot import arrow
arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red')
[x1,y1] = random_quantum_state2()
print(x1,y1)
sqrttwo=2**0.5
oversqrttwo = 1/sqrttwo
[x2,y2] = [ oversqrttwo*x1 + oversqrttwo*y1 , oversqrttwo*x1 - oversqrttwo*y1 ]
print(x2,y2)
draw_quantum_state(x1,y1,"main")
draw_quantum_state(x2,y2,"ref")
# randomly create a 2-dimensional quantum state
from math import cos, sin, pi
from random import randrange
def random_quantum_state2():
angle_degree = randrange(360)
angle_radian = 2*pi*angle_degree/360
return [cos(angle_radian),sin(angle_radian)]
%run qlatvia.py
draw_qubit()
[x1,y1] = random_quantum_state2()
[x2,y2] = [x1,-y1]
draw_quantum_state(x1,y1,"main")
draw_quantum_state(x2,y2,"ref")
# randomly create a 2-dimensional quantum state
from math import cos, sin, pi
from random import randrange
def random_quantum_state2():
angle_degree = randrange(360)
angle_radian = 2*pi*angle_degree/360
return [cos(angle_radian),sin(angle_radian)]
%run qlatvia.py
draw_qubit()
# the line y=x
from matplotlib.pyplot import arrow
arrow(-1,-1,2,2,linestyle='dotted',color='red')
[x1,y1] = random_quantum_state2()
[x2,y2] = [y1,x1]
draw_quantum_state(x1,y1,"main")
draw_quantum_state(x2,y2,"ref")
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
### replaced x gate ###
qc.x(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### replaced x gate ###
qc.x(1)
return qc
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import MCXGate
gate = MCXGate(4)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(5)
circuit.append(gate, [0, 1, 4, 2, 3])
circuit.draw('mpl')
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
import qiskit
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from tsp_qaoa import marina_solution
G=nx.Graph()
i=1
G.add_node(i,pos=(i,i))
G.add_node(2,pos=(2,2))
G.add_node(3,pos=(1,0))
G.add_edge(1,2,weight=20.5)
G.add_edge(1,3,weight=9.8)
pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
def append_zz_term(qc,q1,q2,gamma):
qc.cx(q1,q2)
qc.rz(2*gamma,q2)
qc.cx(q1,q2)
def get_cost_circuit(G,gamma):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for i,j in G.edges():
append_zz_term(qc,i,j,gamma)
return qc
#print(get_cost_circuit(G,0.5))
def append_x_term(qc,q1,beta):
qc.rx(2*beta,q1)
def get_mixer_operator(G,beta):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for n in G.nodes():
append_x_term(qc,n,beta)
return qc
#print(get_mixer_operator(G,0.5))
def get_QAOA_circuit(G,beta,gamma):
assert(len(beta)==len(gamma))
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
qc.h(range(N))
p=len(beta)
#aplicamos las p rotaciones
for i in range(p):
qc=qc.compose(get_cost_circuit(G,gamma[i]))
qc=qc.compose(get_mixer_operator(G,beta[i]))
qc.barrier(range(N))
qc.measure(range(N),range(N))
return qc
print(get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6]))
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
qc=get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6])
backend=Aer.get_backend('qasm_simulator')
job=execute(qc,backend)
result=job.result()
print(invert_counts(result.get_counts()))
def maxcut_obj(x,G):
cut=0
for i,j in G.edges():
if x[i]!=x[j]:
cut = cut-1
return cut
print(maxcut_obj("00011",G))
def compute_maxcut_energy(counts,G):
energy=0
get_counts=0
total_counts=0
for meas, meas_count in counts.items():
obj_for_meas=maxcut_obj(meas,G)
energy+=obj_for_meas*meas_count
total_counts+=meas_count
return energy/total_counts
def get_black_box_objective(G,p):
backend=Aer.get_backend('qasm_simulator')
def f(theta):
beta=theta[:p]
gamma=theta[p:]
qc=get_QAOA_circuit(G,beta,gamma)
counts=execute(qc,backend,seed_simulator=10).result().get_counts()
return compute_maxcut_energy(invert_counts(counts),G)
return f
p=5
obj=get_black_box_objective(G,p)
init_point=np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1])#([2,2,1,1,1,1,1,1,1,1])
res_sample=minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
res_sample
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
cantidad_ciudades = 4
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
pos=nx.spring_layout(G)
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
G
pos=nx.get_node_attributes(G,'weight')
pos
labels = nx.get_edge_attributes(G,'weight')
labels
def funcion_costo(multiplicador_lagrange, cantidad_ciudades, pesos, conexiones ):
N = G.number_of_nodes()
N_square = N^2
# restriccion 1
for i in range(cantidad_ciudades):
cur = sI(N_square)
for j in range(num_cities):
cur -= D(i, j)
ret += cur**2
# retorna el indice de qubit por conversion al problema
def quibit_indice(i, l, N):
return i * N + l
from qiskit.quantum_info.operators import Operator, Pauli
# Create an operator
XX = Operator(Pauli(label='XX'))
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(XX, [0, 1])
circ.measure([0,1], [0,1])
circ.draw('mpl')
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(a, [0])
#circ.measure([0,1], [0,1])
circ.draw('mpl')
a = I - ( 0.5*(I+ Z))**2
a = Operator(a)
a.is_unitary()
print(I @ Z)
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for the wrapper functionality."""
import io
import unittest
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import BasicAer
from qiskit import execute
from qiskit.tools.monitor import job_monitor
from qiskit.test import QiskitTestCase
class TestJobMonitor(QiskitTestCase):
"""Tools test case."""
def test_job_monitor(self):
"""Test job_monitor"""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
qc = QuantumCircuit(qreg, creg)
qc.h(qreg[0])
qc.cx(qreg[0], qreg[1])
qc.measure(qreg, creg)
backend = BasicAer.get_backend("qasm_simulator")
job_sim = execute([qc] * 10, backend)
output = io.StringIO()
job_monitor(job_sim, output=output)
self.assertEqual(job_sim.status().name, "DONE")
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua.components.reciprocals import Reciprocal
from qiskit.aqua.circuits.gates import mct
class LongDivision(Reciprocal):
"""The Long Division Rotation for Reciprocals.
It finds the reciprocal with long division method and rotates the ancillary
qubit by C/lambda. This is a first order approximation of arcsin(C/lambda).
"""
CONFIGURATION = {
'name': 'LongDivision',
'description': 'reciprocal computation with long division and rotation of the ancilla qubit',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'reciprocal_long_division_schema',
'type': 'object',
'properties': {
'negative_evals': {
'type': 'boolean',
'default': False
},
'scale': {
'type': 'number',
'default': 0,
},
'precision': {
'type': ['integer', 'null'],
'default': None,
},
'evo_time': {
'type': ['number', 'null'],
'default': None
},
'lambda_min': {
'type': ['number', 'null'],
'default': None
}
},
'additionalProperties': False
},
}
def __init__(
self,
scale=0,
precision=None,
negative_evals=False,
evo_time=None,
lambda_min=None
):
"""Constructor.
Args:
scale (float, optional): the scale of rotation angle, corresponds to HHL constant C
precision (int, optional): number of qubits that defines the precision of long division
negative_evals (bool, optional): indicate if negative eigenvalues need to be handled
evo_time (float, optional): the evolution time
lambda_min (float, optional): the smallest expected eigenvalue
"""
self.validate(locals())
super().__init__()
self._negative_evals = negative_evals
self._scale = scale
self._precision = precision
self._evo_time = evo_time
self._lambda_min = lambda_min
self._circuit = None
self._ev = None
self._rec = None
self._anc = None
self._reg_size = 0
self._neg_offset = 0
self._n = 0
def sv_to_resvec(self, statevector, num_q):
half = int(len(statevector) / 2)
sv_good = statevector[half:]
vec = np.array([])
for i in range(2 ** num_q):
vec = np.append(vec, sum(x for x in sv_good[i::2 ** num_q]))
return vec
def _ld_circuit(self):
def subtract(a, b, b0, c, z,r, rj, n):
qc = QuantumCircuit(a, b0, b, c, z, r)
qc2 = QuantumCircuit(a, b0, b ,c, z,r)
def subtract_in(qc, a, b, b0, c , z, r, n):
"""subtraction realized with ripple carry adder"""
def maj(p, a, b, c):
p.cx(c, b)
p.cx(c, a)
p.ccx(a, b, c)
def uma(p, a, b, c):
p.ccx(a, b, c)
p.cx(c, a)
p.cx(a, b)
for i in range(n):
qc.x(a[i])
maj(qc, c[0], a[0], b[n-2])
for i in range(n-2):
maj(qc, b[n-2-i+self._neg_offset], a[i+1], b[n-3-i+self._neg_offset])
maj(qc, b[self._neg_offset+0], a[n-1], b0[0])
qc.cx(a[n-1], z[0])
uma(qc, b[self._neg_offset+0], a[n-1], b0[0])
for i in range(2, n):
uma(qc, b[self._neg_offset+i-1], a[n-i], b[self._neg_offset+i-2])
uma(qc, c[0], a[0], b[n-2+self._neg_offset])
for i in range(n):
qc.x(a[i])
qc.x(z[0])
def u_maj(p, a, b, c, r):
p.ccx(c, r, b)
p.ccx(c, r, a)
p.mct([r, a, b], c, None, mode='noancilla')
def u_uma(p, a, b, c, r):
p.mct([r, a, b], c, None, mode='noancilla')
p.ccx(c,r, a)
p.ccx(a, r, b)
def unsubtract(qc2, a, b, b0, c, z, r, n):
"""controlled inverse subtraction to uncompute the registers(when
the result of the subtraction is negative)"""
for i in range(n):
qc2.cx(r, a[i])
u_maj(qc2, c[0], a[0], b[n-2],r)
for i in range(n-2):
u_maj(qc2, b[n-2-i+self._neg_offset], a[i+1], b[n-3-i+self._neg_offset], r)
u_maj(qc2, b[self._neg_offset+0], a[n-1], b0[0], r)
qc2.ccx(a[n-1],r, z[0])
u_uma(qc2, b[self._neg_offset+0], a[n-1], b0[0], r)
for i in range(2, n):
u_uma(qc2, b[self._neg_offset+i-1], a[n-i], b[self._neg_offset+i-2], r)
u_uma(qc2, c[0], a[0], b[n-2+self._neg_offset], r)
for i in range(n):
qc2.cx(r, a[i])
un_qc = qc2.mirror()
un_qc.cx(r, z[0])
return un_qc
# assembling circuit for controlled subtraction
subtract_in(qc, a, b, b0, c, z, r[rj], n)
qc.x(a[n-1])
qc.cx(a[n-1], r[rj])
qc.x(a[n-1])
qc.x(r[rj])
qc += unsubtract(qc2, a, b, b0, c, z, r[rj], n)
qc.x(r[rj])
return qc
def shift_to_one(qc, b, anc, n):
"""controlled bit shifting for the initial alignment of the most
significant bits """
for i in range(n-2): # set all the anc1 qubits to 1
qc.x(anc[i])
for j2 in range(n-2): # if msb is 1, change ancilla j2 to 0
qc.cx(b[0+self._neg_offset], anc[j2])
for i in np.arange(0,n-2):
i = int(i) # which activates shifting with the 2 Toffoli gates
qc.ccx(anc[j2], b[i+1+self._neg_offset], b[i+self._neg_offset])
qc.ccx(anc[j2], b[i+self._neg_offset], b[i+1+self._neg_offset])
for i in range(n-2): # negate all the ancilla
qc.x(anc[i])
def shift_one_left(qc, b, n):
for i in np.arange(n-1,0, -1):
i = int(i)
qc.cx(b[i-1], b[i])
qc.cx(b[i], b[i-1])
def shift_one_leftc(qc, b, ctrl, n):
for i in np.arange(n-2,0, -1):
i = int(i)
qc.ccx(ctrl, b[i-1], b[i])
qc.ccx(ctrl, b[i], b[i-1])
return qc
def shift_one_rightc(qc, b, ctrl, n):
for i in np.arange(0, n-1):
i = int(i)
qc.ccx(ctrl, b[n-2-i+self._neg_offset], b[n-1-i+self._neg_offset])
qc.ccx(ctrl, b[n-1-i+self._neg_offset], b[n-2-i+self._neg_offset])
# executing long division:
self._circuit.x(self._a[self._n-2])
shift_to_one(self._circuit, self._ev, self._anc1, self._n) #initial alignment of most significant bits
for rj in range(self._precision): # iterated subtraction and shifting
self._circuit += subtract(self._a, self._ev, self._b0, self._c,
self._z, self._rec, rj, self._n)
shift_one_left(self._circuit, self._a, self._n)
for ish in range(self._n-2): # unshifting due to initial alignment
shift_one_leftc(self._circuit, self._rec, self._anc1[ish],
self._precision + self._num_ancillae)
self._circuit.x(self._anc1[ish])
shift_one_rightc(self._circuit, self._ev, self._anc1[ish], self._num_ancillae)
self._circuit.x(self._anc1[ish])
def _rotation(self):
qc = self._circuit
rec_reg = self._rec
ancilla = self._anc
if self._negative_evals:
for i in range(0, self._precision + self._num_ancillae):
qc.cu3(self._scale*2**(-i), 0, 0, rec_reg[i], ancilla)
qc.cu3(2*np.pi, 0, 0, self._ev[0], ancilla) #correcting the sign
else:
for i in range(0, self._precision + self._num_ancillae):
qc.cu3(self._scale*2**(-i), 0, 0, rec_reg[i], ancilla)
self._circuit = qc
self._rec = rec_reg
self._anc = ancilla
def construct_circuit(self, mode, inreg):
"""Construct the Long Division Rotation circuit.
Args:
mode (str): consctruction mode, 'matrix' not supported
inreg (QuantumRegister): input register, typically output register of Eigenvalues
Returns:
QuantumCircuit containing the Long Division Rotation circuit.
"""
if mode == 'matrix':
raise NotImplementedError('The matrix mode is not supported.')
self._ev = inreg
if self._scale == 0:
self._scale = 2**-len(inreg)
if self._negative_evals:
self._neg_offset = 1
self._num_ancillae = len(self._ev) - self._neg_offset
if self._num_ancillae < 3:
self._num_ancillae = 3
if self._negative_evals == True:
if self._num_ancillae < 4:
self._num_ancillae = 4
self._n = self._num_ancillae + 1
if self._precision is None:
self._precision = self._num_ancillae
self._a = QuantumRegister(self._n, 'one') #register storing 1
self._b0 = QuantumRegister(1, 'b0') #extension of b - required by subtraction
self._anc1 = QuantumRegister(self._num_ancillae-1, 'algn_anc') # ancilla for the initial shifting
self._z = QuantumRegister(1, 'z') #subtraction overflow
self._c = QuantumRegister(1, 'c') #carry
self._rec = QuantumRegister(self._precision + self._num_ancillae, 'res') #reciprocal result
self._anc = QuantumRegister(1, 'anc')
qc = QuantumCircuit(self._a, self._b0, self._ev, self._anc1, self._c,
self._z, self._rec, self._anc)
self._circuit = qc
self._ld_circuit()
self._rotation()
return self._circuit
|
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.
"""
Special data types.
"""
from enum import Enum
from typing import NamedTuple, List, Union, NewType, Tuple, Dict
from qiskit import circuit
ScheduledGate = NamedTuple(
"ScheduledGate",
[
("t0", int),
("operand", circuit.Gate),
("duration", int),
("bits", List[Union[circuit.Qubit, circuit.Clbit]]),
("bit_position", int),
],
)
ScheduledGate.__doc__ = "A gate instruction with embedded time."
ScheduledGate.t0.__doc__ = "Time when the instruction is issued."
ScheduledGate.operand.__doc__ = "Gate object associated with the gate."
ScheduledGate.duration.__doc__ = "Time duration of the instruction."
ScheduledGate.bits.__doc__ = "List of bit associated with the gate."
ScheduledGate.bit_position.__doc__ = "Position of bit associated with this drawing source."
GateLink = NamedTuple(
"GateLink", [("t0", int), ("opname", str), ("bits", List[Union[circuit.Qubit, circuit.Clbit]])]
)
GateLink.__doc__ = "Dedicated object to represent a relationship between instructions."
GateLink.t0.__doc__ = "A position where the link is placed."
GateLink.opname.__doc__ = "Name of gate associated with this link."
GateLink.bits.__doc__ = "List of bit associated with the instruction."
Barrier = NamedTuple(
"Barrier",
[("t0", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int)],
)
Barrier.__doc__ = "Dedicated object to represent a barrier instruction."
Barrier.t0.__doc__ = "A position where the barrier is placed."
Barrier.bits.__doc__ = "List of bit associated with the instruction."
Barrier.bit_position.__doc__ = "Position of bit associated with this drawing source."
HorizontalAxis = NamedTuple(
"HorizontalAxis", [("window", Tuple[int, int]), ("axis_map", Dict[int, int]), ("label", str)]
)
HorizontalAxis.__doc__ = "Data to represent configuration of horizontal axis."
HorizontalAxis.window.__doc__ = "Left and right edge of graph."
HorizontalAxis.axis_map.__doc__ = "Mapping of apparent coordinate system and actual location."
HorizontalAxis.label.__doc__ = "Label of horizontal axis."
class BoxType(str, Enum):
"""Box type.
SCHED_GATE: Box that represents occupation time by gate.
DELAY: Box associated with delay.
TIMELINE: Box that represents time slot of a bit.
"""
SCHED_GATE = "Box.ScheduledGate"
DELAY = "Box.Delay"
TIMELINE = "Box.Timeline"
class LineType(str, Enum):
"""Line type.
BARRIER: Line that represents barrier instruction.
GATE_LINK: Line that represents a link among gates.
"""
BARRIER = "Line.Barrier"
GATE_LINK = "Line.GateLink"
class SymbolType(str, Enum):
"""Symbol type.
FRAME: Symbol that represents zero time frame change (Rz) instruction.
"""
FRAME = "Symbol.Frame"
class LabelType(str, Enum):
"""Label type.
GATE_NAME: Label that represents name of gate.
DELAY: Label associated with delay.
GATE_PARAM: Label that represents parameter of gate.
BIT_NAME: Label that represents name of bit.
"""
GATE_NAME = "Label.Gate.Name"
DELAY = "Label.Delay"
GATE_PARAM = "Label.Gate.Param"
BIT_NAME = "Label.Bit.Name"
class AbstractCoordinate(Enum):
"""Abstract coordinate that the exact value depends on the user preference.
RIGHT: The horizontal coordinate at t0 shifted by the left margin.
LEFT: The horizontal coordinate at tf shifted by the right margin.
TOP: The vertical coordinate at the top of the canvas.
BOTTOM: The vertical coordinate at the bottom of the canvas.
"""
RIGHT = "RIGHT"
LEFT = "LEFT"
TOP = "TOP"
BOTTOM = "BOTTOM"
class Plotter(str, Enum):
"""Name of timeline plotter APIs.
MPL: Matplotlib plotter interface. Show timeline in 2D canvas.
"""
MPL = "mpl"
# convenient type to represent union of drawing data
DataTypes = NewType("DataType", Union[BoxType, LabelType, LineType, SymbolType])
# convenient type to represent union of values to represent a coordinate
Coordinate = NewType("Coordinate", Union[float, AbstractCoordinate])
# Valid bit objects
Bits = NewType("Bits", Union[circuit.Qubit, circuit.Clbit])
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# let's define the vectors
v=[-3,4,-5,6]
u=[4,3,6,5]
vu = 0
for i in range(len(v)):
vu = vu + v[i]*u[i]
print(v,u,vu)
u = [-3,-4]
uu = u[0]*u[0] + u[1]*u[1]
print(u,u,uu)
u = [-3,-4]
neg_u=[3,4]
v=[-4,3]
neg_v=[4,-3]
# let's define a function for inner product
def inner(v_one,v_two):
summation = 0
for i in range(len(v_one)):
summation = summation + v_one[i]*v_two[i] # adding up pairwise multiplications
return summation # return the inner product
print("inner product of u and -v (",u," and ",neg_v,") is",inner(u,neg_v))
print("inner product of -u and v (",neg_u," and ",v,") is",inner(neg_u,v))
print("inner product of -u and -v (",neg_u," and ",neg_v,") is",inner(neg_u,neg_v))
# let's define a function for inner product
def inner(v_one,v_two):
summation = 0
for i in range(len(v_one)):
summation = summation + v_one[i]*v_two[i] # adding up pairwise multiplications
return summation # return the inner product
v = [-1,2,-3,4]
v_neg_two=[2,-4,6,-8]
u=[-2,-1,5,2]
u_three=[-6,-3,15,6]
print("inner product of v and u is",inner(v,u))
print("inner product of -2v and 3u is",inner(v_neg_two,u_three))
|
https://github.com/HuangJunye/Qiskit-for-GameDev
|
HuangJunye
|
#!/usr/bin/env python3
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, Aer, execute
def run_qasm(qasm, backend_to_run="qasm_simulator"):
qc = QuantumCircuit.from_qasm_str(qasm)
backend = Aer.get_backend(backend_to_run)
job_sim = execute(qc, backend)
sim_result = job_sim.result()
return sim_result.get_counts(qc)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.barrier()
circuit.h(0)
circuit = RemoveBarriers()(circuit)
circuit.draw('mpl')
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.circuit import Gate
# Define no. of message qubits
n = 10
# Alice's end
alice_prepare = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
alice_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
circ = QuantumCircuit(n, n)
# Preparation
circ.reset(range(n))
for i in range(n):
if alice_prepare[i] == 1:
circ.x(i)
circ.barrier()
# Hadamard Transform
for i in range(n):
if alice_hadamard[i] == 1:
circ.h(i)
circ.barrier()
# Eavesdropper
circ.append(Gate(name="$Eve$", num_qubits=n, params=[]), range(n))
# Bob's end
bob_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
circ.barrier()
# Hadamard Transform
for i in range(n):
if bob_hadamard[i] == 1:
circ.h(i)
circ.barrier()
# Measurement
circ.measure(range(n), range(n))
circ.draw('mpl', reverse_bits=True, scale=0.45)
# Alice's end
alice_prepare = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
alice_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
circ = QuantumCircuit(n, n)
# Preparation
circ.reset(range(n))
for i in range(n):
if alice_prepare[i] == 1:
circ.x(i)
circ.barrier()
# Hadamard Transform
for i in range(n):
if alice_hadamard[i] == 1:
circ.h(i)
circ.barrier()
# Bob's end
bob_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
# Hadamard Transform
for i in range(n):
if bob_hadamard[i] == 1:
circ.h(i)
circ.barrier()
# Measurement
circ.measure(range(n), range(n))
circ.draw('mpl', reverse_bits=True, scale=0.45)
# Execute Circuit
backend = Aer.get_backend('qasm_simulator')
job = execute(circ, backend, shots=1)
counts = job.result().get_counts(circ)
bob_measure = list(counts.keys())[0][::-1]
# Print Data
print("".join(["Alice Prepared: ","".join([str(i) for i in alice_prepare])]))
print("".join(["Alice H Transforms: ","".join([str(i) for i in alice_hadamard])]))
print("".join(["Bob H Transforms: ","".join([str(i) for i in bob_hadamard])]))
print("".join(["Bob Measurements: ", bob_measure]))
# Extract Key
alice_key = []
bob_key = []
for i in range(n):
if alice_hadamard[i]==bob_hadamard[i]:
alice_key.append(int(alice_prepare[i]))
bob_key.append(int(bob_measure[i]))
# Print Keys
print("".join(["Alice extracts key as: ","".join([str(i) for i in alice_key])]))
print("".join(["Bob extracts key as: ","".join([str(i) for i in bob_key])]))
# Alice's end
alice_prepare = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
alice_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
circ = QuantumCircuit(n, 2*n)
# Preparation
circ.reset(range(n))
for i in range(n):
if alice_prepare[i] == 1:
circ.x(i)
circ.barrier()
# Hadamard Transform
for i in range(n):
if alice_hadamard[i] == 1:
circ.h(i)
circ.barrier()
# Eavesdropper
circ.measure(range(n), range(n))
# Bob's end
bob_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
circ.barrier()
# Hadamard Transform
for i in range(n):
if bob_hadamard[i] == 1:
circ.h(i)
circ.barrier()
# Measurement
circ.measure(range(n), range(n,2*n))
circ.draw('mpl', reverse_bits=True, scale=0.45)
# Execute Circuit
backend = Aer.get_backend('qasm_simulator')
job = execute(circ, backend, shots=1)
counts = job.result().get_counts(circ)
measure_data = list(counts.keys())[0][::-1]
eve_measure = measure_data[0:n]
bob_measure = measure_data[n:2*n]
# Print Data
print("".join(["Alice Prepared: ","".join([str(i) for i in alice_prepare])]))
print("".join(["Alice H Transforms: ","".join([str(i) for i in alice_hadamard])]))
print("".join(["Eve Measurements: ", eve_measure]))
print("".join(["Bob H Transforms: ","".join([str(i) for i in bob_hadamard])]))
print("".join(["Bob Measurements: ", bob_measure]))
# Extract Key
alice_key = []
bob_key = []
for i in range(n):
if alice_hadamard[i]==bob_hadamard[i]:
alice_key.append(int(alice_prepare[i]))
bob_key.append(int(bob_measure[i]))
# Print Keys
print("".join(["Alice extracts key as: ","".join([str(i) for i in alice_key])]))
print("".join(["Bob extracts key as: ","".join([str(i) for i in bob_key])]))
|
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
# our backend is the Pulse Simulator
from resources import helper
from qiskit.providers.aer import PulseSimulator
backend_sim = PulseSimulator()
# sample duration for pulse instructions
dt = 1e-9
# create the model
duffing_model = helper.get_transmon(dt)
# get qubit frequency from Duffing model
qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift()
import numpy as np
# visualization tools
import matplotlib.pyplot as plt
plt.style.use('dark_background')
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3 # kilohertz
us = 1.0e-6 # microseconds
ns = 1.0e-9 # nanoseconds
from qiskit import pulse
from qiskit.pulse import Play, Acquire
from qiskit.pulse.pulse_lib import GaussianSquare
# qubit to be used throughout the notebook
qubit = 0
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Construct a measurement schedule and add it to an InstructionScheduleMap
meas_samples = 1200
meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150)
measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit))
inst_map = pulse.InstructionScheduleMap()
inst_map.add('measure', [qubit], measure_sched)
# save the measurement/acquire pulse for later
measure = inst_map.get('measure', qubits=[qubit])
from qiskit.pulse import pulse_lib
def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma):
### create a Rabi schedule (already done)
### create a Gaussian Rabi pulse using pulse_lib
### play Rabi pulse on the Rabi schedule and return
rabi_schedule = pulse.Schedule(name='rabi_experiment')
### WRITE YOUR CODE BETWEEN THESE LINES - START
rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp,
sigma=drive_sigma)
rabi_schedule = pulse.Schedule()
rabi_schedule += Play(rabi_pulse, drive_chan)
### WRITE YOUR CODE BETWEEN THESE LINES - END
# add measurement to rabi_schedule
# << indicates time shift the beginning to the start of the schedule
rabi_schedule += measure << rabi_schedule.duration
return rabi_schedule
# Gaussian pulse parameters, with varying amplitude
drive_duration = 128
num_rabi_points = 41
drive_amps = np.linspace(0, 0.9, num_rabi_points)
drive_sigma = 16
# now vary the amplitude for each drive amp
rabi_schedules = []
for drive_amp in drive_amps:
rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma))
rabi_schedules[-1].draw()
# assemble the schedules into a Qobj
from qiskit import assemble
rabi_qobj = assemble(**helper.get_params('rabi', globals()))
answer1a = rabi_qobj
# run the simulation
rabi_result = backend_sim.run(rabi_qobj, duffing_model).result()
# retrieve the data from the experiment
rabi_values = helper.get_values_from_result(rabi_result, qubit)
fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0])
plt.scatter(drive_amps, rabi_values, color='white')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] # get period of rabi oscillation
plt.axvline(0, color='red', linestyle='--')
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
print("Pi pulse amplitude is %f"%float(drive_period/2))
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_duration,
amp=drive_period/4,
sigma=drive_sigma,
name='x90_pulse')
# Ramsey experiment parameters
time_max_us = 0.4
time_step_us = 0.0035
times_us = np.arange(0.1, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
def build_ramsey_pulse_schedule(delay):
### create a Ramsey pulse schedule (already done)
### play an x90 pulse on the drive channel
### play another x90 pulse after delay
### add measurement pulse to schedule
ramsey_schedule = pulse.Schedule(name='ramsey_experiment')
### HINT: include delay by adding it to the duration of the schedule
### round delay to nearest integer with int(delay)
### WRITE YOUR CODE BETWEEN THESE LINES - START
ramsey_schedule = pulse.Schedule()
ramsey_schedule += Play(x90_pulse, drive_chan)
ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay)
ramsey_schedule += measure << ramsey_schedule.duration
### WRITE YOUR CODE BETWEEN THESE LINES - END
return ramsey_schedule
# create schedules for Ramsey experiment
ramsey_schedules = []
for delay in delay_times_dt:
ramsey_schedules.append(build_ramsey_pulse_schedule(delay))
ramsey_schedules[-1].draw()
# assemble the schedules into a Qobj
# the helper will drive the pulses off-resonantly by an unknown value
ramsey_qobj = assemble(**helper.get_params('ramsey', globals()))
answer1b = ramsey_qobj
# run the simulation
ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result()
# retrieve the data from the experiment
ramsey_values = helper.get_values_from_result(ramsey_result, qubit)
# off-resonance component
fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25])
_, _, ramsey_period_us, _, = fit_params
del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us
plt.scatter(times_us, np.real(ramsey_values), color='white')
plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz")
plt.xlim(np.min(times_us), np.max(times_us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend(loc=3)
plt.show()
print("Drive is off-resonant by %f MHz"%float(del_f_MHz))
name = 'Saasha Joshi'
email = 'saashajoshi08@gmail.com'
from grading_tools import grade
grade(answer1a, name, email, 'lab6', 'ex1a')
grade(answer1b, name, email, 'lab6', 'ex1b')
from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();'));
from grading_tools import send_code;send_code('ex1.ipynb')
|
https://github.com/filipecorrea/deutsch-jozsa
|
filipecorrea
|
import qiskit
from qiskit import IBMQ
# IBMQ.save_account('<IBMQ_API_TOKEN>')
IBMQ.load_account()
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import DeutschJozsa
from qiskit.aqua.components.oracles import TruthTableOracle
qiskit.__qiskit_version__
bitstr = '11110000'
oracle = TruthTableOracle(bitstr)
oracle.circuit.draw(output='mpl')
dj = DeutschJozsa(oracle)
backend = BasicAer.get_backend('qasm_simulator')
result = dj.run(QuantumInstance(backend, shots=1024))
print('The truth table {} represents a {} function.'.format(bitstr, result['result']))
bitstr = '1' * 32
oracle = TruthTableOracle(bitstr)
dj = DeutschJozsa(oracle)
result = dj.run(QuantumInstance(backend, shots=1024))
print('The truth table {} represents a {} function.'.format(bitstr, result['result']))
|
https://github.com/ColibrITD-SAS/mpqp
|
ColibrITD-SAS
|
from qiskit import QuantumCircuit
from . import circuit_constructor, circuit_eq
def test_circuit_constructor():
gates_list = ["h", "hs", "hs", "i", "i", "h"]
result = circuit_constructor(gates_list)
result_dag = circuit_constructor(gates_list, True)
expected = QuantumCircuit(6)
expected.h(0)
_ = expected.s(1), expected.h(1)
_ = expected.s(2), expected.h(2)
expected.h(5)
expected_dag = QuantumCircuit(6)
expected_dag.h(0)
_ = expected_dag.h(1), expected_dag.sdg(1)
_ = expected_dag.h(2), expected_dag.sdg(2)
expected_dag.h(5)
assert circuit_eq(result, expected)
assert circuit_eq(result_dag, expected_dag)
|
https://github.com/DanKim44/CodingWithQiskitS2
|
DanKim44
|
#Coding With Qiskit S2E5 Dinner Party using Grover's Algorithm
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.tools.visualization import *
from qiskit.tools.monitor import job_monitor
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
log_expr = '((Olivia & Abe) | (Jin & Amira)) & ~(Abe & Amira)'
algorithm = Grover(LogicalExpressionOracle(log_expr))
backend = BasicAer.get_backend('qasm_simulator')
result = algorithm.run(backend)
plot_histogram(result['measurement'], title="Possible Party Combinations", bar_labels=True)
#Top to bottom:
#Abe Amira Jin Oliva
#Mapping to random Digital Logic Homework: F=(~A+~B+C)(~A+B+C)(A+~B+C)(A+B+~C)(A+B+C)
log_expr2 = '( ~A & ~B & C ) | ( ~A & B & C ) | ( A & ~B & C ) | ( A & B & ~C ) | ( A & B & C )'
algorithm2 = Grover(LogicalExpressionOracle(log_expr2))
result2 = algorithm2.run(backend)
plot_histogram(result2['measurement'], title="Homework:)", bar_labels=True)
#Matches with homework problem & LogicAid:)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, QuantumRegister,ClassicalRegister, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.providers.aer import UnitarySimulator
n =1
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightblue'}
circ.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
n =1
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print( unitary)
n =2
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circ.draw(output='mpl', style = style)
n =2
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print( unitary)
n =2
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[1])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circ.draw(output='mpl', style = style)
n =2
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[1])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print( unitary)
n =2
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.h(q[1])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circ.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
n =2
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.h(q[1])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print( unitary)
n = 3
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.h(q[1])
circ.h(q[2])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circ.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
n =3
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.h(q[1])
circ.h(q[2])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print( unitary)
n = 8
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
for k in range(8):
circ.h(q[k])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightpink'}
circ.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
n =8
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
for k in range(8):
circ.h(q[k])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print( unitary)
unitary.shape
|
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/dkp-quantum/Tutorials
|
dkp-quantum
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
import numpy as np
# Create a quantum register with 3 qubits
q3 = QuantumRegister(3,'q')
# Create a classical register with 3 qubits
c3 = ClassicalRegister(3,'c')
# Create the quantum circuit with the measurement in one go.
qc_ex2 = QuantumCircuit(q3,c3,name="ex1")
qc_ex2.ry(2*np.pi/3,0)
qc_ex2.cx(0,1)
qc_ex2.cx(1,2)
qc_ex2.barrier()
qc_ex2.measure(q3,c3)
qc_ex2.draw(output='mpl')# Now, add a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
backend_q = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
job_ex2 = execute(qc_ex2, backend_q, shots=4096)
# Grab the results from the job.
result_ex2 = job_ex2.result()
plot_histogram(result_ex2.get_counts(qc_ex2))
# Create a quantum register with 3 qubits
q3 = QuantumRegister(3,'q')
# Create a classical register with 3 qubits
c3 = ClassicalRegister(3,'c')
# Create the quantum circuit without a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
qc_toff.ry(2*np.pi/3,0)
qc_toff.h(1)
qc_toff.h(2)
qc_toff.barrier()
qc_toff.measure(q3,c3)
qc_toff.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_toff = execute(qc_toff, backend_q, shots=4096)
# Grab the results from the job.
result_toff = job_toff.result()
plot_histogram(result_toff.get_counts(qc_toff))
# Now, add a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
qc_toff.ry(2*np.pi/3,0)
qc_toff.h(1)
qc_toff.h(2)
qc_toff.ccx(1,2,0)
qc_toff.barrier()
qc_toff.measure(q3,c3)
qc_toff.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_toff = execute(qc_toff, backend_q, shots=4096)
# Grab the results from the job.
result_toff = job_toff.result()
plot_histogram(result_toff.get_counts(qc_toff))
# IBMQ.disable_account()
provider = IBMQ.enable_account('TOKEN')
provider = IBMQ.get_provider(hub='ibm-q-research')
provider.backends()
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
# Retrieve IBM Quantum device information
backend_overview()
# Let's get two quantum devices as an example
backend_qx2 = provider.get_backend('ibmqx2')
backend_vigo = provider.get_backend('ibmq_vigo')
backend_monitor(backend_qx2)
plot_error_map(backend_qx2)
backend_monitor(backend_vigo)
plot_error_map(backend_vigo)
# Create a 5-qubit GHZ state (i.e. (|00000> + |11111>)/sqrt(2))
q5 = QuantumRegister(5,'q')
c5 = ClassicalRegister(5,'c')
ghz5= QuantumCircuit(q5,c5)
ghz5.h(0)
for i in range(1,5):
ghz5.cx(0,i)
ghz5.barrier()
ghz5.measure(q5,c5)
ghz5.draw(output='mpl')
# Run the 5-qubit GHZ experiment on a 5-qubit device (try vigo)
job_exp1 = execute(ghz5, backend=backend_vigo, shots=4096)
job_monitor(job_exp1)
# Grab experimental results
result_vigo = job_exp1.result()
counts_vigo = result_vigo.get_counts(ghz5)
# Let's also try the same experiment on the 15-qubit device.
job_exp2 = execute(ghz5, backend=provider.get_backend('ibmq_16_melbourne'), shots=4096)
job_monitor(job_exp2)
# Grab experimental results
result_mel = job_exp2.result()
counts_mel = result_mel.get_counts(ghz5)
# Now, compare to theory by running it on qasm_simulator
job_qasm = execute(ghz5,backend=backend_q)
result_qasm = job_qasm.result()
counts_qasm = result_qasm.get_counts(ghz5)
# Plot both experimental and ideal results
plot_histogram([counts_qasm,counts_vigo,counts_mel],
color=['black','green','blue'],
legend=['QASM','Vigo','Melbourne'],figsize = [20,8])
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
import numpy as np
# Define a function that takes a QuantumCircuit (qc)
# a qubit index (index) and a message string (msg)
def encoding(qc, index, msg):
if msg == 0:
pass # To send 00 we do nothing
elif msg == 1:
qc.x(index) # To send 10 we apply an X-gate
elif msg == 2:
qc.z(index) # To send 01 we apply a Z-gate
elif msg == 3:
qc.z(index) # To send 11, we apply a Z-gate
qc.x(index) # followed by an X-gate
else:
print("Invalid Message. Sending '00'.")
def decoding(qc, a, b):
qc.cx(a,b)
qc.h(a)
def qc_sdc(msg):
# Create the quantum circuit with 2 qubits
qc = QuantumCircuit(2)
# First, an entangled pair is created between Alice and Bob
# Bob has the first qubit, Alice has the second qubit.
qc.h(0)
qc.cx(0,1)
qc.barrier()
# Next, Bob encodes his message onto qubit 0.
encoding(qc, 0, msg)
qc.barrier()
# Bob then sends his qubit to Alice.
# After recieving qubit 0, Alice applies the recovery protocol:
decoding(qc, 0, 1)
# Finally, Alice measures her qubits to read Bob's message
qc.measure_all()
return qc
backend_qasm = Aer.get_backend('qasm_simulator')
rand_msg = np.random.randint(4)
qc = qc_sdc(rand_msg)
job_sim = execute(qc, backend_qasm, shots=1024)
sim_result = job_sim.result()
measurement_result = sim_result.get_counts(qc)
print(measurement_result)
plot_histogram(measurement_result)
print("The random message was: %s" % rand_msg)
qc.draw(output='mpl')
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
# Retrieve IBM Quantum device information
backend_overview()
# Run the superdense coding experiment on a 5-qubit device (try london)
job_sdc = execute(qc, backend=provider.get_backend('ibmq_london'), shots=4096)
job_monitor(job_sdc)
experiment_result = job_sdc.result().get_counts(qc)
print("The random message was: %s" % rand_msg)
plot_histogram(experiment_result)
def create_bell_pair(qc, a, b):
# Creates a bell pair in qc using qubits a & b
qc.h(a) # Put qubit a into state |+>
qc.cx(a,b) # CNOT with a as control and b as target
qr = QuantumRegister(3) # Protocol uses 3 qubits
cr1 = ClassicalRegister(1) # and 2 classical bits
cr2 = ClassicalRegister(1) # in 2 different registers
teleportation = QuantumCircuit(qr, cr1, cr2)
## STEP 1
# Entangle qubits q1 and q2
create_bell_pair(teleportation, 1, 2)
teleportation.barrier()
# And view the circuit so far:
teleportation.draw(output='mpl')
## STEP 2
# Bob performs his gates
teleportation.cx(0,1)
teleportation.h(0)
teleportation.barrier()
# And view the circuit so far:
teleportation.draw(output='mpl')
## STEP 3
# Bob measures his part
teleportation.measure(0,0)
teleportation.measure(1,1)
# And view the circuit so far:
teleportation.draw(output='mpl')
# This function takes a QuantumCircuit (qc), qubit index
# and ClassicalRegisters (cr1 & cr2) to decide which gates to apply
def alice_recover(qc, index, cr1, cr2):
# Here we use c_if to control our gates with a classical
# bit instead of a qubit
qc.z(index).c_if(cr1, 1) # Apply gates if the registers
qc.x(index).c_if(cr2, 1) # are in the state '1'
## STEP 4
# Alice perform recovery
alice_recover(teleportation, 2, cr1, cr2)
# And view the circuit so far:
teleportation.draw(output='mpl')
def random_init(qc,r1,r2,index):
## STEP 0
# Bob prepares a quantum state to teleport
# by applying a random rotation around y and z
qc.ry(r1,index)
qc.rz(r2,index)
qc.barrier()
def quantum_teleportation(qc):
## STEP 1
# Entangle qubits q1 and q2
create_bell_pair(qc, 1, 2)
qc.barrier()
## STEP 2
# Bob performs his gates
qc.cx(0,1)
qc.h(0)
qc.barrier()
## STEP 3
# Bob measures his part
qc.measure(0,0)
qc.measure(1,1)
## STEP 4
# Alice perform recovery
alice_recover(qc, 2, cr1, cr2)
qr = QuantumRegister(3) # Protocol uses 3 qubits
cr1 = ClassicalRegister(1) # and 2 classical bits
cr2 = ClassicalRegister(1) # in 2 different registers
qc_teleportation = QuantumCircuit(qr, cr1, cr2)
qc_ref = QuantumCircuit(qr)
r1 = np.random.random()*np.pi
r2 = np.random.random()*2*np.pi
random_init(qc_ref, r1, r2, 0)
random_init(qc_teleportation, r1, r2, 0)
quantum_teleportation(qc_teleportation)
qc_teleportation.draw(output='mpl')
backend_sv = BasicAer.get_backend('statevector_simulator')
in_vector = execute(qc_ref, backend_sv).result().get_statevector()
out_vector = execute(qc_teleportation, backend_sv).result().get_statevector()
plot_bloch_multivector(in_vector)
plot_bloch_multivector(out_vector)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# Install the plugin
# !pip install -e .
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import random_clifford
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.synthesis import AILinearFunctionSynthesis
from qiskit_transpiler_service.ai.collection import CollectLinearFunctions
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService
coupling_map = QiskitRuntimeService().backend("ibm_cairo").coupling_map
circuit = QuantumCircuit(27)
for c in range(3):
nq = 8
qs = np.random.choice(range(circuit.num_qubits), size=nq, replace=False)
circuit.compose(random_clifford(nq).to_circuit(), qubits=qs.tolist(), inplace=True)
for q in qs:
circuit.t(q)
print(
f"Original circuit -> Depth: {circuit.decompose(reps=3).depth()}, Gates(2q): {circuit.decompose(reps=3).num_nonlocal_gates()}"
)
circuit.draw(output="mpl", fold=-1, scale=0.3, style="iqp")
qiskit_lvl3_transpiler = generate_preset_pass_manager(
optimization_level=3, coupling_map=coupling_map
)
lvl3_transpiled_circuit = qiskit_lvl3_transpiler.run(circuit)
print(
f"Qiskit lvl3 Transpiler -> Depth: {lvl3_transpiled_circuit.decompose(reps=3).depth()}, Gates(2q): {lvl3_transpiled_circuit.decompose(reps=3).num_nonlocal_gates()}"
)
lvl3_transpiled_circuit.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
ai_optimize_cliffords = PassManager(
[
CollectLinearFunctions(),
AILinearFunctionSynthesis(backend_name="ibm_cairo"),
]
)
# AI Synthesis passes respect the coupling map and should run after transpiling
ai_optimized_circuit = ai_optimize_cliffords.run(lvl3_transpiled_circuit)
print(
f"AI-Optimized circuit -> Depth: {ai_optimized_circuit.decompose(reps=3).depth()}, Gates(2q): {ai_optimized_circuit.decompose(reps=3).num_nonlocal_gates()}"
)
ai_optimized_circuit.draw(output="mpl", fold=-1, scale=0.25, style="iqp")
|
https://github.com/mrvee-qC-bee/SCQC23
|
mrvee-qC-bee
|
from sklearn.datasets import load_iris
iris_data = load_iris()
print(iris_data.DESCR)
features = iris_data.data
labels = iris_data.target
from sklearn.preprocessing import MinMaxScaler
features = MinMaxScaler().fit_transform(features)
import pandas as pd
import seaborn as sns
df = pd.DataFrame(iris_data.data, columns=iris_data.feature_names)
df["class"] = pd.Series(iris_data.target)
sns.pairplot(df, hue="class", palette="tab10")
from sklearn.model_selection import train_test_split
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=0.8, random_state=algorithm_globals.random_seed
)
from sklearn.svm import SVC
svc = SVC()
_ = svc.fit(train_features, train_labels) # suppress printing the return value
train_score_c4 = svc.score(train_features, train_labels)
test_score_c4 = svc.score(test_features, test_labels)
print(f"Classical SVC on the training dataset: {train_score_c4:.2f}")
print(f"Classical SVC on the test dataset: {test_score_c4:.2f}")
from qiskit.circuit.library import EfficientSU2
circuit = EfficientSU2(num_qubits=3, reps=1, insert_barriers=True)
circuit.decompose().draw(output='mpl')
x = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2]
encode = circuit.bind_parameters(x)
encode.decompose().draw(output='mpl')
from qiskit.circuit.library import ZZFeatureMap
circuit = ZZFeatureMap(3, reps=1, insert_barriers=True)
circuit.decompose().draw(output='mpl')
x = [0.1,0.2,0.3]
encode = circuit.bind_parameters(x)
encode.decompose().draw(output='mpl')
from qiskit.circuit.library import ZZFeatureMap
x = [-0.1,0.2]
# YOUR CODE HERE
# circuit =
# encode =
circuit.decompose().draw(output='mpl')
from qiskit.circuit.library import ZZFeatureMap
num_features = features.shape[1]
feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1)
feature_map.decompose().draw(output="mpl", fold=20)
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=num_features, reps=3)
ansatz.decompose().draw(output="mpl", fold=20)
from qiskit.algorithms.optimizers import COBYLA
optimizer = COBYLA(maxiter=100)
from matplotlib import pyplot as plt
from IPython.display import clear_output
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Options, Estimator, Sampler
service = QiskitRuntimeService(channel='ibm_quantum')
service.backends()
backend = service.backends(simulator=True)[0]
print(backend)
import time
from qiskit_machine_learning.algorithms.classifiers import VQC
# from qiskit.primitives import Sampler
with Session(service = service, backend = backend):
vqc = VQC(
sampler=Sampler(),
feature_map=feature_map,
ansatz=ansatz,
optimizer=optimizer,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
start = time.time()
vqc.fit(train_features, train_labels)
elapsed = time.time() - start
print(f"Training time: {round(elapsed)} seconds")
train_score_q4 = vqc.score(train_features, train_labels)
test_score_q4 = vqc.score(test_features, test_labels)
print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}")
print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}")
from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap, StatePreparation
num_features = features.shape[1]
feature_map_ex = # Use any featuremap of your choice!
feature_map_ex.decompose().draw(output="mpl", fold=20)
from qiskit.circuit.library import RealAmplitudes, EfficientSU2, ExcitationPreserving, PauliTwoDesign, TwoLocal, NLocal
ansatz_ex = # Use any ansatz of your choice!
ansatz_ex.decompose().draw(output="mpl", fold=20)
from qiskit.algorithms.optimizers import COBYLA, SPSA, L_BFGS_B, NELDER_MEAD, UMDA, TNC
optimizer_ex = # Use any optimizer of your choice!
import time
from qiskit_machine_learning.algorithms.classifiers import VQC
from qiskit.primitives import Sampler
with Session(service = service, backend = backend):
vqc_ex = VQC(
feature_map=feature_map_ex,
ansatz=ansatz_ex,
optimizer=optimizer_ex,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
start = time.time()
vqc_ex.fit(train_features, train_labels)
elapsed = time.time() - start
print(f"Training time: {round(elapsed)} seconds")
train_score_q4_ex = vqc_ex.score(train_features, train_labels)
test_score_q4_ex = vqc_ex.score(test_features, test_labels)
print(f"Quantum VQC on the training dataset: {train_score_q4_ex:.2f}")
print(f"Quantum VQC on the test dataset: {test_score_q4_ex:.2f}")
from sklearn.decomposition import PCA
features = PCA(n_components=2).fit_transform(features)
plt.rcParams["figure.figsize"] = (6, 6)
sns.scatterplot(x=features[:, 0], y=features[:, 1], hue=labels, palette="tab10")
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=0.8, random_state=algorithm_globals.random_seed
)
svc.fit(train_features, train_labels)
train_score_c2 = svc.score(train_features, train_labels)
test_score_c2 = svc.score(test_features, test_labels)
print(f"Classical SVC on the training dataset: {train_score_c2:.2f}")
print(f"Classical SVC on the test dataset: {test_score_c2:.2f}")
num_features = features.shape[1]
feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1)
ansatz = RealAmplitudes(num_qubits=num_features, reps=3)
ansatz.decompose().draw("mpl")
from qiskit.algorithms.optimizers import COBYLA, SPSA, L_BFGS_B, NELDER_MEAD, UMDA, TNC
optimizer = COBYLA(maxiter=50)
from qiskit.primitives import Sampler
with Session(service = service, backend = backend):
vqc = VQC(
feature_map=feature_map,
ansatz=ansatz,
optimizer=optimizer,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
# make the objective function plot look nicer.
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
vqc.fit(train_features, train_labels)
elapsed = time.time() - start
print(f"Training time: {round(elapsed)} seconds")
train_score_q2_ra = vqc.score(train_features, train_labels)
test_score_q2_ra = vqc.score(test_features, test_labels)
print(f"Quantum VQC on the training dataset using RealAmplitudes: {train_score_q2_ra:.2f}")
print(f"Quantum VQC on the test dataset using RealAmplitudes: {test_score_q2_ra:.2f}")
from qiskit.circuit.library import EfficientSU2
ansatz = EfficientSU2(num_qubits=num_features, reps=3)
optimizer = COBYLA(maxiter=100)
with Session(service = service, backend = backend):
vqc = VQC(
feature_map=feature_map,
ansatz=ansatz,
optimizer=optimizer,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
start = time.time()
vqc.fit(train_features, train_labels)
elapsed = time.time() - start
print(f"Training time: {round(elapsed)} seconds")
train_score_q2_eff = vqc.score(train_features, train_labels)
test_score_q2_eff = vqc.score(test_features, test_labels)
print(f"Quantum VQC on the training dataset using EfficientSU2: {train_score_q2_eff:.2f}")
print(f"Quantum VQC on the test dataset using EfficientSU2: {test_score_q2_eff:.2f}")
print(f"Model | Test Score | Train Score")
print(f"SVC, 4 features | {train_score_c4:10.2f} | {test_score_c4:10.2f}")
print(f"VQC, 4 features, RealAmplitudes | {train_score_q4:10.2f} | {test_score_q4:10.2f}")
print(f"----------------------------------------------------------")
print(f"SVC, 2 features | {train_score_c2:10.2f} | {test_score_c2:10.2f}")
print(f"VQC, 2 features, EfficientSU2 | {train_score_q2_eff:10.2f} | {test_score_q2_eff:10.2f}")
print(f"VQC, 2 features, RealAmplitudes | {train_score_q2_ra:10.2f} | {test_score_q2_ra:10.2f}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC
from qiskit_machine_learning.algorithms.regressors import NeuralNetworkRegressor, VQR
from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN
algorithm_globals.random_seed = 42
num_inputs = 2
num_samples = 20
X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1
y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1}
y = 2 * y01 - 1 # in {-1, +1}
y_one_hot = np.zeros((num_samples, 2))
for i in range(num_samples):
y_one_hot[i, y01[i]] = 1
for x, y_target in zip(X, y):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
# construct QNN
qc = QuantumCircuit(2)
feature_map = ZZFeatureMap(2)
ansatz = RealAmplitudes(2)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
qc.draw(output="mpl")
estimator_qnn = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# QNN maps inputs to [-1, +1]
estimator_qnn.forward(X[0, :], algorithm_globals.random.random(estimator_qnn.num_weights))
# callback function that draws a live plot when the .fit() method is called
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
# construct neural network classifier
estimator_classifier = NeuralNetworkClassifier(
estimator_qnn, optimizer=COBYLA(maxiter=60), callback=callback_graph
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
estimator_classifier.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
estimator_classifier.score(X, y)
# evaluate data points
y_predict = estimator_classifier.predict(X)
# plot results
# red == wrongly classified
for x, y_target, y_p in zip(X, y, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if y_target != y_p:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
estimator_classifier.weights
# construct feature map
feature_map = ZZFeatureMap(num_inputs)
# construct ansatz
ansatz = RealAmplitudes(num_inputs, reps=1)
# construct quantum circuit
qc = QuantumCircuit(num_inputs)
qc.append(feature_map, range(num_inputs))
qc.append(ansatz, range(num_inputs))
qc.decompose().draw(output="mpl")
# parity maps bitstrings to 0 or 1
def parity(x):
return "{:b}".format(x).count("1") % 2
output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping.
# construct QNN
sampler_qnn = SamplerQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=output_shape,
)
# construct classifier
sampler_classifier = NeuralNetworkClassifier(
neural_network=sampler_qnn, optimizer=COBYLA(maxiter=30), callback=callback_graph
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
sampler_classifier.fit(X, y01)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
sampler_classifier.score(X, y01)
# evaluate data points
y_predict = sampler_classifier.predict(X)
# plot results
# red == wrongly classified
for x, y_target, y_p in zip(X, y01, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if y_target != y_p:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
sampler_classifier.weights
# construct feature map, ansatz, and optimizer
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs, reps=1)
# construct variational quantum classifier
vqc = VQC(
feature_map=feature_map,
ansatz=ansatz,
loss="cross_entropy",
optimizer=COBYLA(maxiter=30),
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
vqc.fit(X, y_one_hot)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
vqc.score(X, y_one_hot)
# evaluate data points
y_predict = vqc.predict(X)
# plot results
# red == wrongly classified
for x, y_target, y_p in zip(X, y_one_hot, y_predict):
if y_target[0] == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if not np.all(y_target == y_p):
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
from sklearn.datasets import make_classification
from sklearn.preprocessing import MinMaxScaler
X, y = make_classification(
n_samples=10,
n_features=2,
n_classes=3,
n_redundant=0,
n_clusters_per_class=1,
class_sep=2.0,
random_state=algorithm_globals.random_seed,
)
X = MinMaxScaler().fit_transform(X)
plt.scatter(X[:, 0], X[:, 1], c=y)
y_cat = np.empty(y.shape, dtype=str)
y_cat[y == 0] = "A"
y_cat[y == 1] = "B"
y_cat[y == 2] = "C"
print(y_cat)
vqc = VQC(
num_qubits=2,
optimizer=COBYLA(maxiter=30),
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
vqc.fit(X, y_cat)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
vqc.score(X, y_cat)
predict = vqc.predict(X)
print(f"Predicted labels: {predict}")
print(f"Ground truth: {y_cat}")
num_samples = 20
eps = 0.2
lb, ub = -np.pi, np.pi
X_ = np.linspace(lb, ub, num=50).reshape(50, 1)
f = lambda x: np.sin(x)
X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb
y = f(X[:, 0]) + eps * (2 * algorithm_globals.random.random(num_samples) - 1)
plt.plot(X_, f(X_), "r--")
plt.plot(X, y, "bo")
plt.show()
# construct simple feature map
param_x = Parameter("x")
feature_map = QuantumCircuit(1, name="fm")
feature_map.ry(param_x, 0)
# construct simple ansatz
param_y = Parameter("y")
ansatz = QuantumCircuit(1, name="vf")
ansatz.ry(param_y, 0)
# construct a circuit
qc = QuantumCircuit(1)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# construct QNN
regression_estimator_qnn = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# construct the regressor from the neural network
regressor = NeuralNetworkRegressor(
neural_network=regression_estimator_qnn,
loss="squared_error",
optimizer=L_BFGS_B(maxiter=5),
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit to data
regressor.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score the result
regressor.score(X, y)
# plot target function
plt.plot(X_, f(X_), "r--")
# plot data
plt.plot(X, y, "bo")
# plot fitted line
y_ = regressor.predict(X_)
plt.plot(X_, y_, "g-")
plt.show()
regressor.weights
vqr = VQR(
feature_map=feature_map,
ansatz=ansatz,
optimizer=L_BFGS_B(maxiter=5),
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit regressor
vqr.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score result
vqr.score(X, y)
# plot target function
plt.plot(X_, f(X_), "r--")
# plot data
plt.plot(X, y, "bo")
# plot fitted line
y_ = vqr.predict(X_)
plt.plot(X_, y_, "g-")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/dlyongemallo/qiskit-zx-transpiler
|
dlyongemallo
|
# ZX transpiler pass for Qiskit
# Copyright (C) 2023 David Yonge-Mallo
#
# 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.
if __name__ == '__main__':
import sys
sys.path.append('..')
from qiskit import transpile
from qiskit.circuit import QuantumCircuit
from qiskit.transpiler import PassManager
from typing import Dict, List, Tuple
import matplotlib.pyplot as plt # type: ignore
from zxpass import ZXPass
pass_manager = PassManager(ZXPass())
def _benchmark(subdir: str, circuit_name: str, as_plugin: bool = False) -> Tuple[float, float, float]:
print(f"Circuit name: {circuit_name}")
qc = QuantumCircuit.from_qasm_file(f"QASMBench/{subdir}/{circuit_name}/{circuit_name}.qasm")
opt_qc = transpile(qc, basis_gates=['u3', 'cx'], optimization_level=3)
if as_plugin:
zx_qc = transpile(qc, optimization_method="zxpass", optimization_level=3)
else:
zx_qc = pass_manager.run(qc)
print(f"Size - original: {qc.size()}, "
f"optimized: {opt_qc.size()} ({qc.size() / opt_qc.size():.2f}), "
f"zx: {zx_qc.size()} ({qc.size() / zx_qc.size():.2f})")
print(f"Depth - original: {qc.depth()}, "
f"optimized: {opt_qc.depth()} ({qc.depth() / opt_qc.depth():.2f}), "
f"zx: {zx_qc.depth()} ({qc.depth() / zx_qc.depth():.2f})")
print(f"Number of non-local gates - original: {qc.num_nonlocal_gates()}, ", end="")
if qc.num_nonlocal_gates() != 0:
print(f"optimized: {opt_qc.num_nonlocal_gates()}, zx: {zx_qc.num_nonlocal_gates()}, "
f"ratio: {opt_qc.num_nonlocal_gates() / zx_qc.num_nonlocal_gates():.2f}")
else:
print("optimized: 0, zx: 0")
print()
return (qc.depth() / opt_qc.depth(),
qc.depth() / zx_qc.depth(),
qc.num_nonlocal_gates() / zx_qc.num_nonlocal_gates() if zx_qc.num_nonlocal_gates() != 0 else 0)
def _save_plot(title: str, plot_index: List[str], data: Dict[str, List[float]], ylabel: str) -> None:
width = 0.35
fig, ax = plt.subplots()
ax.set_title(title)
ax.set_ylabel(ylabel)
x = range(len(plot_index))
ax.bar(x, data['qiskit'], width, label='qiskit')
ax.bar([i + width for i in x], data['pyzx'], width, label='pyzx')
ax.set_xticks([i + width / 2 for i in x])
ax.set_xticklabels(plot_index, rotation=90)
ax.legend()
plt.tight_layout()
plt.savefig(f"{title.replace(' ', '_')}.png")
def run_benchmarks() -> None:
# List of circuits to benchmark, based on: https://github.com/Qiskit/qiskit/issues/4990#issuecomment-1157858632
small_benchmarks = ['wstate_n3', 'linearsolver_n3', 'fredkin_n3', 'dnn_n2', 'qrng_n4', 'adder_n4', 'deutsch_n2',
'cat_state_n4', 'basis_trotter_n4', 'qec_en_n5', 'toffoli_n3', 'grover_n2', 'hs4_n4', 'qaoa_n3',
'teleportation_n3', 'lpn_n5', 'vqe_uccsd_n4', 'quantumwalks_n2', 'variational_n4', 'qft_n4',
'iswap_n2', 'bell_n4', 'basis_change_n3', 'vqe_uccsd_n6', 'ising_n10', 'simon_n6', 'qpe_n9',
'qaoa_n6', 'bb84_n8', 'vqe_uccsd_n8', 'adder_n10', 'dnn_n8']
medium_benchmarks = ['bv_n14', 'multiplier_n15', 'sat_n11', 'qft_n18']
depth_ratio: Dict[str, List[float]] = {'qiskit': [], 'pyzx': []}
num_nonlocal_ratio: Dict[str, List[float]] = {'qiskit': [], 'pyzx': []}
plot_index = []
for benchmark in small_benchmarks:
qiskit_depth, zx_depth, non_local_ratio = _benchmark('small', benchmark)
depth_ratio['pyzx'].append(zx_depth)
depth_ratio['qiskit'].append(qiskit_depth)
num_nonlocal_ratio['pyzx'].append(non_local_ratio)
num_nonlocal_ratio['qiskit'].append(1 if non_local_ratio != 0 else 0)
plot_index.append(benchmark)
for benchmark in medium_benchmarks:
qiskit_depth, zx_depth, non_local_ratio = _benchmark('medium', benchmark)
depth_ratio['pyzx'].append(zx_depth)
depth_ratio['qiskit'].append(qiskit_depth)
num_nonlocal_ratio['pyzx'].append(non_local_ratio)
num_nonlocal_ratio['qiskit'].append(1 if non_local_ratio != 0 else 0)
plot_index.append(benchmark)
_save_plot('Depth compression ratio', plot_index, depth_ratio, 'depth_ratio')
_save_plot('Ratio of non-local gates', plot_index, num_nonlocal_ratio, 'num_nonlocal_ratio')
if __name__ == '__main__':
run_benchmarks()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def step_1_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
##1 Initialization
q0, q1 = qr
# apply Hadamard on the auxiliary qubit
qc.h(q0)
# put the system qubit into the |1> state
qc.x(q1)
##2 Apply control-U operator as many times as needed to get the least significant phase bit
# controlled-S is equivalent to CPhase with angle pi / 2
s_angle = np.pi / 2
# we want to apply controlled-S 2^k times
k = 1
# calculate the angle of CPhase corresponding to 2^k applications of controlled-S
cphase_angle = s_angle * 2**k
# apply the controlled phase gate
qc.cp(cphase_angle, q0, q1)
##3 Measure the auxiliary qubit in x-basis into the first classical bit
# apply Hadamard to change to the X basis
qc.h(q0)
# measure the auxiliary qubit into the first classical bit
c0, _ = cr
qc.measure(q0, c0)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_1_circuit(qr, cr)
qc.draw("mpl")
# Submit your circuit
from qc_grader.challenges.qgss_2023 import grade_lab4_ex1
grade_lab4_ex1(qc)
def step_2_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
# begin with the circuit from Step 1
qc = step_1_circuit(qr, cr)
####### your code goes here #######
##1 Reset and re-initialize the auxiliary qubit
q0, q1 = qr
# reset the auxiliary qubit
qc.reset(q0)
# apply Hadamard on the auxiiliary qubit
qc.h(q0)
##2 Apply phase correction conditioned on the first classical bit
c0, c1 = cr
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
##3 Apply control-U operator as many times as needed to get the next phase bit
# controlled-S is equivalent to CPhase with angle pi / 2
s_angle = np.pi / 2
# we want to apply controlled-S 2^k times
k = 0
# calculate the angle of CPhase corresponding to 2^k applications of controlled-S
cphase_angle = s_angle * 2**k
# apply the controlled phase gate
qc.cp(cphase_angle, q0, q1)
##4 Measure the auxiliary qubit in x-basis into the second classical bit
# apply Hadamard to change to the X basis
qc.h(q0)
# measure the auxiliary qubit into the first classical bit
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_2_circuit(qr, cr)
qc.draw("mpl")
# Submit your circuit
from qc_grader.challenges.qgss_2023 import grade_lab4_ex2
grade_lab4_ex2(qc)
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def t_gate_ipe_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 3 bits
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
t_angle = np.pi / 4
k = 2
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the first classical bit
qc.h(q0)
c0, c1, c2 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 1
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first and second classical bits
with qc.if_test((c0, 1)):
qc.p(-np.pi / 4, q0)
with qc.if_test((c1, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 0
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the third classical bit
qc.h(q0)
qc.measure(q0, c2)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(3, "c")
qc = QuantumCircuit(qr, cr)
qc = t_gate_ipe_circuit(qr, cr)
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
# Submit your circuit
from qc_grader.challenges.qgss_2023 import grade_lab4_ex3
grade_lab4_ex3(qc)
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
u_angle = 2 * np.pi / 3
k = 1
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the first classical bit
qc.h(q0)
c0, c1 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 0
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
print(counts)
success_probability = counts["01"] / counts.shots()
print(f"Success probability: {success_probability}")
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 1 bits
qc = QuantumCircuit(qr, cr)
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
u_angle = 2 * np.pi / 3
k = 1
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis
qc.h(q0)
(c0,) = cr
qc.measure(q0, c0)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
job = sim.run(qc, shots=15)
result = job.result()
counts = result.get_counts()
print(counts)
step1_bit: int
####### your code goes here #######
step1_bit = 1 if counts["1"] > counts["0"] else 0
print(step1_bit)
# Submit your result
from qc_grader.challenges.qgss_2023 import grade_lab4_ex4
grade_lab4_ex4(step1_bit)
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
# Initialization
q0, q1 = qr
if step1_bit:
qc.x(q0)
qc.x(q1)
# Measure the auxiliary qubit
c0, c1 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
u_angle = 2 * np.pi / 3
k = 0
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
# Submit your result
from qc_grader.challenges.qgss_2023 import grade_lab4_ex5
grade_lab4_ex5(qc)
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
print(counts)
success_probability = counts["01"] / counts.shots()
print(f"Success probability: {success_probability}")
from qiskit.circuit import Gate
def iterative_phase_estimation(
qr: QuantumRegister,
cr: ClassicalRegister,
controlled_unitaries: list[Gate],
state_prep: Gate,
) -> QuantumCircuit:
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
auxiliary_qubit = qr[0]
system_qubits = qr[1:]
qc.append(state_prep, system_qubits)
for i in range(len(cr)):
k = len(cr) - 1 - i
qc.reset(auxiliary_qubit)
qc.h(auxiliary_qubit)
for j in range(i):
with qc.if_test((cr[j], 1)):
qc.p(-np.pi / 2 ** (i - j), auxiliary_qubit)
qc.append(controlled_unitaries[k], qr)
qc.h(auxiliary_qubit)
qc.measure(auxiliary_qubit, cr[i])
return qc
from qiskit.circuit.library import CPhaseGate, XGate
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
s_angle = np.pi / 2
controlled_unitaries = [CPhaseGate(s_angle * 2**k) for k in range(2)]
qc = iterative_phase_estimation(qr, cr, controlled_unitaries, XGate())
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
from qiskit_ibm_provider import IBMProvider
provider = IBMProvider()
hub = "YOUR_HUB"
group = "YOUR_GROUP"
project = "YOUR_PROJECT"
backend_name = "ibmq_manila"
backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}")
from qiskit import transpile
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_2_circuit(qr, cr)
qc_transpiled = transpile(qc, backend)
job = backend.run(qc_transpiled, shots=1000, dynamic=True)
job_id = job.job_id()
print(job_id)
retrieve_job = provider.retrieve_job(job_id)
retrieve_job.status()
from qiskit.tools.visualization import plot_histogram
counts = retrieve_job.result().get_counts()
plot_histogram(counts)
|
https://github.com/mlvqc/Byskit
|
mlvqc
|
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
backend = BasicAer.get_backend('qasm_simulator')
%matplotlib inline
from byskit import byskit,gen_random_weights
n_parent = 3
n_child = 3
parents,children = gen_random_weights(n_parent,n_child)
b = byskit(backend,parents,children)
b.circ.draw(output='mpl')
results = b.execute_circ()
plot_histogram(results.results().get_counts(b.circ))
n_parent = 2
n_child = 4
parents,children = gen_random_weights(n_parent,n_child)
b = byskit(backend,parents,children)
b.circ.draw(output='mpl')
results = b.execute_circ()
plot_histogram(results.results().get_counts(b.circ))
|
https://github.com/crabster/qiskit-learning
|
crabster
|
from argparse import ArgumentParser
from qiskit import execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
from circuits.test import test_circuit
from circuits.quantum_teleportation import quantum_teleportation_example
from circuits.superdense_coding import superdense_coding_example
from circuits.deutsch_jozsa import deutsch_jozsa_example
from circuits.bernstein_vazirani import bernstein_vazirani_example
from circuits.quantum_fourier_transform import qft_example
from circuits.quantum_phase_estimation import qpe_example
parser = ArgumentParser(description='Run quantum circuit.')
parser.add_argument('-b', '--backend', metavar='BE', default='qasm_simulator',
choices=['auto', 'qasm_simulator', 'ibmqx2', 'ibmq_16_melbourne',
'ibmq_vigo', 'ibmq_ourense', 'ibmq_london',
'ibmq_burlington', 'ibmq_essex', 'ibmq_armonk', 'ibmq_rome'],
help='backend BE on which will the circuit run')
parser.add_argument('-c', '--circuit', metavar='QC', required=True,
choices=['test', 'tp', 'sc', 'dj', 'bv', 'qft', 'qpe'],
help='circuit QC to be run')
parser.add_argument('--shots', type=int, default=1024,
help='plot counts histogram of the result')
parser.add_argument('--plot', action="store_true",
help='plot counts histogram of the result')
args = parser.parse_args()
if args.circuit == 'test':
qc = test_circuit()
if args.circuit == 'tp':
qc = quantum_teleportation_example()
if args.circuit == 'sc':
qc = superdense_coding_example()
if args.circuit == 'dj':
qc = deutsch_jozsa_example()
if args.circuit == 'bv':
qc = bernstein_vazirani_example()
if args.circuit == 'qft':
qc = qft_example()
if args.circuit == 'qpe':
qc = qpe_example()
if args.backend == 'qasm_simulator':
backend = BasicAer.get_backend('qasm_simulator')
else:
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
if args.backend == 'auto':
backends = provider.backends(filters=lambda b:
b.configuration().n_qubits >= qc.num_qubits and
not b.configuration().simulator and
b.status().operational==True)
backend = least_busy(backends)
else:
backend = provider.get_backend(args.backend)
job = execute(qc, backend, shots=args.shots)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
if args.plot:
plot_histogram(counts)
plt.show()
|
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.
"""Tests for PTM quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators.channel import PTM
from .channel_test_case import ChannelTestCase
class TestPTM(ChannelTestCase):
"""Tests for PTM channel representation."""
def test_init(self):
"""Test initialization"""
mat4 = np.eye(4) / 2.0
chan = PTM(mat4)
assert_allclose(chan.data, mat4)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat16 = np.eye(16) / 4
chan = PTM(mat16)
assert_allclose(chan.data, mat16)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan.num_qubits, 2)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, PTM, mat16, input_dims=2, output_dims=4)
# Non multi-qubit dimensions should raise exception
self.assertRaises(QiskitError, PTM, np.eye(6) / 2, input_dims=3, output_dims=2)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = PTM(circuit)
target = PTM(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, PTM, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4, real=True)
self.assertEqual(PTM(mat), PTM(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = PTM(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = PTM(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = PTM(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(PTM(self.depol_ptm(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(PTM(1.25 * self.ptmI - 0.25 * self.depol_ptm(1)).is_cptp())
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, PTM(np.eye(4)).compose, PTM(np.eye(16)))
self.assertRaises(QiskitError, PTM(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = PTM(self.ptmX)
chan2 = PTM(self.ptmY)
chan = chan1.compose(chan2)
rho_targ = rho.evolve(PTM(self.ptmZ))
self.assertEqual(rho.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = PTM(self.depol_ptm(0.5))
chan = chan1.compose(chan1)
rho_targ = rho.evolve(PTM(self.depol_ptm(0.75)))
self.assertEqual(rho.evolve(chan), rho_targ)
# Compose random
ptm1 = self.rand_matrix(4, 4, real=True)
ptm2 = self.rand_matrix(4, 4, real=True)
chan1 = PTM(ptm1, input_dims=2, output_dims=2)
chan2 = PTM(ptm2, input_dims=2, output_dims=2)
rho_targ = rho.evolve(chan1).evolve(chan2)
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho.evolve(chan), rho_targ)
chan = chan1 & chan2
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho.evolve(chan), rho_targ)
def test_dot(self):
"""Test dot method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = PTM(self.ptmX)
chan2 = PTM(self.ptmY)
rho_targ = rho.evolve(PTM(self.ptmZ))
self.assertEqual(rho.evolve(chan2.dot(chan1)), rho_targ)
self.assertEqual(rho.evolve(chan2 @ chan1), rho_targ)
# Compose random
ptm1 = self.rand_matrix(4, 4, real=True)
ptm2 = self.rand_matrix(4, 4, real=True)
chan1 = PTM(ptm1, input_dims=2, output_dims=2)
chan2 = PTM(ptm2, input_dims=2, output_dims=2)
rho_targ = rho.evolve(chan1).evolve(chan2)
self.assertEqual(rho.evolve(chan2.dot(chan1)), rho_targ)
self.assertEqual(rho.evolve(chan2 @ chan1), rho_targ)
def test_compose_front(self):
"""Test deprecated front compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = PTM(self.ptmX)
chan2 = PTM(self.ptmY)
chan = chan2.compose(chan1, front=True)
rho_targ = rho.evolve(PTM(self.ptmZ))
self.assertEqual(rho.evolve(chan), rho_targ)
# Compose random
ptm1 = self.rand_matrix(4, 4, real=True)
ptm2 = self.rand_matrix(4, 4, real=True)
chan1 = PTM(ptm1, input_dims=2, output_dims=2)
chan2 = PTM(ptm2, input_dims=2, output_dims=2)
rho_targ = rho.evolve(chan1).evolve(chan2)
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho.evolve(chan), rho_targ)
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = PTM(self.ptmI)
chan2 = PTM(self.ptmX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = PTM(self.depol_ptm(1))
chan = chan_dep.expand(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = PTM(self.ptmI)
chan2 = PTM(self.ptmX)
# X \otimes I
chan = chan2.tensor(chan1)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan1.tensor(chan2)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = PTM(self.depol_ptm(1))
chan = chan_dep.tensor(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
p_id = 0.9
depol = PTM(self.depol_ptm(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = PTM(self.depol_ptm(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.ptmI
mat2 = 0.5 * self.depol_ptm(1)
chan1 = PTM(mat1)
chan2 = PTM(mat2)
targ = PTM(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = PTM(mat1 - mat2)
self.assertEqual(chan1 - chan2, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = PTM(mat)
op0 = PTM(mat0)
op1 = PTM(mat1)
op01 = op1.tensor(op0)
eye = PTM(self.ptmI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = PTM(mat)
op0 = PTM(mat0)
op1 = PTM(mat1)
op01 = op1.tensor(op0)
eye = PTM(self.ptmI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_add_except(self):
"""Test add method raises exceptions."""
chan1 = PTM(self.ptmI)
chan2 = PTM(np.eye(16))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = PTM(self.ptmI)
val = 0.5
targ = PTM(val * self.ptmI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = PTM(self.ptmI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = PTM(self.ptmI)
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
chan = PTM(self.ptmI)
targ = PTM(-self.ptmI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
### added x gate ###
qc.x(qubit)
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/Axect/QuantumAlgorithms
|
Axect
|
import pennylane as qml
from pennylane import numpy as np
import matplotlib.pyplot as plt
import scienceplots
qml.drawer.use_style(style='sketch')
def unitary_matrix_from_hermitian(A):
eigenvalues, eigenvectors = np.linalg.eigh(A)
D = np.diag(np.exp(2j * np.pi * eigenvalues))
U = np.dot(eigenvectors, np.dot(D, eigenvectors.conj().T))
return U
def MultipleControlledRY(target_wire, control_wires, lamb1, lamb2):
"""
Apply a multiple controlled RY gate to the target wire, with control on the control wires.
Args:
target_wire (int): the target wire the RY gate acts on
control_wires (list[int]): the control wires
lamb (float): the eigenvalue. lamb should be converted to the qubit state (e.g. 0.25 (n=2) -> 01)
"""
n = len(control_wires)
angle1 = 2 * np.arcsin(lamb1)
lamb1_bin = format(int(lamb1 * 2**n), f'0{n}b')
control_values1 = [int(bit) for bit in lamb1_bin]
angle2 = 2 * np.arcsin(lamb2)
lamb2_bin = format(int(lamb2 * 2**n), f'0{n}b')
control_values2 = [int(bit) for bit in lamb2_bin]
# print(control_values)
qml.ctrl(qml.RY, control=control_wires, control_values=control_values1)(angle1, wires=target_wire)
qml.ctrl(qml.RY, control=control_wires, control_values=control_values2)(angle2, wires=target_wire)
dev = qml.device('default.qubit', wires=3)
@qml.qnode(dev)
def aqe_test(lamb1, lamb2):
qml.PauliX(wires=2)
MultipleControlledRY(0, [1, 2], lamb1, lamb2)
return qml.state()
lamb1 = 0.75
lamb2 = 0.25
qml.draw_mpl(aqe_test)(lamb1, lamb2)
plt.show()
state = aqe_test(lamb1, lamb2)
print(state)
@qml.qnode(dev)
def aqe_test(lamb1, lamb2):
qml.PauliX(wires=1)
qml.PauliX(wires=2)
MultipleControlledRY(0, [1, 2], lamb1, lamb2)
return qml.state()
state = aqe_test(lamb1, lamb2)
print(state)
qml.draw_mpl(aqe_test)(lamb1, lamb2)
plt.show()
A = np.array([[0.5, 0.25], [0.25, 0.5]])
U = unitary_matrix_from_hermitian(A)
x = np.array([1, 0])
dev = qml.device('default.qubit', wires=3)
@qml.qnode(dev)
def qpe_test(U, x):
# Encode the input vector x into the amplitudes of the state (here, only 2d vectors)
qml.AmplitudeEmbedding(features=x, wires=2, normalize=True)
# Apply Hadamard gate to the first n qubits
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
# Apply controlled unitary operations
qml.ControlledSequence(qml.QubitUnitary(U, wires=2), control=range(2))
# Apply inverse QFT
qml.adjoint(qml.QFT)(wires=range(2))
# Measure c-register and return the probability distribution
return qml.state()
qml.draw_mpl(qpe_test)(U, x)
plt.show()
qpe_test(U, x).round(2)
def gen_qmm(n: int, A):
U = unitary_matrix_from_hermitian(A)
U_inv = np.linalg.inv(U)
dev1 = qml.device("default.qubit", wires=n+1) # c-register, encoding x
dev2 = qml.device("lightning.qubit", wires=n+2, shots=10000, mcmc=True) # ancilla, c-register, encoding x
@qml.qnode(dev1)
def eigenvalue_circuit(x):
# Encode the input vector x into the amplitudes of the state (here, only 2d vectors)
qml.AmplitudeEmbedding(features=x, wires=n, normalize=True)
# Apply Hadamard gate to the first n qubits
for i in range(n):
qml.Hadamard(wires=i)
# Apply controlled unitary operations
qml.ControlledSequence(qml.QubitUnitary(U, wires=n), control=range(n))
# Apply inverse QFT
qml.adjoint(qml.QFT)(wires=range(n))
# Measure c-register and return the probability distribution
return qml.probs(wires=range(n))
@qml.qnode(dev2)
def final_circuit(x, lamb1, lamb2):
# Encode the input vector x into the amplitudes of the state (here, only 2d vectors)
qml.AmplitudeEmbedding(features=x, wires=n+1, normalize=True)
# Apply Hadamard gate to the c-register
for i in range(1, n+1):
qml.Hadamard(wires=i)
# Apply controlled unitary operations
qml.ControlledSequence(qml.QubitUnitary(U, wires=n+1), control=range(1,n+1))
# Apply inverse QFT
qml.adjoint(qml.QFT)(wires=range(1,n+1))
# Apply controlled rotations for |lambda> -> |lambda> (sqrt(1-lambda^2) |0> + lambda |1>)
MultipleControlledRY([0], range(1, n+1), lamb1, lamb2)
# Apply QFT
qml.QFT(wires=range(1,n+1))
# Apply controlled unitary operations
qml.ControlledSequence(qml.QubitUnitary(U_inv, wires=n+1), control=range(1,n+1))
# Apply Hadamard gate to the c-register
for i in range(1, n+1):
qml.Hadamard(wires=i)
# Return the state of the last qubit and the measurement result
return qml.sample(wires=[0, n+1])
def circuit(x):
lamb_prob = eigenvalue_circuit(x)
# lamb_cand = np.arange(2**n) / 2**n
sorted_lamb_prob = np.argsort(lamb_prob)[::-1]
lamb1 = sorted_lamb_prob[0] / 2**(n)
lamb2 = sorted_lamb_prob[1] / 2**(n)
print(lamb1, lamb2)
samples = final_circuit(x, lamb1, lamb2)
return samples
return circuit, (dev1, eigenvalue_circuit), (dev2, final_circuit)
A = np.array([[0.5, 0.25], [0.25, 0.5]])
x = np.array([1, 2])
A @ x
eigv = np.linalg.eig(A)
print(eigv)
qmm_circuit, (dev1, ec), (dev2, fc) = gen_qmm(2, A)
qml.draw_mpl(ec)(x)
plt.show()
qml.draw_mpl(fc)(x, 0.25, 0.75)
plt.show()
result = qmm_circuit(x)
result
meas_one = result[:,0] == 1
result_zero = result[meas_one & (result[:,1] == 0)]
result_one = result[meas_one & (result[:,1] == 1)]
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(result[:,0], result[:,1])
cm
import matplotlib.pyplot as plt
import seaborn as sns
sns.heatmap(cm, annot=True, fmt='d')
plt.show()
res = np.array([result_zero.shape[0], result_one.shape[0]])
res
np.sqrt(res) / np.linalg.norm(np.sqrt(res))
B = A @ x
B / np.linalg.norm(B)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0)
plot_circuit_layout(new_circ_lv0, backend)
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from IPython.display import IFrame
IFrame(src="http://www.youtube.com/embed/tBnWG_95F9c", width=1920/2, height=1080/2)
from qiskit import *
circuit = QuantumCircuit(1,1)
circuit.x(0)
%matplotlib inline
circuit.draw(output='mpl')
simulator = Aer.get_backend('unitary_simulator')
result = execute(circuit, backend=simulator).result()
unitary = result.get_unitary()
print(unitary)
from qiskit import *
circuit = QuantumCircuit(1,1)
circuit.x(0)
simulator = Aer.get_backend('statevector_simulator')
result = execute(circuit, backend=simulator).result()
statevector = result.get_statevector()
print(statevector)
# in the video, we imported from qiskit.tools.visualization.
# this part of Qiskit has been moved to qiskit.visualization, and we recommend using qiskit.visualization instead
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(statevector)
circuit = QuantumCircuit(1,1)
circuit.x(0)
circuit.measure([0], [0])
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator, shots=1024).result()
counts = result.get_counts()
from qiskit.visualization import plot_histogram
plot_histogram(counts)
qiskit.__qiskit_version__
import qiskit.tools.jupyter
%qiskit_copyright
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Symmetric informationally complete (SIC)-POVM tomography preparation basis.
"""
# Needed for functions
import numpy as np
# Import QISKit classes
from qiskit import QuantumCircuit
from .tomographybasis import TomographyBasis
###########################################################################
# Built-in circuit functions
###########################################################################
def sicpovm_preparation_circuit(op, qubit):
"""
Return a SIC-POVM projector preparation circuit.
This circuit assumes the qubit is initialized in the Zp eigenstate [1, 0].
Params:
op (str): SIC-POVM element label 'S0', 'S1', 'S2' or 'S3'.
qubit (QuantumRegister tuple): qubit to be prepared.
Returns:
A QuantumCircuit object.
"""
circ = QuantumCircuit(qubit[0])
theta = -2 * np.arctan(np.sqrt(2))
if op == 'S1':
circ.u3(theta, np.pi, 0.0, qubit)
if op == 'S2':
circ.u3(theta, np.pi / 3, 0.0, qubit)
if op == 'S3':
circ.u3(theta, -np.pi / 3, 0.0, qubit)
return circ
###########################################################################
# Matrix functions for built-in bases
###########################################################################
def sicpovm_preparation_matrix(label):
"""
Return the matrix corresonding to a SIC-POVM preparation.
Args:
label (str): single-qubit SIC-POVM element label.
Returns:
A Numpy array for the SIC-POVM element.
Allowed inputs and corresponding returned matrices are:
'S0' : [[1, 0], [0, 0]]
'S1' : [[1, np.sqrt(2)], [np.sqrt(2), 2]]/ 3
'S2' : [[1, exp(pi * 2j / 3) * sqrt(2)],
[exp(-pi * 2j / 3) * sqrt(2), 2]] / 3
'S3' : [[1, exp(-pi * 2j / 3) * sqrt(2)],
[exp(pi * 2j / 3) * sqrt(2), 2]] / 3
"""
res = np.array([])
# Return matrix for allowed label
if label == 'S0':
res = np.array([[1, 0], [0, 0]], dtype=complex)
if label == 'S1':
res = np.array([[1, np.sqrt(2)], [np.sqrt(2), 2]], dtype=complex) / 3
if label == 'S2':
res = np.array([[1, np.exp(np.pi * 2j / 3) * np.sqrt(2)],
[np.exp(-np.pi * 2j / 3) * np.sqrt(2), 2]]) / 3
if label == 'S3':
res = np.array([[1, np.exp(-np.pi * 2j / 3) * np.sqrt(2)],
[np.exp(np.pi * 2j / 3) * np.sqrt(2), 2]]) / 3
return res
###########################################################################
# PauliBasis Object
###########################################################################
SICBasis = TomographyBasis('SIC', measurement=None,
preparation=(('S0', 'S1', 'S2', 'S3'),
sicpovm_preparation_circuit,
sicpovm_preparation_matrix))
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
"""Docstring."""
from qiskit import QuantumCircuit, execute, QuantumRegister, ClassicalRegister
from qiskit_aer import Aer
class Random:
"""Demo random."""
def __init__(self):
"""Demo random."""
self.pow = 2
self.qasm = Aer.get_backend("aer_simulator")
def run(self, number: int) -> int:
"""Run method."""
nb_qubits = number
print("Generate random number")
circ = QuantumRegister(nb_qubits, "the number")
meas = ClassicalRegister(nb_qubits, "measurement")
quant_circ = QuantumCircuit(circ, meas)
for i in range(0, nb_qubits):
quant_circ.x(i)
quant_circ.measure(circ, meas)
job = execute(quant_circ, self.qasm, shots=1, memory=True)
result_sim = job.result()
memory = result_sim.get_memory()
result = int(memory[0], 2) + 1
return result
def __repr__(self):
return f"Random(circuit of: {self.pow})"
|
https://github.com/abhishekchak52/quantum-computing-course
|
abhishekchak52
|
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import *
from qiskit.quantum_info import *
q1_sv = Statevector.from_label('+') # Available basis states are 0, 1, +, -, l, r
print(q1_sv.data)
q1_sv.is_valid()
print(q1_sv.probabilities_dict())
print(sum(q1_sv.probabilities()))
outcome, new_sv = q1_sv.measure() # This returns two values
print(f'The outcome of measurement was {outcome}')
print(f'The collapsed statevector after measurement is {new_sv.data}')
outcome2, new2_sv = new_sv.measure() # This returns two values
print('Measured collapsed statevector')
print(f'The outcome of measurement was {outcome2}')
print(f'The collapsed statevector after measurement is {new2_sv.data}')
q1_sv = Statevector.from_label('+')
measured_values = [int(q1_sv.measure()[0]) for _ in range(1000)]
print(f'Number of 0 measured: {measured_values.count(0)}, Number of 1 measured: {measured_values.count(1)}')
q1_sv = Statevector.from_label('+') # Available basis states are 0, 1, +, -, l, r
plot_bloch_multivector(q1_sv)
op1 = Operator.from_label('X') # I, X, Y, Z, S, T, H
print(op1.data)
op1.is_unitary()
op1_adj = op1.adjoint()
print(op1_adj.data)
res = op1*op1_adj
print(res.data)
q2_sv_0 = Statevector.from_label('+')
plot_bloch_multivector(q2_sv_0)
op1 = Operator.from_label('Z')
q2_sv_1 = q2_sv_0.evolve(op1)
plot_bloch_multivector(q2_sv_1)
op2 = Operator.from_label('Z')
q2_sv_2 = q2_sv_1.evolve(op2.adjoint())
plot_bloch_multivector(q2_sv_2)
print(q2_sv_0 == q2_sv_2)
qc = QuantumCircuit(1)
qc.h(0)
qc.z(0)
qc.draw(output='mpl')
visualize_transition(qc, trace=True)
qc = QuantumCircuit(1)
qc.h(0)
qc.z(0)
qc.measure_all()
qc.draw(output='mpl')
job = execute(qc, backend=QasmSimulator(), shots=1024)
plot_histogram(job.result().get_counts())
job.result().get_counts()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
from qiskit import * # import tudo do qiskit
# Determina o número de qubits e de cbits a serem utilizados
qr = QuantumRegister(2) # determina quantos qubits serão usados
cr = ClassicalRegister(2) # determina quantos cbits serão usados
# Constrói o circuito quântico
qc = QuantumCircuit(qr, cr)
# para o circuitos quânticos ficarem mais apresentáveis
%matplotlib inline
qc.draw(output='mpl') # mostra o circuito
# adiciona a porta lógica de Hadamard ao circuito, aplicada no qubit (registro quântico) 0
qc.h(qr[0]); # tem que usar ; pra não dar aviso
qc.draw(output = 'mpl') # o output = 'mpl' é para a figura ficar mais apresentável
# adiciona uma controll-not ao circuito, com o controle sendo qr[0] e o target sendo qr[1]
qc.cx(qr[0],qr[1]);
# é importante sempre mandar mostrar o circuito, pra ter certeza que é realmente o que queremos construir
qc.draw(output = 'mpl')
# adiciona medidas em todos os qubits (a ser usada quando queremos acessar a distribuições de probabilidades)
qc.measure(qr,cr);
qc.draw(output = 'mpl')
# Determina o backend a ser usado, que poder ser um simulador ou um chip real
# Neste caso escolhemos o simulador qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# número de medidas para estimativa de uma distribuição de probabilidades
nshots = 8192
# executa o circuito qc no backend escolhido
result = execute(qc, backend = simulator, shots = nshots).result()
# para visualizar o histograma da distribuicao de probabilidades
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(qc))
counts = result.get_counts(qc); counts, counts['00']
# carrega minha conta no IBMQ (o ID foi incluido no outro arquivo, nao precisa incluir aqui)
qiskit.IBMQ.load_account();
#provider = IBMQ.get_provider('ibm-q')
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
# determina em qual backend vamos executar o circuito
device = provider.get_backend('ibmq_casablanca')
# se certifica que o backend esta certo
device.name()
# executa o circuito quantico qc no CQ escolhido
job = execute(qc, backend = device, shots = nshots)
from qiskit.tools.monitor import job_monitor
# para monitorar a execucao do circuito
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(qc))
|
https://github.com/GroenteLepel/qiskit-quantum-knn
|
GroenteLepel
|
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)
from qiskit_quantum_knn.qknn.qknn_construction import create_qknn
test_data = [1, 0]
train_data = [
[1, 0],
[1, 0]
]
circuit = create_qknn(test_data, train_data, add_measurement=True)
print(circuit.draw())
|
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.
"""
Module defining Qiskit OpenQASM conversions
"""
from typing import TYPE_CHECKING
from qbraid_core._import import LazyLoader
from qbraid.transpiler.annotations import weight
qiskit = LazyLoader("qiskit", globals(), "qiskit")
if TYPE_CHECKING:
import qiskit as qiskit_
@weight(1)
def qasm2_to_qiskit(qasm: str) -> "qiskit_.QuantumCircuit":
"""Returns a Qiskit circuit equivalent to the input OpenQASM 2 string.
Args:
qasm: OpenQASM 2 string to convert to a Qiskit circuit.
Returns:
Qiskit.QuantumCircuit object equivalent to the input OpenQASM 2 string.
"""
return qiskit.QuantumCircuit.from_qasm_str(qasm)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can show the phase of each state and use
# degrees instead of radians
from qiskit.quantum_info import DensityMatrix
import numpy as np
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
qc.z(1)
matrix = DensityMatrix(qc)
plot_state_qsphere(matrix,
show_state_phases = True, use_degrees = True)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.quantumcircuitdata import CircuitInstruction
from qiskit.circuit import Measure
from qiskit.circuit.library import HGate, CXGate
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
instructions = [
CircuitInstruction(HGate(), [qr[0]], []),
CircuitInstruction(CXGate(), [qr[0], qr[1]], []),
CircuitInstruction(Measure(), [qr[0]], [cr[0]]),
CircuitInstruction(Measure(), [qr[1]], [cr[1]]),
]
circuit = QuantumCircuit.from_instructions(instructions)
circuit.draw("mpl")
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
%matplotlib inline
from qiskit import *
from qiskit.visualization import *
from qiskit.tools.monitor import *
from qiskit.aqua import *
from qiskit.aqua.components.oracles import *
from qiskit.aqua.algorithms import *
oracle = TruthTableOracle("0101")
oracle.construct_circuit().draw(output='mpl')
dj = DeutschJozsa(oracle)
dj.construct_circuit(measurement=True).draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend)
result = dj.run(quantum_instance)
print(result)
oracle2 = TruthTableOracle('00000000')
dj2 = DeutschJozsa(oracle2)
result = dj2.run(quantum_instance)
print("The function is",result['result'])
backend = Aer.get_backend('qasm_simulator')
oracle3 = TruthTableOracle('0001')
g = Grover(oracle3, iterations=1)
result = g.run(quantum_instance)
print(result)
expression = '(x | y) & (~y | z) & (~x | ~z | w) & (~x | y | z | ~w)'
oracle4 = LogicalExpressionOracle(expression)
g2 = Grover(oracle4, iterations = 3)
result = g2.run(quantum_instance)
print(result)
backend = Aer.get_backend('qasm_simulator')
expression2 = '(x & y & z & w) | (~x & ~y & ~z & ~w)'
#expression2 = '(x & y) | (~x & ~y)'
oracle5 = LogicalExpressionOracle(expression2, optimization = True)
g3 = Grover(oracle5, incremental = True)
result = g3.run(quantum_instance)
print(result)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
for _ in range(100):
depths.append(
transpile(
ghz,
backend,
layout_method='trivial' # Fixed layout mapped in circuit order
).depth()
)
plt.figure(figsize=(8, 6))
plt.hist(depths, align='left', color='#AC557C')
plt.xlabel('Depth', fontsize=14)
plt.ylabel('Counts', fontsize=14);
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
circ.draw(output='mpl')
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.