repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 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/scaleway/qiskit-scaleway
|
scaleway
|
# Copyright 2024 Scaleway
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from qiskit import QuantumCircuit
from qiskit_scaleway import ScalewayProvider
provider = ScalewayProvider(
project_id="<your-scaleway-project-id>",
secret_key="<your-scaleway-secret-key>",
)
# Retrieve a backend by providing search criteria. The search must have a single match
backend = provider.get_backend("aer_simulation_2l4")
# Define a quantum circuit that produces a 4-qubit GHZ state.
qc = QuantumCircuit(4)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.measure_all()
# Create and send a job to the new QPU's session (or on an existing one)
result = backend.run(qc, shots=1000).result()
if result.success:
print(result.get_counts())
else:
print(result.to_dict()["error"])
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import qiskit
from qiskit import *
from qiskit import Aer
import pandas as pd
from qiskit.providers.aer.noise.noise_model import NoiseModel
from qiskit.test.mock import *
from qiskit.providers.aer import AerSimulator, QasmSimulator
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
import itertools
import mitiq
import argparse
import cma
import os
import sys
from qiskit import IBMQ
import pickle
import random
import re
from pprint import pprint
#! ここからmainの実行処理
IBMQ.load_account()
# provider = IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
print("provider:", provider)
L = 3
p = 2
dt = 1.0
tf = 20
shots = 8192
#TODO 外部実装
def TwirlCircuit(circ: str) -> QuantumCircuit:
#! qasm ベタ書き
def apply_pauli(num: int, qb: int) -> str:
if (num == 0):
return f'id q[{qb}];\n'
elif (num == 1):
return f'x q[{qb}];\n'
elif (num == 2):
return f'y q[{qb}];\n'
else:
return f'z q[{qb}];\n'
paulis = [(i,j) for i in range(0,4) for j in range(0,4)]
paulis.remove((0,0))
paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)]
new_circ = ''
ops = circ.qasm().splitlines(True) #! 生のqasmコードを持ってきてる: オペレータに分解
for op in ops:
if (op[:2] == 'cx'): # can add for cz, etc.
num = random.randrange(len(paulis))
qbs = re.findall('q\[(.)\]', op)
new_circ += apply_pauli(paulis[num][0], qbs[0])
new_circ += apply_pauli(paulis[num][1], qbs[1])
new_circ += op
new_circ += apply_pauli(paulis_map[num][0], qbs[0])
new_circ += apply_pauli(paulis_map[num][1], qbs[1])
else:
new_circ += op
return qiskit.circuit.QuantumCircuit.from_qasm_str(new_circ)
#! convert 完了
def TrotterEvolveCircuit(dt, nt, init):
"""
Implements trotter evolution of the Heisenberg hamiltonian using the circuit from https://arxiv.org/pdf/1906.06343.pdf #! 要チェック
:param tf: time to evolve to #! dt * nt = tf ???
:param nt: number of trotter steps to use
:param init: initial state for the trotter evolution. Should be another Qiskit circuit
外部変数: L
"""
# def get_angles(a, b, c):
# return (np.pi/2 - 2*c, 2*a - np.pi/2, np.pi/2 - 2*b)
def get_angles(a):
#! 角度計算, aはalpha, return値タプルの0はtheta, 1はphi, 2はlambd = theta
return (np.pi/2 - 2*a, 2*a - np.pi/2, np.pi/2 - 2*a)
def N(cir, qb0, qb1):
#! fig 4を実装: thetaとphiとlambdはglobal変数
#! cnotのdepthは3
cir.rz(-np.pi/2, qb1)
cir.cnot(qb1, qb0)
cir.rz(theta, qb0)
cir.ry(phi, qb1)
cir.cnot(qb0, qb1)
cir.ry(lambd, qb1)
cir.cnot(qb1, qb0)
cir.rz(np.pi/2, qb0)
return cir
#! dtはtrotter step size ← step sizeとは??? (default: 0.25)
theta, phi, lambd = get_angles(-dt/4) #! why divided by 4??? 少なくとも時間間隔ではある
circ = init
for i in range(nt): #! ntはTrotterステップ数 (ここではcnotが深さnt * 3かかる)
# even (odd indices)
if (L % 2 == 0): #! Lはsystem size
# UEven
for i in range(1, L-1, 2): # L for periodic bdy conditions
circ = N(circ, i, (i+1)%L)
# UOdd
for i in range(0, L-1, 2):
circ = N(circ, i, (i+1)%L)
else:
# UEven
for i in range(1, L, 2):
circ = N(circ, i, (i+1)%L)
# UOdd
for i in range(0, L-1, 2):
circ = N(circ, i, (i+1)%L)
# UBdy
# circ = N(circ, L-1, 0)
return circ
#! convert完了
def AnsatzCircuit(params: list, p: int) -> QuantumCircuit:
"""
Implements HVA ansatz using circuits from https://arxiv.org/pdf/1906.06343.pdf #! 要チェック
#! HVA := Hamiltonian Variational Ansatz
:param params: parameters to parameterize circuit
:param p: depth of the ansatz
外部変数: L, p
"""
circ = QuantumCircuit(L) #! L = system size
def get_angles(a): #! 回転角度の計算 (肩に乗せるやつ)
return (np.pi/2 - 2*a, 2*a - np.pi/2, np.pi/2 - 2*a)
def N(cir, angles, qb0, qb1):
#! angles = (theta, phi, lambd)
cir.rz(-np.pi/2, qb1)
cir.cnot(qb1, qb0)
cir.rz(angles[0], qb0)
cir.ry(angles[1], qb1)
cir.cnot(qb0, qb1)
cir.ry(angles[2], qb1)
cir.cnot(qb1, qb0)
cir.rz(np.pi/2, qb0)
return cir
for i in range(p):
if (L % 2 == 0):
for j in range(1, L-1, 2): # L for periodic bdy conditions #! periodicなので、Lで割って、0とn-1にまたがる回路が存在する
circ = N(circ, get_angles(-params[((L-1)*i)+j]/4), j, (j+1)%L)
for j in range(0, L-1, 2):
circ = N(circ, get_angles(-params[((L-1)*i)+j]/4), j, (j+1)%L)
else:
for j in range(1, L, 2):
circ = N(circ, get_angles(-params[((L-1)*i)+j]/4), j, (j+1)%L)
for j in range(0, L-1, 2):
circ = N(circ, get_angles(-params[((L-1)*i)+j]/4), j, (j+1)%L)
# circ = N(circ, get_angles(-params[(L*i)+L-1]/4), L-1, 0) # boundary
return circ
#TODO reverse_bitを適宜挟む
def ReorderBasis(circ):
"""
#! changing the big endian to little endian
#! unnecessary function: equal to reverse_bit() method
Reorders basis so that 0th qubit is on the left side of the tensor product
:param circ: circuit to reorder, can also be a vector
"""
if (isinstance(circ, qiskit.circuit.quantumcircuit.QuantumCircuit)):
for i in range(L//2):
circ.swap(i, L-i-1)
return circ
else:
perm = np.eye(2**L)
for i in range(1, 2**L//2):
perm[:, [i, 2**L-i-1]] = perm[:, [2**L-i-1, i]]
return perm @ circ
#TODO VTCとは別実装?→ no, 同じ実装に。
def SimulateAndReorder(circ):
"""
#! execution wrapper
Executes a circuit using the statevector simulator and reorders basis to match with standard
"""
circ = ReorderBasis(circ)
backend = Aer.get_backend('statevector_simulator')
return execute(circ, backend).result().get_statevector()
#TODO
def Simulate(circ):
"""
#! execution wrapper
Executes a circuit using the statevector simulator. Doesn't reorder -- which is needed for intermediate steps in the VTC
"""
backend = Aer.get_backend('statevector_simulator')
return execute(circ, backend).result().get_statevector()
#TODO
def LoschmidtEchoExecutor(circuits, backend, shots, filter):
"""
#! 回路を実行
Returns the expectation value to be mitigated.
:param circuit: Circuit to run. #! ここでのcircuitsは
:param backend: backend to run the circuit on
:param shots: Number of times to execute the circuit to compute the expectation value.
:param fitter: measurement error mitigator
"""
# circuits = [TwirlCircuit(circ) for circ in circuits]
scale_factors = [1.0, 2.0, 3.0] #! ZNEのノイズスケーリングパラメタ
folded_circuits = [] #! ZNE用の回路
for circuit in circuits:
folded_circuits.append([mitiq.zne.scaling.fold_gates_at_random(circuit, scale) for scale in scale_factors]) #! ここでmitiqを使用
folded_circuits = list(itertools.chain(*folded_circuits)) #! folded_circuitsを平坦化
folded_circuits = [TwirlCircuit(circ) for circ in folded_circuits] #! 後からPauli Twirlingを施す!
print("length of circuit in job", len(folded_circuits))
#! jobを投げる
job = qiskit.execute(
experiments=folded_circuits,
backend=backend,
optimization_level=0,
shots=shots
)
print("casted job")
c = ['1','1','0'] #! これをpermutationする
# c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)]
c = ''.join(c)[::-1] #! endianを反転 (big endianへ)
res = job.result()
if (filter is not None): #! QREM
res = filter.apply(res)
print("retrieved job")
all_counts = [job.result().get_counts(i) for i in range(len(folded_circuits))]
expectation_values = []
for counts in all_counts:
total_allowed_shots = [counts.get(''.join(p)) for p in set(itertools.permutations(c))] #! ここでcをpermutationしている
total_allowed_shots = sum([0 if x is None else x for x in total_allowed_shots])
if counts.get(c) is None:
expectation_values.append(0)
else:
expectation_values.append(counts.get(c)/total_allowed_shots)
# expectation_values = [counts.get(c) / shots for counts in all_counts]
zero_noise_values = []
if isinstance(backend, qiskit.providers.aer.backends.qasm_simulator.QasmSimulator): # exact_sim
for i in range(len(circuits)):
zero_noise_values.append(np.mean(expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)]))
else: #device_sim, real_device
fac = mitiq.zne.inference.LinearFactory(scale_factors)
for i in range(len(circuits)):
zero_noise_values.append(fac.extrapolate(scale_factors,
expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)]))
print("zero_noise_values")
pprint(zero_noise_values)
print()
return zero_noise_values
#TODO
def LoschmidtEchoCircuit(params, U_v, U_trot, init, p):
"""
#! 回路を作成
Cost function using the Loschmidt Echo. Just using statevectors currently -- can rewrite using shots
:param params: parameters new variational circuit that represents U_trot U_v | init >. Need dagger for cost function
:param U_v: variational circuit that stores the state before the trotter step
:param U_trot: trotter step
:param init: initial state
:param p: number of ansatz steps
"""
U_v_prime = AnsatzCircuit(params, p)
circ = init + U_v + U_trot + U_v_prime.inverse()
circ.measure_all()
return circ
def LoschmidtEcho(params, U_v, U_trot, init, p, backend, shots, filter):
"""
#! 実行パート
"""
circs = []
for param in params:
circs.append(LoschmidtEchoCircuit(param, U_v, U_trot, init, p)) #! 回路を作成
print("length of circuits without zne:", len(circs))
res = LoschmidtEchoExecutor(circs, backend, shots, filter) #! 回路を実行
return abs(1 - np.array(res))
def LoschmidtEchoExact(params, U_v, U_trot, init, p):
"""
#! unused function
"""
U_v_prime = AnsatzCircuit(params, p)
circ = init + U_v + U_trot + U_v_prime.inverse()
circ_vec = Simulate(circ)
init_vec = Simulate(init)
return 1 - abs(np.conj(circ_vec) @ init_vec)**2
def CMAES(U_v, U_trot, init, p, backend, shots, filter):
"""
#! 実行 + 最適化パート
"""
init_params = np.random.uniform(0, 2*np.pi, (L-1)*p)
es = cma.CMAEvolutionStrategy(init_params, np.pi/2)
es.opts.set({'ftarget':5e-3, 'maxiter':1000})
# es = pickle.load(open(f'./results_{L}/optimizer_dump', 'rb'))
while not es.stop(): #! 最適化パート
# solutions = es.ask(25) # ! 25 = number of returned solutions
solutions = es.ask(1)
print("solutions")
pprint(solutions)
es.tell(solutions, LoschmidtEcho(solutions, U_v, U_trot, init, p, backend, shots, filter)) #! 実行パート
# es.tell(solutions, LoschmidtEchoExact(solutions, U_v, U_trot, init, p)) #! 実行パート
es.disp()
open(f'./results_{L}/optimizer_dump', 'wb').write(es.pickle_dumps())
return es.result_pretty()
def VTC(tf, dt, p, init, backend, shots, filter):
"""
#! tf: 総経過時間
#! dt: trotter step size: 時間間隔
#! p: ansatzのステップ数
"""
VTCParamList = [np.zeros((L-1)*p)] #! デフォルトのパラメタ(初期値)
VTCStepList = [SimulateAndReorder(init.copy())] #! type: List[Statevector]
# TrotterFixStepList = [init]
TimeStep = [0]
if (os.path.exists(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv')): #! 2巡目からこっち
VTCParamList = pd.read_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0)
VTCStepList = pd.read_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0)
temp = VTCParamList.iloc[-1]
print(temp, "th time interval")
U_v = AnsatzCircuit(temp, p)
else: #! 最初はこっちに入る
VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep))
VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep))
print("0 th time interval")
print()
U_v = QuantumCircuit(L)
ts = VTCParamList.index
#! 時間間隔
U_trot = TrotterEvolveCircuit(dt, p, QuantumCircuit(L)) #! Trotter分解のunitaryを作る
print()
print("start CMAES")
print()
res = CMAES(U_v, U_trot, init, p, backend, shots, filter) #! ここでプロセスを実行!!!!
print()
print("res")
pprint(res)
#! 新しいループ結果を追加し、tsを更新
res = res.xbest # ! best solution evaluated
print("res.xbest")
pprint(res)
VTCParamList.loc[ts[-1]+(dt*p)] = np.array(res)
VTCStepList.loc[ts[-1]+(dt*p)] = np.array(SimulateAndReorder(init + AnsatzCircuit(res, p)))
ts = VTCParamList.index
# VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep))
# VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep))
#! csvファイルを更新
VTCParamList.to_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv')
VTCStepList.to_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv')
if (ts[-1] >= tf):
return
else:
print("next step")
VTC(tf, dt, p, init, backend, shots, filter)
#! ここからQREM回路
qr = QuantumRegister(L)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# device_backend = FakeJakarta()
# device_sim = AerSimulator.from_backend(device_backend)
real_device = provider.get_backend('ibmq_jakarta')
noise_model = NoiseModel.from_backend(real_device)
device_sim = QasmSimulator(method='statevector', noise_model=noise_model)
exact_sim = Aer.get_backend('qasm_simulator') # QasmSimulator(method='statevector')
t_qc = transpile(meas_calibs)
qobj = assemble(t_qc, shots=8192)
# cal_results = real_device.run(qobj, shots=8192).result()
cal_results = device_sim.run(qobj, shots=8192).result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print("qrem done")
# np.around(meas_fitter.cal_matrix, decimals=2)
init = QuantumCircuit(L)
# c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)]
c = ['1','1','0'] #! なぜinitial stateが110なの??????? もしかしてopen science prizeを意識???
#! けどループでこのプログラムが実行されるたびにここが|110>だとおかしくないか?
for q in range(len(c)):
if (c[q] == '1'):
init.x(q)
#! ここまでQREM回路
nt = int(np.ceil(tf / (dt * p)))
# f = open(f'./results_{L}/logging.txt', 'a')
# sys.stdout = f
#! tf: シミュレーションの(経過)時間
#! dt: trotter分解のステップ数
#! p: ansatzのステップ数 (論文中のL)
# VTC(tf, dt, p, init, real_device, shots, meas_fitter.filter) #! mainの処理
print("vtc start!!!! \n\n\n")
VTC(tf, dt, p, init, device_sim, shots, meas_fitter.filter) #! mainの処理
# f.close()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the QAOA algorithm."""
import unittest
from functools import partial
from test.python.algorithms import QiskitAlgorithmsTestCase
import numpy as np
import rustworkx as rx
from ddt import ddt, idata, unpack
from scipy.optimize import minimize as scipy_minimize
from qiskit import QuantumCircuit
from qiskit_algorithms.minimum_eigensolvers import QAOA
from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD
from qiskit.circuit import Parameter
from qiskit.primitives import Sampler
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.result import QuasiDistribution
from qiskit.utils import algorithm_globals
W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
P1 = 1
M1 = SparsePauliOp.from_list(
[
("IIIX", 1),
("IIXI", 1),
("IXII", 1),
("XIII", 1),
]
)
S1 = {"0101", "1010"}
W2 = np.array(
[
[0.0, 8.0, -9.0, 0.0],
[8.0, 0.0, 7.0, 9.0],
[-9.0, 7.0, 0.0, -8.0],
[0.0, 9.0, -8.0, 0.0],
]
)
P2 = 1
M2 = None
S2 = {"1011", "0100"}
CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0]
@ddt
class TestQAOA(QiskitAlgorithmsTestCase):
"""Test QAOA with MaxCut."""
def setUp(self):
super().setUp()
self.seed = 10598
algorithm_globals.random_seed = self.seed
self.sampler = Sampler()
@idata(
[
[W1, P1, M1, S1],
[W2, P2, M2, S2],
]
)
@unpack
def test_qaoa(self, w, reps, mixer, solutions):
"""QAOA test"""
self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, solutions)
@idata(
[
[W1, P1, S1],
[W2, P2, S2],
]
)
@unpack
def test_qaoa_qc_mixer(self, w, prob, solutions):
"""QAOA test with a mixer as a parameterized circuit"""
self.log.debug(
"Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s",
prob,
w,
)
optimizer = COBYLA()
qubit_op, _ = self._get_operator(w)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
theta = Parameter("θ")
mixer.rx(theta, range(num_qubits))
qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, solutions)
def test_qaoa_qc_mixer_many_parameters(self):
"""QAOA test with a mixer as a parameterized circuit with the num of parameters > 1."""
optimizer = COBYLA()
qubit_op, _ = self._get_operator(W1)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
for i in range(num_qubits):
theta = Parameter("θ" + str(i))
mixer.rx(theta, range(num_qubits))
qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
self.log.debug(x)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, S1)
def test_qaoa_qc_mixer_no_parameters(self):
"""QAOA test with a mixer as a parameterized circuit with zero parameters."""
qubit_op, _ = self._get_operator(W1)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
# just arbitrary circuit
mixer.rx(np.pi / 2, range(num_qubits))
qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
# we just assert that we get a result, it is not meaningful.
self.assertIsNotNone(result.eigenstate)
def test_change_operator_size(self):
"""QAOA change operator size test"""
qubit_op, _ = self._get_operator(
np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
)
qaoa = QAOA(self.sampler, COBYLA(), reps=1)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest(msg="QAOA 4x4"):
self.assertIn(graph_solution, {"0101", "1010"})
qubit_op, _ = self._get_operator(
np.array(
[
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
]
)
)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest(msg="QAOA 6x6"):
self.assertIn(graph_solution, {"010101", "101010"})
@idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]])
@unpack
def test_qaoa_initial_point(self, w, solutions, init_pt):
"""Check first parameter value used is initial point as expected"""
qubit_op, _ = self._get_operator(w)
first_pt = []
def cb_callback(eval_count, parameters, mean, metadata):
nonlocal first_pt
if eval_count == 1:
first_pt = list(parameters)
qaoa = QAOA(
self.sampler,
COBYLA(),
initial_point=init_pt,
callback=cb_callback,
)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest("Initial Point"):
# If None the preferred random initial point of QAOA variational form
if init_pt is None:
self.assertLess(result.eigenvalue, -0.97)
else:
self.assertListEqual(init_pt, first_pt)
with self.subTest("Solution"):
self.assertIn(graph_solution, solutions)
def test_qaoa_random_initial_point(self):
"""QAOA random initial point"""
w = rx.adjacency_matrix(
rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
self.assertLess(result.eigenvalue, -0.97)
def test_optimizer_scipy_callable(self):
"""Test passing a SciPy optimizer directly as callable."""
w = rx.adjacency_matrix(
rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(
self.sampler,
partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}),
)
result = qaoa.compute_minimum_eigenvalue(qubit_op)
self.assertEqual(result.cost_function_evals, 5)
def _get_operator(self, weight_matrix):
"""Generate Hamiltonian for the max-cut problem of a graph.
Args:
weight_matrix (numpy.ndarray) : adjacency matrix.
Returns:
PauliSumOp: operator for the Hamiltonian
float: a constant shift for the obj function.
"""
num_nodes = weight_matrix.shape[0]
pauli_list = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))])
shift -= 0.5 * weight_matrix[i, j]
lst = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list]
return SparsePauliOp.from_list(lst), shift
def _get_graph_solution(self, x: np.ndarray) -> str:
"""Get graph solution from binary string.
Args:
x : binary string as numpy array.
Returns:
a graph solution as string.
"""
return "".join([str(int(i)) for i in 1 - x])
def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: Quasi-distribution.
Returns:
Binary string as numpy.ndarray of ints.
"""
values = list(state_vector.values())
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = np.zeros(n)
for i in range(n):
x[i] = k % 2
k >>= 1
return x
if __name__ == "__main__":
unittest.main()
|
https://github.com/carstenblank/qiskit-aws-braket-provider
|
carstenblank
|
# Copyright 2020 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from datetime import datetime
from typing import List, Dict
import pint
import qiskit
from braket.device_schema import DeviceCapabilities
from braket.device_schema.ionq import IonqDeviceCapabilities
from braket.device_schema.rigetti import RigettiDeviceCapabilities
from braket.device_schema.simulators import GateModelSimulatorDeviceCapabilities
from qiskit.providers import BaseBackend
from qiskit.providers.models import QasmBackendConfiguration, BackendProperties
from qiskit.providers.models.backendproperties import Nduv
logger = logging.getLogger(__name__)
units = pint.UnitRegistry()
# noinspection PyTypeChecker
def aws_ionq_to_properties(properties: IonqDeviceCapabilities, configuration: QasmBackendConfiguration) -> BackendProperties:
updated_time: datetime = properties.service.updatedAt or datetime.now()
general: List[Nduv] = []
qubits: List[List[Nduv]] = []
gates: List[qiskit.providers.models.backendproperties.Gate] = []
# FIXME: qiskit has an absolutely rediculous unit conversion mechanism,
# see qiskit.providers.models.backendproperties.BackendProperties._apply_prefix,
# which means that since we have seconds (s) we need to convert them to milli-seconds otherwise we get a
# BackendPropertyError raised.
# per qubit: T1, T2, frequency, anharmonicity, readout_error, prob_meas0_prep1, prob_meas1_prep0
# (if possible)
qubits = [
[
Nduv(date=updated_time, name='T1', unit='ms',
value=(properties.provider.timing.get('T1') * units.seconds).m_as(units.milliseconds)),
Nduv(date=updated_time, name='T2', unit='ms',
value=(properties.provider.timing.get('T2') * units.seconds).m_as(units.milliseconds))
]
for _ in range(configuration.n_qubits)
]
# use native gates and all qubits possibilities: set gate_error and gate_length as parameters (Nduv)
def get_fidelities(qubits):
return properties.provider.fidelity.get('1Q' if len(qubits) == 1 else '2Q', {'mean': None}) \
.get('mean')
def get_timings(qubits):
return properties.provider.timing.get('1Q' if len(qubits) == 1 else '2Q')
gates = [
qiskit.providers.models.backendproperties.Gate(
gate=b.name,
qubits=qubits,
parameters=[
Nduv(date=updated_time, name='gate_error', unit='',
value=1 - get_fidelities(qubits)),
Nduv(date=updated_time, name='gate_length', unit='ms',
value=(get_timings(qubits) * units.seconds).m_as(units.milliseconds))
])
for b in configuration.gates for qubits in b.coupling_map
]
# General Measurements maybe of interest / any other interesting measurement (like cross-talk)
general = [
Nduv(date=updated_time, name='spam_fidelity', unit='',
value=properties.provider.fidelity.get('spam', {'mean': None}).get('mean')),
Nduv(date=updated_time, name='readout_time', unit='ms',
value=(properties.provider.timing.get('readout') * units.seconds).m_as(units.milliseconds)),
Nduv(date=updated_time, name='reset_time', unit='ms',
value=(properties.provider.timing.get('reset') * units.seconds).m_as(units.milliseconds))
]
backend_properties: BackendProperties = BackendProperties(
backend_name=configuration.backend_name,
backend_version=configuration.backend_version,
last_update_date=updated_time,
qubits=qubits,
gates=gates,
general=general
)
return backend_properties
# noinspection PyTypeChecker
def aws_rigetti_to_properties(properties: RigettiDeviceCapabilities, configuration: QasmBackendConfiguration) -> BackendProperties:
updated_time: datetime = properties.service.updatedAt or datetime.now()
general: List[Nduv] = []
qubits: Dict[str, List[Nduv]] = {}
gates: List[qiskit.providers.models.backendproperties.Gate] = []
specs: Dict[str, Dict[str, Dict[str, float]]] = properties.provider.specs
# TODO: check units!!
# per qubit: T1, T2, frequency, anharmonicity, readout_error, prob_meas0_prep1, prob_meas1_prep0
# (if possible)
one_qubit_specs: Dict[str, Dict[str, float]] = specs['1Q']
two_qubit_specs: Dict[str, Dict[str, float]] = specs['2Q']
qubits_dict = dict([
(q, [ # The default cannot be 0.0 exactly... TODO: find out what a good default value could be
Nduv(date=updated_time, name='T1', unit='ms', value=(q_specs.get('T1', 1e-9) * units.seconds).m_as(units.milliseconds)),
Nduv(date=updated_time, name='T2', unit='ms', value=(q_specs.get('T2', 1e-9) * units.seconds).m_as(units.milliseconds)),
Nduv(date=updated_time, name='readout_error', unit='', value=q_specs.get('fRO')),
])
for q, q_specs in one_qubit_specs.items()
])
qubits = list(qubits_dict.values())
# use native gates and all qubits possibilities: set gate_error and gate_length as parameters (Nduv)
def get_fidelities(qubits):
if len(qubits) == 1:
q = configuration.coupling_canonical_2_device[qubits[0]]
stats: Dict[str, float] = one_qubit_specs[q]
return stats.get('f1Q_simultaneous_RB')
else:
q = "-".join([configuration.coupling_canonical_2_device[q] for q in sorted(qubits)])
stats: Dict[str, float] = two_qubit_specs[q]
return stats.get('fCZ')
gates = [
qiskit.providers.models.backendproperties.Gate(
gate=b.name,
qubits=q,
parameters=[
Nduv(date=updated_time, name='gate_error', unit='', value=1 - get_fidelities(q)),
Nduv(date=updated_time, name='gate_length', unit='ns', value=60 if len(q) == 1 else 160 if len(q) else None)
])
for b in configuration.gates for q in b.coupling_map
]
# General Measurements maybe of interest / any other interesting measurement (like cross-talk)
general = []
backend_properties: BackendProperties = BackendProperties(
backend_name=configuration.backend_name,
backend_version=configuration.backend_version,
last_update_date=updated_time,
qubits=qubits,
gates=gates,
general=general
)
# backend_properties._qubits = qubits
return backend_properties
# noinspection PyTypeChecker
def aws_simulator_to_properties(properties: GateModelSimulatorDeviceCapabilities, configuration: QasmBackendConfiguration) -> BackendProperties:
updated_time: datetime = properties.service.updatedAt or datetime.now()
general: List[Nduv] = []
qubits: List[List[Nduv]] = []
gates: List[qiskit.providers.models.backendproperties.Gate] = []
backend_properties: BackendProperties = BackendProperties(
backend_name=configuration.backend_name,
backend_version=configuration.backend_version,
last_update_date=updated_time,
qubits=qubits,
gates=gates,
general=general
)
return backend_properties
# noinspection PyTypeChecker
def aws_general_to_properties(properties: DeviceCapabilities, configuration: QasmBackendConfiguration) -> BackendProperties:
updated_time: datetime = properties.service.updatedAt or datetime.now()
general: List[Nduv] = []
qubits: List[List[Nduv]] = []
gates: List[qiskit.providers.models.backendproperties.Gate] = []
backend_properties: BackendProperties = BackendProperties(
backend_name=configuration.name,
backend_version=configuration.arn,
last_update_date=updated_time,
qubits=qubits,
gates=gates,
general=general
)
return backend_properties
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
# TODO: This example should use a real mock backend.
backend = FakeOpenPulse3Q()
d2 = pulse.DriveChannel(2)
with pulse.build(backend) as bell_prep:
pulse.u2(0, math.pi, 0)
pulse.cx(0, 1)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_prep)
pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
import numpy as np
from sklearn.utils import shuffle
import matplotlib.pyplot as plt
data1Path = r'../../dataset/data0.txt'
data1Label = r'../../dataset/data0label.txt'
dataCoords = np.loadtxt(data1Path)
dataLabels = np.loadtxt(data1Label)
# Make a data structure which is easier to work with
# for shuffling.
# Also, notice we change the data labels from {0, 1} to {-1, +1}
data = list(zip(dataCoords, 2*dataLabels-1))
shuffled_data = shuffle(data)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o')
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o')
from IPython.display import Image
import sys
sys.path.append('../../Pyfiles')
from circuits import *
from qiskit.circuit import Parameter
#circuit 1
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(62):
theta.append((Parameter('θ'+str(i))))
qc=circuit1(qc,qr,theta,1,0)
#load the simulation functcions from the quantumcircuit.py file
from quantumcircuit import *
#location,label,param,[circuit#,layer]
loss_qubitF([0.5,0.5],-1,[0,0,0,-5,0,0,0,0],[0,1])
#load the SPSA optimizer from the optimizer.py file
from optimizer import *
c = 0.5
a = 0.5
# Do the updates
lossList = []
coeffsList = []
paramsList = []
accuracyList = []
np.random.seed(2)
currentParams = pi*np.random.uniform(size=8)
for j in range(10):
cj = c/(j+1)**(1/2)
aj = a/(j+1)
# Grab a subset of the data for minibatching
#np.random.seed(j)
np.random.seed(2)
#data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data))
data_ixs = np.random.choice(len(data), size=100)
# Evaluate the loss over that subset
# We include a regularization term at the end
L = lambda x: np.sum([loss_qubitF(data[j][0],data[j][1],x,[0,1]) for j in data_ixs])/len(data_ixs)
lossList.append(L(currentParams))
coeffsList.append((cj, aj))
paramsList.append(currentParams)
accuracyList.append(np.sum([predict_qubitF(data[j][0],currentParams,[0,1]) ==data[j][1] for j in data_ixs])/len(data_ixs))
print(j,"th iteration L=",lossList[-1],"Accuracy =",accuracyList[-1])
currentParams = SPSA_update(L, currentParams, aj, cj)
fig = plt.figure(figsize=(15, 10))
ax = fig.add_subplot(2, 2, 1)
ax.plot(lossList)
ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3)))
ax.set_yscale('log')
ax = fig.add_subplot(2, 2, 2)
ax.plot(accuracyList)
ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3)))
ax.set_yscale('log')
ax = fig.add_subplot(2, 2, 3)
ax.plot([c[0] for c in coeffsList], label='a')
ax.plot([c[1] for c in coeffsList], label='c')
ax.legend(loc=0)
ax.set_title('Update coefficients')
ax = fig.add_subplot(2, 2, 4)
for j in range(4):
ax.plot([X[j] for X in paramsList], label='x{0}'.format(j))
ax.legend(loc=0)
ax.set_title('Parameter values')
ax.legend(loc=0)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o')
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o')
X = np.linspace(0, 1, num=10)
Z = np.zeros((len(X), len(X)))
# Contour map
for j in range(len(X)):
for k in range(len(X)):
# Fill Z with the labels (numerical values)
# the inner loop goes over the columns of Z,
# which corresponds to sweeping x-values
# Therefore, the role of j,k is flipped in the signature
Z[j, k] = predict_qubitF( np.array([X[k], X[j]]),currentParams,[0,1])
ax.contourf(X, X, Z, cmap='bwr', levels=30)
#circuit 2
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(62):
theta.append((Parameter('θ'+str(i))))
qc=circuit3(qc,qr,theta,1,0)
data1Path = r'../../dataset/data1a.txt'
data1Label = r'../../dataset/data1alabel.txt'
dataCoords = np.loadtxt(data1Path)
dataLabels = np.loadtxt(data1Label)
# Make a data structure which is easier to work with
# for shuffling.
# Also, notice we change the data labels from {0, 1} to {-1, +1}
data = list(zip(dataCoords, 2*dataLabels-1))
shuffled_data = shuffle(data)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o')
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o')
c = 1
a = 1
# Do the updates
lossList = []
coeffsList = []
paramsList = []
accuracyList = []
np.random.seed(2)
currentParams = pi*np.random.uniform(size=12)
for j in range(10):
cj = c/(j+1)**(1/2)
aj = a/(j+1)
# Grab a subset of the data for minibatching
#np.random.seed(j)
np.random.seed(3)
#data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data))
data_ixs = np.random.choice(len(data), size=100)
# Evaluate the loss over that subset
# We include a regularization term at the end
L = lambda x: np.sum([loss_qubitF(data[j][0],data[j][1],x,[2,1]) for j in data_ixs])/len(data_ixs)
lossList.append(L(currentParams))
coeffsList.append((cj, aj))
paramsList.append(currentParams)
accuracyList.append(np.sum([predict_qubitF(data[j][0],currentParams,[2,1]) ==data[j][1] for j in data_ixs])/len(data_ixs))
print(j,"th iteration L=",lossList[-1],"Accuracy =",accuracyList[-1])
currentParams = SPSA_update(L, currentParams, aj, cj)
fig = plt.figure(figsize=(15, 10))
ax = fig.add_subplot(2, 2, 1)
ax.plot(lossList)
ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3)))
ax.set_yscale('log')
ax = fig.add_subplot(2, 2, 2)
ax.plot(accuracyList)
ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3)))
ax.set_yscale('log')
ax = fig.add_subplot(2, 2, 3)
ax.plot([c[0] for c in coeffsList], label='a')
ax.plot([c[1] for c in coeffsList], label='c')
ax.legend(loc=0)
ax.set_title('Update coefficients')
ax = fig.add_subplot(2, 2, 4)
for j in range(4):
ax.plot([X[j] for X in paramsList], label='x{0}'.format(j))
ax.legend(loc=0)
ax.set_title('Parameter values')
ax.legend(loc=0)
currentParams
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o')
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o')
X = np.linspace(0, 1, num=10)
Z = np.zeros((len(X), len(X)))
# Contour map
for j in range(len(X)):
for k in range(len(X)):
# Fill Z with the labels (numerical values)
# the inner loop goes over the columns of Z,
# which corresponds to sweeping x-values
# Therefore, the role of j,k is flipped in the signature
Z[j, k] = predict_qubitF( np.array([X[k], X[j]]),currentParams,[1,1])
ax.contourf(X, X, Z, cmap='bwr', levels=30)
#circuit 1
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(62):
theta.append((Parameter('θ'+str(i))))
qc=circuit19(qc,qr,theta,2,0)
data1Path = r'../../dataset/data2c.txt'
data1Label = r'../../dataset/data2clabel.txt'
dataCoords = np.loadtxt(data1Path)
dataLabels = np.loadtxt(data1Label)
# Make a data structure which is easier to work with
# for shuffling.
# Also, notice we change the data labels from {0, 1} to {-1, +1}
data = list(zip(dataCoords, 2*dataLabels-1))
shuffled_data = shuffle(data)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o')
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o')
c = 1
a = 1
# Do the updates
lossList = []
coeffsList = []
paramsList = []
accuracyList = []
np.random.seed(2)
currentParams = 2*np.random.uniform(size=40)
for j in range(30):
cj = c/(j+1)**(1/4)
aj = a/(j+1)
# Grab a subset of the data for minibatching
#np.random.seed(j)
np.random.seed(3)
#data_ixs = np.random.choice(len(shuffled_data), size=len(shuffled_data))
data_ixs = np.random.choice(len(data), size=100)
# Evaluate the loss over that subset
# We include a regularization term at the end
L = lambda x: np.sum([loss_qubitF(data[j][0],data[j][1],x,[18,2]) for j in data_ixs])/len(data_ixs)
lossList.append(L(currentParams))
coeffsList.append((cj, aj))
paramsList.append(currentParams)
accuracyList.append(np.sum([predict_qubitF(data[j][0],currentParams,[18,2]) ==data[j][1] for j in data_ixs])/len(data_ixs))
print(j,"th iteration L=",lossList[-1],"Accuracy =",accuracyList[-1])
currentParams = SPSA_update(L, currentParams, aj, cj)
fig = plt.figure(figsize=(15, 10))
ax = fig.add_subplot(2, 2, 1)
ax.plot(lossList)
ax.set_title('Loss function\nStart {0} Finish {1}'.format(np.round(lossList[0], 3), np.round(lossList[-1], 3)))
ax.set_yscale('log')
ax = fig.add_subplot(2, 2, 2)
ax.plot(accuracyList)
ax.set_title('Classification accuracy \nStart {0} Finish {1}'.format(np.round(accuracyList[0], 3), np.round(accuracyList[-1], 3)))
ax.set_yscale('log')
ax = fig.add_subplot(2, 2, 3)
ax.plot([c[0] for c in coeffsList], label='a')
ax.plot([c[1] for c in coeffsList], label='c')
ax.legend(loc=0)
ax.set_title('Update coefficients')
ax = fig.add_subplot(2, 2, 4)
for j in range(4):
ax.plot([X[j] for X in paramsList], label='x{0}'.format(j))
ax.legend(loc=0)
ax.set_title('Parameter values')
ax.legend(loc=0)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o')
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o')
X = np.linspace(0, 1, num=10)
Z = np.zeros((len(X), len(X)))
# Contour map
for j in range(len(X)):
for k in range(len(X)):
# Fill Z with the labels (numerical values)
# the inner loop goes over the columns of Z,
# which corresponds to sweeping x-values
# Therefore, the role of j,k is flipped in the signature
Z[j, k] = predict_qubitF( np.array([X[k], X[j]]),currentParams,[18,2])
ax.contourf(X, X, Z, cmap='bwr', levels=30)
currentParams
|
https://github.com/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
|
DRA-chaos
|
!pip install qiskit
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import qiskit
from qiskit import transpile, assemble
from qiskit.visualization import *
def to_numbers(tensor_list):
num_list = []
for tensor in tensor_list:
num_list += [tensor.item()]
return num_list
import numpy as np
import torch
from torch.autograd import Function
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute
from qiskit.circuit import Parameter
from qiskit import Aer
from tqdm import tqdm
from matplotlib import pyplot as plt
%matplotlib inline
class QuantumCircuit:
"""
This class provides a simple interface for interaction
with the quantum circuit
"""
def __init__(self, n_qubits, backend, shots):
# --- Circuit definition ---
self._circuit = qiskit.QuantumCircuit(n_qubits)
all_qubits = [i for i in range(n_qubits)]
self.theta = qiskit.circuit.Parameter('theta')
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
# ---------------------------
self.backend = backend
self.shots = shots
def run(self, thetas):
t_qc = transpile(self._circuit,
self.backend)
qobj = assemble(t_qc,
shots=self.shots,
parameter_binds = [{self.theta: theta} for theta in thetas])
job = self.backend.run(qobj)
result = job.result().get_counts()
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
return np.array([expectation])
simulator = qiskit.Aer.get_backend('qasm_simulator')
circuit = QuantumCircuit(1, simulator, 100)
print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0]))
circuit._circuit.draw()
class HybridFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
""" Forward pass computation """
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
expectation_z = ctx.quantum_circuit.run(input[0].tolist())
result = torch.tensor([expectation_z])
ctx.save_for_backward(input, result)
return result
@staticmethod
def backward(ctx, grad_output):
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class Hybrid(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(1, backend, shots)
self.shift = shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift)
import torchvision
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors
cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform)
labels = cifar_trainset.targets # get the labels for the data
labels = np.array(labels)
idx1 = np.where(labels == 0) # filter on aeroplanes
idx2 = np.where(labels == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=100
# concatenate the data indices
idx = np.concatenate((idx1[0][0:n],idx2[0][0:n]))
# create the filtered dataset for our training set
cifar_trainset.targets = labels[idx]
cifar_trainset.data = cifar_trainset.data[idx]
train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True)
import numpy as np
import matplotlib.pyplot as plt
n_samples_show = 8
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 2))
while n_samples_show > 0:
images, targets = data_iter.__next__()
images=images.squeeze()
#axes[n_samples_show - 1].imshow( tf.shape( tf.squeeze(images[0]) ),cmap='gray' )
#plt.imshow((tf.squeeze(images[0])))
#plt.imshow( tf.shape( tf.squeeze(x_train) ) )
#axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray')
axes[n_samples_show - 1].imshow(images[0].numpy(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
#Testing data
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors
cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform)
labels1 = cifar_testset.targets # get the labels for the data
labels1 = np.array(labels1)
idx1_ae = np.where(labels1 == 0) # filter on aeroplanes
idx2_au = np.where(labels1 == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=50
# concatenate the data indices
idxa = np.concatenate((idx1_ae[0][0:n],idx2_au[0][0:n]))
# create the filtered dataset for our training set
cifar_testset.targets = labels[idxa]
cifar_testset.data = cifar_testset.data[idxa]
test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=True)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(500, 500)
self.fc2 = nn.Linear(500, 1)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
#qc = TorchCircuit.apply
Ignore this cell
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.h1 = nn.Linear(500, 500)
self.h2 = nn.Linear(500, 1)
def forward(self,x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 500)
x = F.relu(self.h1(x))
x = F.dropout(x, training=self.training)
x = self.h2(x)
x = qc(x)
x = (x+1)/2 # Normalise the inputs to 1 or 0
x = torch.cat((x, 1-x), -1)
return x
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 5
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Now plotting the training graph
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 10
loss_list1 = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list1.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list1[-1]))
#Alongside, let's also plot the data
plt.plot(loss_list1)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list2 = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list2.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list2[-1]))
#Alongside, let's also plot the data
plt.plot(loss_list2)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 30
loss_list3 = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
#Alongside, let's also plot the data
plt.plot(loss_list3)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 30
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
#Alongside, let's also plot the data
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
import torch
import torchvision
import torchvision.transforms as transforms
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 10
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
#Testing the quantum hybrid in order to comapre it with the classical one
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(500, 500)
self.fc2 = nn.Linear(500,49)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 99)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return F.softmax(x)
|
https://github.com/nahumsa/volta
|
nahumsa
|
import numpy as np
import qiskit
from qiskit.aqua.operators import OperatorBase, ListOp, PrimitiveOp, PauliOp
from qiskit.aqua.operators import I, X, Y, Z
from qiskit.quantum_info import Pauli
from qiskit.aqua.algorithms import VQE, NumPyEigensolver
import matplotlib.pyplot as plt
# hamiltonian = 0.5*(Z^I) + 0.5*(Z^Z)
hamiltonian = 1/2*((I^Z) + (Z^I) + 2*( (X^X) + (Y^Y)))
print(hamiltonian)
eigenvalues, _ = np.linalg.eigh(hamiltonian.to_matrix())
print(f"Eigenvalues: {eigenvalues}")
from qiskit.circuit.library import TwoLocal
def _get_ansatz(n_qubits):
return TwoLocal(n_qubits, ['ry','rz'], 'cx', reps=1)
def get_num_parameters(n_qubits):
return len(_get_ansatz(n_qubits).parameters)
def get_var_form(params, n_qubits=2):
"""Get an hardware-efficient ansatz for n_qubits
given parameters.
"""
# Define variational Form
var_form = _get_ansatz(n_qubits)
# Get Parameters from the variational form
var_form_params = sorted(var_form.parameters, key=lambda p: p.name)
# Check if the number of parameters is compatible
assert len(var_form_params) == len(params), "The number of parameters don't match"
# Create a dictionary with the parameters and values
param_dict = dict(zip(var_form_params, params))
# Assing those values for the ansatz
wave_function = var_form.assign_parameters(param_dict)
return wave_function
from qiskit import Aer, execute
def _measure_zz_circuit(qc: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit:
""" Construct the circuit to measure
"""
zz_circuit = qc.copy()
zz_circuit.measure_all()
return zz_circuit
def _clear_counts(count: dict) -> dict:
if '00' not in count:
count['00'] = 0
if '01' not in count:
count['01'] = 0
if '10' not in count:
count['10'] = 0
if '11' not in count:
count['11'] = 0
return count
def measure_zz(qc, backend, shots=10000):
""" Measure the ZZ expectation value for a given circuit.
"""
zz_circuit = _measure_zz_circuit(qc)
count = execute(zz_circuit, backend=backend, shots=shots).result().get_counts()
count = _clear_counts(count)
# Get total counts in order to obtain the probability
total_counts = count['00'] + count['11'] + count['01'] + count['10']
# Get counts for expected value
zz_meas = count['00'] + count['11'] - count['01'] - count['10']
return zz_meas / total_counts
def measure_zi(qc, backend, shots=10000):
""" Measure the ZI expectation value for a given circuit.
"""
zi_circuit = _measure_zz_circuit(qc)
count = execute(zi_circuit, backend=backend, shots=shots).result().get_counts()
count = _clear_counts(count)
# Get total counts in order to obtain the probability
total_counts = count['00'] + count['11'] + count['01'] + count['10']
# Get counts for expected value
zi_meas = count['00'] - count['11'] + count['01'] - count['10']
return zi_meas / total_counts
def measure_iz(qc, backend, shots=10000):
""" Measure the IZ expectation value for a given circuit.
"""
iz_circuit = _measure_zz_circuit(qc)
count = execute(iz_circuit, backend=backend, shots=shots).result().get_counts()
count = _clear_counts(count)
# Get total counts in order to obtain the probability
total_counts = count['00'] + count['11'] + count['01'] + count['10']
# Get counts for expected value
iz_meas = count['00'] - count['11'] - count['01'] + count['10']
return iz_meas / total_counts
def _measure_xx_circuit(qc: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit:
""" Construct the circuit to measure
"""
xx_circuit = qc.copy()
xx_circuit.h(xx_circuit.qregs[0])
xx_circuit.measure_all()
return xx_circuit
def measure_xx(qc, backend, shots=10000):
""" Measure the XX expectation value for a given circuit.
"""
xx_circuit = _measure_xx_circuit(qc)
count = execute(xx_circuit, backend=backend, shots=shots).result().get_counts()
count = _clear_counts(count)
# Get total counts in order to obtain the probability
total_counts = count['00'] + count['11'] + count['01'] + count['10']
# Get counts for expected value
xx_meas = count['00'] + count['11'] - count['01'] - count['10']
return xx_meas / total_counts
def _measure_yy_circuit(qc: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit:
""" Construct the circuit to measure
"""
yy_meas = qc.copy()
yy_meas.barrier(range(2))
yy_meas.sdg(range(2))
yy_meas.h(range(2))
yy_meas.measure_all()
return yy_meas
def measure_yy(qc, backend, shots=10000):
""" Measure the YY expectation value for a given circuit.
"""
yy_circuit = _measure_yy_circuit(qc)
count = execute(yy_circuit, backend=backend, shots=shots).result().get_counts()
count = _clear_counts(count)
# Get total counts in order to obtain the probability
total_counts = count['00'] + count['11'] + count['01'] + count['10']
# Get counts for expected value
xx_meas = count['00'] + count['11'] - count['01'] - count['10']
return xx_meas / total_counts
import unittest
class TestStringMethods(unittest.TestCase):
def setUp(self):
# Simulator
self.backend = Aer.get_backend("qasm_simulator")
# ZZ expectation value of 1
self.qcZ = qiskit.QuantumCircuit(2)
# XX expectation value of 1
self.qcX = qiskit.QuantumCircuit(2)
self.qcX.h(range(2))
# YY expectation value of 1
self.qcY = qiskit.QuantumCircuit(2)
self.qcY.h(range(2))
self.qcY.s(range(2))
def test_ZZ(self):
want = 1.
got = measure_zz(self.qcZ, self.backend)
decimalPlace = 2
message = "ZZ measurement not working for state Zero^Zero."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_XX(self):
want = 1.
got = measure_xx(self.qcX, self.backend)
decimalPlace = 2
message = "XX measurement not working for state Plus^Plus."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_YY(self):
want = 1.
got = measure_yy(self.qcY, self.backend)
decimalPlace = 2
message = "YY measurement not working for state iPlus^iPlus."
self.assertAlmostEqual(want, got, decimalPlace, message)
unittest.main(argv=[''], verbosity=2, exit=False);
from Observables import *
def get_hamiltonian(qc, backend, num_shots):
# Hamiltonian BCS
hamiltonian = .5*(measure_iz(qc, backend, num_shots) + measure_zi(qc, backend, num_shots)
+ 2*(measure_xx(qc, backend, num_shots) + measure_yy(qc, backend, num_shots)))
# hamiltonian = 0.5*(measure_zi(qc, backend, num_shots) + measure_zz(qc, backend, num_shots))
return hamiltonian
def objective_function(params):
# Parameters
backend = Aer.get_backend("qasm_simulator")
NUM_SHOTS = 10000
n_qubits = 2
# Define Ansatz
qc = get_var_form(params, n_qubits)
# Hamiltonian
hamiltonian = get_hamiltonian(qc, backend, NUM_SHOTS)
# Get the cost function
cost = hamiltonian
return cost
from qiskit.aqua.components.optimizers import COBYLA, NELDER_MEAD, SLSQP
optimizer = COBYLA(maxiter=1000, disp=False, rhobeg=1.0,
tol=None)
# optimizer = NELDER_MEAD(maxiter=1000, maxfev=1000, disp=False,
# xatol=0.0001, tol=None, adaptive=True)
# optimizer = SLSQP(maxiter=100, disp=False,
# ftol=1e-06, tol=None)
# Create the initial parameters (noting that our single qubit variational form has 3 parameters)
n_qubits = 2
n_parameters = get_num_parameters(n_qubits)
params = np.random.rand(n_parameters)
optimal_params, energy_gs, n_iters = optimizer.optimize(num_vars=n_parameters,
objective_function=objective_function,
initial_point=params)
# Obtain the output distribution using the final parameters
ground_state = get_var_form(optimal_params)
print(f"Energy obtained: {energy_gs}")
ground_state.draw('mpl')
import qiskit
from qiskit import QuantumCircuit
def swap_test_circuit(qc1: qiskit.QuantumCircuit, qc2: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit:
""" Construct the SWAP test circuit given two circuits.
Args:
qc1(qiskit.QuantumCircuit): Quantum circuit for the
first state.
qc2(qiskit.QuantumCircuit): Quantum circuit for the
second state.
Output:
(qiskit.QuantumCircuit): swap test circuit.
"""
# Helper variables
n_total = qc1.num_qubits + qc2.num_qubits
range_qc1 = [i + 1 for i in range(qc1.num_qubits)]
range_qc2 = [i + qc1.num_qubits + 1 for i in range(qc2.num_qubits)]
# Constructing the SWAP test circuit
qc_swap = QuantumCircuit(n_total + 1, 1)
qc_swap.append(qc1, range_qc1)
qc_swap.append(qc2, range_qc2)
# Swap Test
qc_swap.h(0)
for index, qubit in enumerate(range_qc1):
qc_swap.cswap(0, qubit, range_qc2[index] )
qc_swap.h(0)
# Measurement on the auxiliary qubit
qc_swap.measure(0,0)
return qc_swap
def measure_swap_test(qc1: qiskit.QuantumCircuit, qc2: qiskit.QuantumCircuit,
backend: qiskit.providers.aer.backends,
num_shots: int=10000) -> float:
""" Returns the fidelity from a SWAP test.
"""
swap_circuit = swap_test_circuit(qc1, qc2)
count = execute(swap_circuit, backend=backend, shots=num_shots).result().get_counts()
if '0' not in count:
count['0'] = 0
if '1' not in count:
count['1'] = 0
total_counts = count['0'] + count['1']
fid_meas = count['0']
p_0 = fid_meas / total_counts
return 2*(p_0 - 1/2)
import unittest
from qiskit import QuantumCircuit, Aer
class TestStringMethods(unittest.TestCase):
def setUp(self):
self.qc1 = QuantumCircuit(1)
self.qc1.x(0)
self.qc2 = QuantumCircuit(1)
self.backend = Aer.get_backend("qasm_simulator")
def test_01states(self):
want = 0.
got = measure_swap_test(self.qc1, self.qc2, self.backend)
decimalPlace = 1
message = "Swap test not working for states 0 and 1."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_00states(self):
want = 1.
got = measure_swap_test(self.qc2, self.qc2, self.backend)
decimalPlace = 2
message = "Swap test not working for states 0 and 0."
self.assertAlmostEqual(want, got, decimalPlace, message)
def test_11states(self):
want = 1.
got = measure_swap_test(self.qc1, self.qc1, self.backend)
decimalPlace = 2
message = "Swap test not working for states 1 and 1."
self.assertAlmostEqual(want, got, decimalPlace, message)
unittest.main(argv=[''], verbosity=2, exit=False);
import unittest
unittest.assertAlmostEqual(0.5, measure_swap_test(qc1,qc2, backend))
qc1 = QuantumCircuit(1)
qc1.x(0)
qc2 = QuantumCircuit(1)
measure_swap_test(qc1, qc2, backend)
measure_swap_test(ground_state, ground_state, backend)
import qiskit
from qiskit import QuantumCircuit
def dswap_test_circuit(qc1: qiskit.QuantumCircuit, qc2: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit:
""" Construct the destructive SWAP test circuit
given two circuits.
Args:
qc1(qiskit.QuantumCircuit): Quantum circuit for the
first state.
qc2(qiskit.QuantumCircuit): Quantum circuit for the
second state.
Output:
(qiskit.QuantumCircuit): destructive swap test circuit.
"""
# Helper variables
n_total = qc1.num_qubits + qc2.num_qubits
range_qc1 = [i for i in range(qc1.num_qubits)]
range_qc2 = [i + qc1.num_qubits for i in range(qc2.num_qubits)]
# Constructing the Destructive SWAP TEST
qc_swap = QuantumCircuit(n_total)
qc_swap.append(qc1, range_qc1)
qc_swap.append(qc2, range_qc2)
for index, qubit in enumerate(range_qc1):
qc_swap.cx(qubit,range_qc2[index])
# Haddamard in the first state
qc_swap.h(range_qc1)
qc_swap.measure_all()
return qc_swap
qc = get_var_form([0]*n_parameters)
dswap_circuit = dswap_test_circuit(qc, ground_state)
backend = Aer.get_backend("qasm_simulator")
NUM_SHOTS = 10000
count = execute(dswap_circuit, backend, shots=NUM_SHOTS).result().get_counts()
print(count)
from SWAPTest import measure_swap_test
def objective_function_es(params):
# Parameters
backend = Aer.get_backend("qasm_simulator")
NUM_SHOTS = 10000
BETA = 1.
# Define Ansatz
qc = get_var_form(params)
# Hamiltonian
hamiltonian = get_hamiltonian(qc, backend, NUM_SHOTS)
# Swap Test
fidelity = measure_swap_test(qc, ground_state, backend)
# Get the cost function
cost = hamiltonian + BETA*fidelity
return cost
# Create the initial parameters
params = np.random.rand(n_parameters)
optimal_params, energy_es, n_iters = optimizer.optimize(num_vars=n_parameters,
objective_function=objective_function_es,
initial_point=params)
# Obtain the output state
excited_state = get_var_form(optimal_params)
print(f"Energy obtained: {energy_es}")
excited_state.draw('mpl')
backend = Aer.get_backend("qasm_simulator")
print(f"Fidelity between the Ground state and the Excited state {measure_swap_test(excited_state, ground_state, backend)}")
print("Energies")
print(f"Ground State\nExpected: {eigenvalues[0]} | Got: {np.round(energy_gs,4)}")
print(f"Ground State\nExpected: {eigenvalues[1]} | Got: {np.round(energy_es,4)}")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXSimple(), backend=FakeBoeblingen())
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation
circuit = QuantumCircuit(5)
# Quantum Instantaneous Polynomial Time example
circuit.cx(0, 1)
circuit.cx(2, 1)
circuit.cx(4, 3)
circuit.cx(2, 3)
circuit.z(0)
circuit.z(4)
circuit.cx(0, 1)
circuit.cx(2, 1)
circuit.cx(4, 3)
circuit.cx(2, 3)
circuit.cx(3, 2)
print(circuit)
pm = PassManager()
pm.append([CommutationAnalysis(), CommutativeCancellation()])
new_circuit = pm.run(circuit)
print(new_circuit)
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
import sys
from matplotlib import pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
path = "data/BH_phase-diagrams-and-loss/data_rike/"
x = np.load(path + "x.npy")
y = np.load(path + "y.npy")
es = np.load(path + "es2.npy")
dd = np.load(path + "dd2.npy")
cost0 = np.load(path + "cost_bh_L12_trash2_d48_v5_seed17.npy")
cost1 = np.load(path + "cost_bh_L12_trash4_d25_v47_seed16.npy")
cost2 = np.load(path + "cost_bh_L12_trash6_d10_v10_seed22.npy")
vs = np.logspace(-2,2,50)
ds = np.linspace(-0.95,0.95,50)
fig,aa = plt.subplots(figsize=(16,4),sharey="row",dpi=220)
fs_labels = 17
fs_ticks = 16
ax00 = plt.subplot2grid(shape=(8,25), loc=(0, 0), rowspan=4, colspan=4, xticklabels=[])
ax10 = plt.subplot2grid(shape=(8,25), loc=(4, 0), rowspan=4, colspan=4, xticklabels=[])
ax01 = plt.subplot2grid(shape=(8,25), loc=(1, 7), rowspan=6, colspan=6, xticklabels=[])
ax02 = plt.subplot2grid(shape=(8,25), loc=(1, 13), rowspan=6, colspan=6, xticklabels=[], yticklabels=[])
ax03 = plt.subplot2grid(shape=(8,25), loc=(1, 19), rowspan=6, colspan=6, xticklabels=[], yticklabels=[])
cmap = plt.get_cmap("plasma") #'viridis'
cbar_labelsize = 10
cbar = np.zeros((2,2), dtype="object")
axs=np.array([[ax00,ax10],[ax01,ax02]])
print(axs[0,0])
for ax in axs.flatten():
ax.tick_params(labelsize=fs_ticks)
ax = axs[0,0]
axs[0,0].set_title("DMRG", fontsize=14)
im = ax.pcolormesh(x,y,dd.T, cmap=cmap, shading="auto",rasterized=True) #,rasterized=True necessary for pdf export
#im.ax.tick_params(labelsize=cbar_labelsize)
ax.set_xscale("log")
cbar[0,0] = fig.colorbar(im, ax=ax)
cbar[0,0].ax.tick_params(labelsize=fs_ticks)
cbar[0,0].ax.set_ylabel("$O_{CDW}$",fontsize=fs_labels)
axs[0,0].set_ylabel(r"$\delta J$",fontsize=fs_labels)
ax.set_xticks([], minor=True)
ax.set_xticks([], minor=False)
ax = axs[0,1]
im = ax.pcolormesh(x,y,es.T, cmap=cmap, shading="auto",rasterized=True)
ax.set_xscale("log")
cbar[0,1] = fig.colorbar(im, ax=ax)
cbar[0,1].ax.tick_params(labelsize=fs_ticks)
cbar[0,1].ax.set_ylabel("$D_{ES}$",fontsize=fs_labels)
axs[0,1].set_xlabel(r"$V/J$",fontsize=fs_labels)
axs[0,1].set_ylabel(r"$\delta J$",fontsize=fs_labels)
ax = axs[1,0]
im = ax.pcolormesh(x,y,cost2.T,vmin=0, cmap=cmap, shading="auto",rasterized=True)
ax.set_xscale("log")
cbar[1,0] = fig.colorbar(im, ax=ax)
cbar[1,0].ax.tick_params(labelsize=fs_ticks)
ax.plot(vs[10],ds[10],"X", color="magenta",markersize=15, alpha=0.8)
axs[1,0].set_xlabel(r"$V/J$",fontsize=fs_labels)
axs[1,0].set_ylabel(r"$\delta J$",fontsize=fs_labels)
ax = axs[1,1]
im = ax.pcolormesh(x,y,cost1.T,vmin=0, cmap=cmap, shading="auto",rasterized=True)
ax.set_xscale("log")
cbar[1,1] = fig.colorbar(im, ax=ax)
cbar[1,1].ax.tick_params(labelsize=fs_ticks)
cbar[1,1].ax.set_title("cost", fontsize=fs_labels)
ax.plot(vs[47],ds[25],"X", color="magenta",markersize=15, alpha=0.8)
axs[1,1].set_xlabel(r"$V/J$",fontsize=fs_labels)
ax.set_yticks([])
ax = ax03
ax.tick_params(labelsize=fs_ticks)
im = ax.pcolormesh(x,y,cost0.T,vmin=0, cmap=cmap, shading="auto",rasterized=True)
ax.set_xscale("log")
cbar[1,1] = fig.colorbar(im, ax=ax)
cbar[1,1].ax.tick_params(labelsize=fs_ticks)
cbar[1,1].ax.set_title("cost", fontsize=fs_labels)
ax.plot(vs[5],ds[48],"X", color="magenta",markersize=15, alpha=0.8)
ax03.set_xlabel(r"$V/J$",fontsize=fs_labels)
ax.set_yticks([])
plt.tight_layout()
# has to happen after tight_layout()
axs[0,0].text(-0.21,0.89,"(a)", fontweight="bold", size=fs_labels, transform = axs[0,0].transAxes)
axs[1,0].text(0.5,1.07,"(c)", fontweight="bold", size=fs_labels, transform = axs[1,0].transAxes)
axs[0,1].text(-0.21,0.88,"(b)", fontweight="bold", size=fs_labels, transform = axs[0,1].transAxes)
axs[1,1].text(0.5,1.07,"(d)", fontweight="bold", size=fs_labels, transform = axs[1,1].transAxes)
ax03.text(0.5,1.07,"(e)", fontweight="bold", size=fs_labels, transform = ax03.transAxes)
axs[1,0].text(0.33,0.15,"MI", fontweight="bold", size=fs_labels, transform = axs[1,0].transAxes, color="white")
axs[1,0].text(0.23,0.8,"TMI", fontweight="bold", size=fs_labels, transform = axs[1,0].transAxes)
axs[1,0].text(0.7,0.5,"CDW", fontweight="bold", size=fs_labels, transform = axs[1,0].transAxes)
cbar[1,0].ax.set_title("cost", fontsize=fs_labels)
plt.savefig("plots/BH_paper.pdf", bbox_inches='tight')
cost = np.load("data/ibmq_antiferro-2D_load-AD_10x10_noisy-rome-simu_thetas-loss-cost_run1.npy",allow_pickle=True)
qmag = np.load("data/noisy_rome_simu_VQE_maxiter-500_Ising_L5_anti_-1_10x10.npz", allow_pickle=True)["Qmag"].reshape(10,10)
x,y = np.logspace(-2,2,10), np.logspace(-2,2,10)
x,y = np.meshgrid(x,y)
fig,axs = plt.subplots(ncols=2, nrows=1,figsize=(8,3),sharex=True, sharey=True, dpi=220)
cmap1 = plt.get_cmap("viridis")
cmap2 = plt.get_cmap("plasma")
cbar_labelsize = 18
cbar = np.zeros((2), dtype="object")
ax0 = axs[0]
im = ax0.pcolormesh(x, y, qmag, cmap=cmap1, shading="auto", rasterized=True) #,rasterized=True necessary for pdf export
cbar[0] = fig.colorbar(im, ax=ax0)
cbar[0].ax.tick_params(labelsize=cbar_labelsize)
cbar[0].ax.set_ylabel("$\hat{S}$",fontsize=20)
ax1 = axs[1]
im = ax1.pcolormesh(x, y, cost,vmin=0, cmap=cmap2, shading="auto",rasterized=True)
cbar[1] = fig.colorbar(im, ax=ax1)
cbar[1].ax.tick_params(labelsize=cbar_labelsize)
cbar[1].ax.set_ylabel("cost",fontsize=20)
#ax.plot(vs[47],ds[25],"x", color="magenta")
ax1.plot(1e-2,1e-2,"X", color="magenta",markersize=15, alpha=0.7, clip_on=False)
ax0.set_yscale("log")
ax0.set_yscale("log")
ax1.set_xscale("log")
ax0.set_xscale("log")
ax0.tick_params(labelsize=18)
ax1.tick_params(labelsize=18)
ax1.set_xlabel(r"$g_x$",fontsize=20)
ax0.set_ylabel(r"$g_z$",fontsize=20)
ax0.set_xlabel(r"$g_x$",fontsize=20)
#ax1.set_yticks([], minor=True)
#ax1.set_yticks([], minor=False)
plt.tight_layout()
# has to happen after tight_layout()
axs[0].text(-0.35,0.9,"(a)", fontweight="bold", size=18, transform = axs[0].transAxes)
axs[1].text(-0.2, 0.9,"(b)", fontweight="bold", size=18, transform = axs[1].transAxes)
plt.savefig("plots/antiferro2D_paper.pdf", bbox_inches='tight')
anti = -1
L = 5
num_trash = 2
name = "ibmq_antiferro-1D-load_bogota-optimize-20points" # 01.06.2021 experiment
filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle"
print("filename: ", filename, "notebook name: ", name)
# where to get the simulated thetas values from? needs to contain a thetas_mitigated array
filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_bogota-optimize_thetas-loss-cost_run2.npz'
# this is noisy simulation data
L = 5
num_trash = 2
anti = -1
VQE_params = np.load(filename + ".npz", allow_pickle=True)
pick = np.arange(0,len(VQE_params['gx_list']))
gx_list = VQE_params['gx_list'][pick]
gz_list = VQE_params['gz_list'][pick]
opt_params = VQE_params['opt_params'][pick]
Qmags = VQE_params["Qmag"][pick]
Qen = VQE_params["Qen"][pick]
Sen = VQE_params["Sen"][pick]
Smags = VQE_params["Smag"][pick]
temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True)
Qmags_executed = temp["Qmags"]
gx_vals = np.unique(gx_list)
gz_vals = np.unique(gz_list)
fig, axs = plt.subplots(nrows=2,figsize=(5,5),sharex=True,gridspec_kw={'height_ratios': [2, 2]},dpi=220)
ax = axs[0]
cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,".:")#, label="loss noisy sim.")
cost = np.load("data/" + name + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,".:")#, label="loss ibmq_bogota")
ax.plot(gx_list, Qmags,"x--", label="$\hat{S}$ noisy sim.")
ax.plot(gx_list, Qmags_executed,"x--", label="$\hat{S}$ ibmq$\_$bogota")
ax.set_xscale("log")
ax.plot(gx_list[0],cost[0], "X",markersize=20,alpha=0.4,color="magenta")
ax = axs[1]
cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,"x--", label="cost noisy sim.")
cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,".:", label="cost ibmq$\_$bogota")
ax.plot(gx_list, abs(Qmags),"x--", label="$\mid \hat{S} \mid$ noisy sim.")
ax.plot(gx_list, abs(Qmags_executed),".:", label="$\mid \hat{S} \mid$ ibmq$\_$bogota")
ax.set_xscale("log")
ax.plot(gx_list[-1],cost[-1],"X",markersize=20,alpha=0.4,color="magenta")
for ax in axs:
ax.legend()
ax.tick_params(labelsize=14)
axs[-1].set_xlabel("$g_x$", fontsize=18)
plt.tight_layout()
axs[0].text(-0.11,0.9,"(a)", fontweight="bold", size=18, transform = axs[0].transAxes)
axs[1].text(-0.11,0.9,"(b)", fontweight="bold", size=18, transform = axs[1].transAxes)
plt.savefig("plots/" + name + "_mainplot.png", bbox_inches='tight')
plt.savefig("plots/" + name + "_mainplot.pdf", bbox_inches='tight')
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import QuantumCircuit
QuantumCircuit(2)
QuantumCircuit(2, 2)
import math
qc = QuantumCircuit(4)
qc.h(0)
qc.id(2)
qc.i(2)
qc.p(math.pi/2,0)
qc.rx(math.pi/4,2)
qc.ry(math.pi/8,0)
qc.rz(math.pi/2,1)
qc.s(3)
qc.sdg(3)
qc.sx(2)
qc.t(1)
qc.tdg(1)
qc.u(math.pi/2,0,math.pi,1)
qc.x(3)
qc.y([0,2,3])
qc.z(2)
qc = QuantumCircuit(4)
qc.h(0)
qc.id(2)
qc.p(math.pi/2,0)
qc.rx(math.pi/4,2)
qc.ry(math.pi/8,0)
qc.rz(math.pi/2,1)
qc.s(3)
qc.sdg(3)
qc.sx(2)
qc.t(1)
qc.tdg(1)
qc.u(math.pi/2,0,math.pi,1)
qc.x(3)
qc.y([0,2,3])
qc.z(2)
qc.draw('mpl')
qc.ccx(0,1,2)
qc.ch(0,1)
qc.cp(math.pi/4,0,1)
qc.crx(math.pi/2,2,3)
qc.crz(math.pi/4,0,1)
qc.cswap(0,2,3)
qc.fredkin(0,2,3)
qc.csx(0,1)
qc.cu(math.pi/2,0,math.pi,0,0,1)
qc.cx(2,3)
qc.cnot(2,3)
qc.cy(2,3)
qc.cz(1,2)
qc.dcx(2,3)
qc.iswap(0,1)
qc.mcp(math.pi/4,[0,1,2],3)
qc.mcx([0,1,2],3)
qc.swap(2,3)
qc = QuantumCircuit(4)
qc.ccx(0,1,2)
qc.ch(0,1)
qc.cp(math.pi/4,0,1)
qc.crx(math.pi/2,2,3)
qc.crz(math.pi/4,0,1)
qc.cswap(0,2,3)
qc.csx(0,1)
qc.cu(math.pi/2,0,math.pi,0,0,1)
qc.cx(2,3)
qc.cy(2,3)
qc.cz(1,2)
qc.dcx(2,3)
qc.iswap(0,1)
qc.mcp(math.pi/4,[0,1,2],3)
qc.mcx([0,1,2],3)
qc.swap(2,3)
qc.draw('mpl')
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.draw('mpl')
qc = QuantumCircuit(2)
qc.h([0,1])
qc.barrier()
qc.x(0)
qc.x(0)
qc.s(1)
qc.barrier([1])
qc.s(1)
qc.draw('mpl')
qc = QuantumCircuit(3, 3)
qc.h([0,1,2])
qc.measure([0,1,2], [0,1,2])
qc.draw('mpl')
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc.measure_all()
qc.draw('mpl')
qc.depth()
qc.size()
qc.width()
qc.clbits
qc.data
qc.global_phase
qc.num_clbits
qc.num_qubits
qc.qubits
from qiskit.circuit.library import CXGate
qc = QuantumCircuit(2)
qc.h(1)
cx_gate = CXGate()
qc.append(cx_gate, [1,0])
qc.draw()
from qiskit.circuit import QuantumCircuit,\
Parameter
theta1 = Parameter('θ1')
theta2 = Parameter('θ2')
theta3 = Parameter('θ3')
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc.p(theta1,0)
qc.p(theta2,1)
qc.p(theta3,2)
qc.draw()
b_qc = qc.bind_parameters({theta1: math.pi/8,
theta2: math.pi/4,
theta3: math.pi/2})
b_qc.draw()
qc = QuantumCircuit(2,2)
qc.h(0)
another_qc = QuantumCircuit(2,2)
another_qc.cx(0,1)
bell_qc = qc.compose(another_qc)
bell_qc.draw()
qc = QuantumCircuit(2)
qc.h(0)
qc.s(0)
qc.x(1)
decomposed_qc = qc.decompose()
decomposed_qc.draw()
qasm_str = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0],q[1];
measure q[0] -> c[0];
measure q[1] -> c[1];
"""
new_qc = QuantumCircuit.from_qasm_str(qasm_str)
new_qc.draw()
qc = QuantumCircuit(2)
qc.initialize([0, 0, 0, 1])
qc.draw()
qc = QuantumCircuit(1)
qc.x(0)
qc.reset(0)
qc.draw()
anti_cnot_qc = QuantumCircuit(2)
anti_cnot_qc.x(0)
anti_cnot_qc.cx(0,1)
anti_cnot_qc.x(0)
anti_cnot_qc.draw()
anti_cnot_gate = anti_cnot_qc.to_gate()
qc = QuantumCircuit(3)
qc.x([0,1,2])
qc.append(anti_cnot_gate, [0,2])
qc.decompose().draw()
reset_one_qc = QuantumCircuit(1)
reset_one_qc.reset(0)
reset_one_qc.x(0)
reset_one_qc.draw()
reset_one_inst = reset_one_qc.to_instruction()
qc = QuantumCircuit(2)
qc.h([0,1])
qc.reset(0)
qc.append(reset_one_inst, [1])
qc.decompose().draw()
from qiskit import QuantumRegister, \
ClassicalRegister
qr = QuantumRegister(3, 'q')
scratch = QuantumRegister(1, 'scratch')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qr, scratch, cr)
qc.h(qr)
qc.x(scratch)
qc.h(scratch)
qc.cx(qr[0], scratch)
qc.cx(qr[2], scratch)
qc.barrier(qr)
qc.h(qr)
qc.measure(qr, cr)
qc.draw()
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram,plot_bloch_multivector
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)
%matplotlib inline
circuit.draw(output = 'mpl')
plot_bloch_multivector(statevector)
circuit.measure([0],[0])
backend = Aer.get_backend('qasm_simulator')
result = execute(circuit,backend = backend,shots = 1024).result()
counts = result.get_counts()
plot_histogram(counts)
circuit = QuantumCircuit(1,1)
circuit.x(0)
simulator = Aer.get_backend('unitary_simulator')
result = execute(circuit,backend = simulator).result()
unitary = result.get_unitary()
print(unitary)
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utils for using with Qiskit unit tests."""
import logging
import os
import unittest
from enum import Enum
from qiskit import __path__ as qiskit_path
class Path(Enum):
"""Helper with paths commonly used during the tests."""
# Main SDK path: qiskit/
SDK = qiskit_path[0]
# test.python path: qiskit/test/python/
TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python'))
# Examples path: examples/
EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples'))
# Schemas path: qiskit/schemas
SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas'))
# VCR cassettes path: qiskit/test/cassettes/
CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes'))
# Sample QASMs path: qiskit/test/python/qasm
QASMS = os.path.normpath(os.path.join(TEST, 'qasm'))
def setup_test_logging(logger, log_level, filename):
"""Set logging to file and stdout for a logger.
Args:
logger (Logger): logger object to be updated.
log_level (str): logging level.
filename (str): name of the output file.
"""
# Set up formatter.
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(logger.name))
formatter = logging.Formatter(log_fmt)
# Set up the file handler.
file_handler = logging.FileHandler(filename)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(log_level, logging.INFO)
logger.setLevel(level)
class _AssertNoLogsContext(unittest.case._AssertLogsContext):
"""A context manager used to implement TestCase.assertNoLogs()."""
# pylint: disable=inconsistent-return-statements
def __exit__(self, exc_type, exc_value, tb):
"""
This is a modified version of TestCase._AssertLogsContext.__exit__(...)
"""
self.logger.handlers = self.old_handlers
self.logger.propagate = self.old_propagate
self.logger.setLevel(self.old_level)
if exc_type is not None:
# let unexpected exceptions pass through
return False
if self.watcher.records:
msg = 'logs of level {} or higher triggered on {}:\n'.format(
logging.getLevelName(self.level), self.logger.name)
for record in self.watcher.records:
msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname,
record.lineno,
record.getMessage())
self._raiseFailure(msg)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the VF2Layout pass"""
import io
import pickle
import unittest
from math import pi
import ddt
import numpy
import rustworkx
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit import ControlFlowOp
from qiskit.transpiler import CouplingMap, Target, TranspilerError
from qiskit.transpiler.passes.layout.vf2_layout import VF2Layout, VF2LayoutStopReason
from qiskit._accelerate.error_map import ErrorMap
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import (
FakeTenerife,
FakeVigoV2,
FakeRueschlikon,
FakeManhattan,
FakeYorktown,
FakeGuadalupeV2,
)
from qiskit.circuit import Measure
from qiskit.circuit.library import GraphState, CXGate, XGate, HGate
from qiskit.transpiler import PassManager, AnalysisPass
from qiskit.transpiler.target import InstructionProperties
from qiskit.transpiler.preset_passmanagers.common import generate_embed_passmanager
class LayoutTestCase(QiskitTestCase):
"""VF2Layout assertions"""
seed = 42
def assertLayout(self, dag, coupling_map, property_set, strict_direction=False):
"""Checks if the circuit in dag was a perfect layout in property_set for the given
coupling_map"""
self.assertEqual(property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND)
layout = property_set["layout"]
edges = coupling_map.graph.edge_list()
def run(dag, wire_map):
for gate in dag.two_qubit_ops():
if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp):
continue
physical_q0 = wire_map[gate.qargs[0]]
physical_q1 = wire_map[gate.qargs[1]]
if strict_direction:
result = (physical_q0, physical_q1) in edges
else:
result = (physical_q0, physical_q1) in edges or (
physical_q1,
physical_q0,
) in edges
self.assertTrue(result)
for node in dag.op_nodes(ControlFlowOp):
for block in node.op.blocks:
inner_wire_map = {
inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits)
}
run(circuit_to_dag(block), inner_wire_map)
run(dag, {bit: layout[bit] for bit in dag.qubits})
@ddt.ddt
class TestVF2LayoutSimple(LayoutTestCase):
"""Tests the VF2Layout pass"""
def test_1q_component_influence(self):
"""Assert that the 1q component of a connected interaction graph is scored correctly."""
target = Target()
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(error=0.0),
(1, 2): InstructionProperties(error=0.0),
(2, 3): InstructionProperties(error=0.0),
},
)
target.add_instruction(
HGate(),
{
(0,): InstructionProperties(error=0.0),
(1,): InstructionProperties(error=0.0),
(2,): InstructionProperties(error=0.0),
},
)
target.add_instruction(
Measure(),
{
(0,): InstructionProperties(error=0.1),
(1,): InstructionProperties(error=0.1),
(2,): InstructionProperties(error=0.9),
},
)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 0)
qc.measure(0, 0)
qc.measure(1, 1)
vf2_pass = VF2Layout(target=target, seed=self.seed)
vf2_pass(qc)
layout = vf2_pass.property_set["layout"]
self.assertEqual([1, 0], list(layout._p2v.keys()))
def test_2q_circuit_2q_coupling(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
cmap = CouplingMap([[0, 1]])
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=False, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
def test_2q_circuit_2q_coupling_sd(self):
"""A simple example, considering the direction
0 -> 1
qr1 -> qr0
"""
cmap = CouplingMap([[0, 1]])
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=True, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set, strict_direction=True)
@ddt.data(True, False)
def test_2q_circuit_simple_control_flow(self, strict_direction):
"""Test that simple control-flow can be routed on a 2q coupling map."""
cmap = CouplingMap([(0, 1)])
circuit = QuantumCircuit(2)
with circuit.for_loop((1,)):
circuit.cx(1, 0)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=strict_direction, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set, strict_direction=strict_direction)
@ddt.data(True, False)
def test_2q_circuit_nested_control_flow(self, strict_direction):
"""Test that simple control-flow can be routed on a 2q coupling map."""
cmap = CouplingMap([(0, 1)])
circuit = QuantumCircuit(2, 1)
with circuit.while_loop((circuit.clbits[0], True)):
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cx(1, 0)
with else_:
circuit.cx(1, 0)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=strict_direction, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set, strict_direction=strict_direction)
def test_3q_circuit_3q_coupling_non_induced(self):
"""A simple example, check for non-induced subgraph
1 qr0 -> qr1 -> qr2
/ \
0 - 2
"""
cmap = CouplingMap([[0, 1], [1, 2], [2, 0]])
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1]) # qr0-> qr1
circuit.cx(qr[1], qr[2]) # qr1-> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
def test_3q_circuit_3q_coupling_non_induced_control_flow(self):
r"""A simple example, check for non-induced subgraph
1 qr0 -> qr1 -> qr2
/ \
0 - 2
"""
cmap = CouplingMap([[0, 1], [1, 2], [2, 0]])
circuit = QuantumCircuit(3, 1)
with circuit.for_loop((1,)):
circuit.cx(0, 1) # qr0-> qr1
with circuit.if_test((circuit.clbits[0], True)) as else_:
pass
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(1, 2) # qr1-> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
def test_call_limit(self):
"""Test that call limit is enforce."""
cmap = CouplingMap([[0, 1], [1, 2], [2, 0]])
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1]) # qr0-> qr1
circuit.cx(qr[1], qr[2]) # qr1-> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, call_limit=1)
pass_.run(dag)
self.assertEqual(
pass_.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.NO_SOLUTION_FOUND
)
def test_coupling_map_and_target(self):
"""Test that a Target is used instead of a CouplingMap if both are specified."""
cmap = CouplingMap([[0, 1], [1, 2]])
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None, (1, 0): None})
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1]) # qr0-> qr1
circuit.cx(qr[1], qr[2]) # qr1-> qr2
circuit.cx(qr[1], qr[0]) # qr1-> qr0
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, max_trials=1, target=target)
pass_.run(dag)
self.assertLayout(dag, target.build_coupling_map(), pass_.property_set)
def test_neither_coupling_map_or_target(self):
"""Test that we raise if neither a target or coupling map is specified."""
vf2_pass = VF2Layout(seed=123, call_limit=1000, time_limit=20, max_trials=7)
circuit = QuantumCircuit(2)
dag = circuit_to_dag(circuit)
with self.assertRaises(TranspilerError):
vf2_pass.run(dag)
def test_target_no_error(self):
"""Test that running vf2layout on a pass against a target with no error rates works."""
n_qubits = 15
target = Target()
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
vf2_pass = VF2Layout(target=target)
circuit = QuantumCircuit(2)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
vf2_pass.run(dag)
self.assertLayout(dag, target.build_coupling_map(), vf2_pass.property_set)
def test_target_some_error(self):
"""Test that running vf2layout on a pass against a target with some error rates works."""
n_qubits = 15
target = Target()
target.add_instruction(
XGate(), {(i,): InstructionProperties(error=0.00123) for i in range(n_qubits)}
)
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
vf2_pass = VF2Layout(target=target)
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
vf2_pass.run(dag)
self.assertLayout(dag, target.build_coupling_map(), vf2_pass.property_set)
class TestVF2LayoutLattice(LayoutTestCase):
"""Fit in 25x25 hexagonal lattice coupling map"""
cmap25 = CouplingMap.from_hexagonal_lattice(25, 25, bidirectional=False)
def graph_state_from_pygraph(self, graph):
"""Creates a GraphState circuit from a PyGraph"""
adjacency_matrix = rustworkx.adjacency_matrix(graph)
return GraphState(adjacency_matrix).decompose()
def test_hexagonal_lattice_graph_20_in_25(self):
"""A 20x20 interaction map in 25x25 coupling map"""
graph_20_20 = rustworkx.generators.hexagonal_lattice_graph(20, 20)
circuit = self.graph_state_from_pygraph(graph_20_20)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(self.cmap25, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, self.cmap25, pass_.property_set)
def test_hexagonal_lattice_graph_9_in_25(self):
"""A 9x9 interaction map in 25x25 coupling map"""
graph_9_9 = rustworkx.generators.hexagonal_lattice_graph(9, 9)
circuit = self.graph_state_from_pygraph(graph_9_9)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(self.cmap25, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, self.cmap25, pass_.property_set)
class TestVF2LayoutBackend(LayoutTestCase):
"""Tests VF2Layout against backends"""
def test_5q_circuit_Rueschlikon_no_solution(self):
"""5 qubits in Rueschlikon, no solution
q0[1] ↖ ↗ q0[2]
q0[0]
q0[3] ↙ ↘ q0[4]
"""
cmap16 = FakeRueschlikon().configuration().coupling_map
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[3])
circuit.cx(qr[0], qr[4])
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(CouplingMap(cmap16), seed=self.seed, max_trials=1)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertIsNone(layout)
self.assertEqual(
pass_.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.NO_SOLUTION_FOUND
)
def test_9q_circuit_Rueschlikon_sd(self):
"""9 qubits in Rueschlikon, considering the direction
1 → 2 → 3 → 4 ← 5 ← 6 → 7 ← 8
↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑
0 ← 15 → 14 ← 13 ← 12 → 11 → 10 ← 9
"""
cmap16 = CouplingMap(FakeRueschlikon().configuration().coupling_map)
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2]
circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3]
circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2]
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap16, strict_direction=True, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap16, pass_.property_set)
def test_4q_circuit_Tenerife_loose_nodes(self):
"""4 qubits in Tenerife, with loose nodes
1
↙ ↑
0 ← 2 ← 3
↑ ↙
4
"""
cmap5 = CouplingMap(FakeTenerife().configuration().coupling_map)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap5, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap5, pass_.property_set)
def test_3q_circuit_Tenerife_sd(self):
"""3 qubits in Tenerife, considering the direction
1 1
↙ ↑ ↙ ↑
0 ← 2 ← 3 0 ← qr2 ← qr1
↑ ↙ ↑ ↙
4 qr0
"""
cmap5 = CouplingMap(FakeTenerife().configuration().coupling_map)
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap5, strict_direction=True, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap5, pass_.property_set, strict_direction=True)
def test_9q_circuit_Rueschlikon(self):
"""9 qubits in Rueschlikon, without considering the direction
1 → 2 → 3 → 4 ← 5 ← 6 → 7 ← 8
↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑
0 ← 15 → 14 ← 13 ← 12 → 11 → 10 ← 9
1 -- q1_0 - q1_1 - 4 --- 5 -- 6 - 7 --- q0_1
| | | | | | | |
q1_2 - q1_3 - q0_0 - 13 - q0_3 - 11 - q1_4 - q0_2
"""
cmap16 = CouplingMap(FakeRueschlikon().configuration().coupling_map)
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2]
circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3]
circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2]
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap16, strict_direction=False, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap16, pass_.property_set)
def test_3q_circuit_Tenerife(self):
"""3 qubits in Tenerife, without considering the direction
1 1
↙ ↑ / |
0 ← 2 ← 3 0 - qr1 - qr2
↑ ↙ | /
4 qr0
"""
cmap5 = CouplingMap(FakeTenerife().configuration().coupling_map)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap5, strict_direction=False, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap5, pass_.property_set)
def test_3q_circuit_vigo_with_custom_scores(self):
"""Test custom ErrorMap from analysis pass are used for scoring."""
backend = FakeVigoV2()
target = backend.target
class FakeScore(AnalysisPass):
"""Fake analysis pass with custom scoring."""
def run(self, dag):
error_map = ErrorMap(9)
error_map.add_error((0, 0), 0.1)
error_map.add_error((0, 1), 0.5)
error_map.add_error((1, 1), 0.2)
error_map.add_error((1, 2), 0.8)
error_map.add_error((1, 3), 0.75)
error_map.add_error((2, 2), 0.123)
error_map.add_error((3, 3), 0.333)
error_map.add_error((3, 4), 0.12345423)
error_map.add_error((4, 4), 0.2222)
self.property_set["vf2_avg_error_map"] = error_map
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
vf2_pass = VF2Layout(target=target, seed=1234568942)
property_set = {}
vf2_pass(circuit, property_set)
pm = PassManager([FakeScore(), VF2Layout(target=target, seed=1234568942)])
pm.run(circuit)
# Assert layout is different from backend properties
self.assertNotEqual(property_set["layout"], pm.property_set["layout"])
self.assertLayout(circuit_to_dag(circuit), backend.coupling_map, pm.property_set)
def test_error_map_pickle(self):
"""Test that the `ErrorMap` Rust structure correctly pickles and depickles."""
errors = {(0, 1): 0.2, (1, 0): 0.2, (0, 0): 0.05, (1, 1): 0.02}
error_map = ErrorMap.from_dict(errors)
with io.BytesIO() as fptr:
pickle.dump(error_map, fptr)
fptr.seek(0)
loaded = pickle.load(fptr)
self.assertEqual(len(loaded), len(errors))
self.assertEqual({k: loaded[k] for k in errors}, errors)
def test_perfect_fit_Manhattan(self):
"""A circuit that fits perfectly in Manhattan (65 qubits)
See https://github.com/Qiskit/qiskit-terra/issues/5694"""
manhattan_cm = FakeManhattan().configuration().coupling_map
cmap65 = CouplingMap(manhattan_cm)
rows = [x[0] for x in manhattan_cm]
cols = [x[1] for x in manhattan_cm]
adj_matrix = numpy.zeros((65, 65))
adj_matrix[rows, cols] = 1
circuit = GraphState(adj_matrix).decompose()
circuit.measure_all()
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap65, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap65, pass_.property_set)
class TestVF2LayoutOther(LayoutTestCase):
"""Other VF2Layout tests"""
def test_seed(self):
"""Different seeds yield different results"""
seed_1 = 42
seed_2 = 45
cmap5 = FakeTenerife().configuration().coupling_map
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_1 = VF2Layout(CouplingMap(cmap5), seed=seed_1, max_trials=1)
pass_1.run(dag)
layout_1 = pass_1.property_set["layout"]
self.assertEqual(
pass_1.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND
)
pass_2 = VF2Layout(CouplingMap(cmap5), seed=seed_2, max_trials=1)
pass_2.run(dag)
layout_2 = pass_2.property_set["layout"]
self.assertEqual(
pass_2.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND
)
self.assertNotEqual(layout_1, layout_2)
def test_3_q_gate(self):
"""The pass does not handle gates with more than 2 qubits"""
seed_1 = 42
cmap5 = FakeTenerife().configuration().coupling_map
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.ccx(qr[1], qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_1 = VF2Layout(CouplingMap(cmap5), seed=seed_1, max_trials=1)
pass_1.run(dag)
self.assertEqual(
pass_1.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.MORE_THAN_2Q
)
class TestMultipleTrials(QiskitTestCase):
"""Test the passes behavior with >1 trial."""
def test_no_properties(self):
"""Test it finds the lowest degree perfect layout with no properties."""
vf2_pass = VF2Layout(
CouplingMap(
[
(0, 1),
(0, 2),
(0, 3),
(1, 0),
(1, 2),
(1, 3),
(2, 0),
(2, 1),
(2, 2),
(2, 3),
(3, 0),
(3, 1),
(3, 2),
(4, 0),
(0, 4),
(5, 1),
(1, 5),
]
)
)
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.measure_all()
property_set = {}
vf2_pass(qc, property_set)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {4, 5})
def test_with_properties(self):
"""Test it finds the least noise perfect layout with no properties."""
backend = FakeYorktown()
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.measure_all()
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
vf2_pass = VF2Layout(cmap, properties=properties)
property_set = {}
vf2_pass(qc, property_set)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {1, 3})
def test_max_trials_exceeded(self):
"""Test it exits when max_trials is reached."""
backend = FakeYorktown()
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.cx(0, 1)
qc.measure_all()
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
vf2_pass = VF2Layout(cmap, properties=properties, seed=-1, max_trials=1)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
self.assertIn(
"DEBUG:qiskit.transpiler.passes.layout.vf2_layout:Trial 1 is >= configured max trials 1",
cm.output,
)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {2, 0})
def test_time_limit_exceeded(self):
"""Test the pass stops after time_limit is reached."""
backend = FakeYorktown()
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.cx(0, 1)
qc.measure_all()
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
vf2_pass = VF2Layout(cmap, properties=properties, seed=-1, time_limit=0.0)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
for output in cm.output:
if output.startswith(
"DEBUG:qiskit.transpiler.passes.layout.vf2_layout:VF2Layout has taken"
) and output.endswith("which exceeds configured max time: 0.0"):
break
else:
self.fail("No failure debug log message found")
self.assertEqual(set(property_set["layout"].get_physical_bits()), {2, 0})
def test_reasonable_limits_for_simple_layouts(self):
"""Test that the default trials is set to a reasonable number."""
backend = FakeManhattan()
qc = QuantumCircuit(5)
qc.cx(2, 3)
qc.cx(0, 1)
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
# Run without any limits set
vf2_pass = VF2Layout(cmap, properties=properties, seed=42)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
self.assertIn(
"DEBUG:qiskit.transpiler.passes.layout.vf2_layout:Trial 159 is >= configured max trials 159",
cm.output,
)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {49, 40, 33, 0, 34})
def test_no_limits_with_negative(self):
"""Test that we're not enforcing a trial limit if set to negative."""
backend = FakeYorktown()
qc = QuantumCircuit(3)
qc.h(0)
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
# Run without any limits set
vf2_pass = VF2Layout(
cmap,
properties=properties,
seed=42,
max_trials=0,
)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
for output in cm.output:
self.assertNotIn("is >= configured max trials", output)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {3, 1, 0})
def test_qregs_valid_layout_output(self):
"""Test that vf2 layout doesn't add extra qubits.
Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8667
"""
backend = FakeGuadalupeV2()
qr = QuantumRegister(16, name="qr")
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.rz(pi / 2, qr[0])
qc.sx(qr[0])
qc.sx(qr[1])
qc.rz(-pi / 4, qr[1])
qc.sx(qr[1])
qc.rz(pi / 2, qr[1])
qc.rz(2.8272143, qr[0])
qc.rz(0.43324854, qr[1])
qc.sx(qr[1])
qc.rz(-0.95531662, qr[7])
qc.sx(qr[7])
qc.rz(3 * pi / 4, qr[7])
qc.barrier([qr[1], qr[10], qr[4], qr[0], qr[7]])
vf2_pass = VF2Layout(
seed=12345,
target=backend.target,
)
vf2_pass(qc)
self.assertEqual(len(vf2_pass.property_set["layout"].get_physical_bits()), 16)
self.assertEqual(len(vf2_pass.property_set["layout"].get_virtual_bits()), 16)
pm = PassManager(
[
VF2Layout(
seed=12345,
target=backend.target,
)
]
)
pm += generate_embed_passmanager(backend.coupling_map)
res = pm.run(qc)
self.assertEqual(res.num_qubits, 16)
if __name__ == "__main__":
unittest.main()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A module of magic functions"""
import time
import threading
from IPython.display import display # pylint: disable=import-error
from IPython.core import magic_arguments # pylint: disable=import-error
from IPython.core.magic import cell_magic, Magics, magics_class # pylint: disable=import-error
try:
import ipywidgets as widgets # pylint: disable=import-error
except ImportError:
raise ImportError('These functions need ipywidgets. '
'Run "pip install ipywidgets" before.')
import qiskit
from qiskit.tools.events.progressbar import TextProgressBar
from .progressbar import HTMLProgressBar
def _html_checker(job_var, interval, status, header,
_interval_set=False):
"""Internal function that updates the status
of a HTML job monitor.
Args:
job_var (BaseJob): The job to keep track of.
interval (int): The status check interval
status (widget): HTML ipywidget for output ot screen
header (str): String representing HTML code for status.
_interval_set (bool): Was interval set by user?
"""
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
status.value = header % (job_status_msg)
while job_status_name not in ['DONE', 'CANCELLED']:
time.sleep(interval)
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
if job_status_name == 'ERROR':
break
else:
if job_status_name == 'QUEUED':
job_status_msg += ' (%s)' % job_var.queue_position()
if not _interval_set:
interval = max(job_var.queue_position(), 2)
else:
if not _interval_set:
interval = 2
status.value = header % (job_status_msg)
status.value = header % (job_status_msg)
@magics_class
class StatusMagic(Magics):
"""A class of status magic functions.
"""
@cell_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument(
'-i',
'--interval',
type=float,
default=None,
help='Interval for status check.'
)
def qiskit_job_status(self, line='', cell=None):
"""A Jupyter magic function to check the status of a Qiskit job instance.
"""
args = magic_arguments.parse_argstring(self.qiskit_job_status, line)
if args.interval is None:
args.interval = 2
_interval_set = False
else:
_interval_set = True
# Split cell lines to get LHS variables
cell_lines = cell.split('\n')
line_vars = []
for cline in cell_lines:
if '=' in cline and '==' not in cline:
line_vars.append(cline.replace(' ', '').split('=')[0])
elif '.append(' in cline:
line_vars.append(cline.replace(' ', '').split('(')[0])
# Execute the cell
self.shell.ex(cell)
# Look for all vars that are BaseJob instances
jobs = []
for var in line_vars:
iter_var = False
if '#' not in var:
# The line var is a list or array, but we cannot parse the index
# so just iterate over the whole array for jobs.
if '[' in var:
var = var.split('[')[0]
iter_var = True
elif '.append' in var:
var = var.split('.append')[0]
iter_var = True
if iter_var:
for item in self.shell.user_ns[var]:
if isinstance(item, qiskit.providers.basejob.BaseJob):
jobs.append(item)
else:
if isinstance(self.shell.user_ns[var],
qiskit.providers.basejob.BaseJob):
jobs.append(self.shell.user_ns[var])
# Must have one job class
if not any(jobs):
raise Exception(
"Cell must contain at least one variable of BaseJob type.")
# List index of job if checking status of multiple jobs.
multi_job = False
if len(jobs) > 1:
multi_job = True
job_checkers = []
# Loop over every BaseJob that was found.
for idx, job_var in enumerate(jobs):
style = "font-size:16px;"
if multi_job:
idx_str = '[%s]' % idx
else:
idx_str = ''
header = "<p style='{style}'>Job Status {id}: %s </p>".format(id=idx_str,
style=style)
status = widgets.HTML(
value=header % job_var.status().value)
thread = threading.Thread(target=_html_checker, args=(job_var, args.interval,
status, header,
_interval_set))
thread.start()
job_checkers.append(status)
# Group all HTML widgets into single vertical layout
box = widgets.VBox(job_checkers)
display(box)
@magics_class
class ProgressBarMagic(Magics):
"""A class of progress bar magic functions.
"""
@cell_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument(
'-t',
'--type',
type=str,
default='html',
help="Type of progress bar, 'html' or 'text'."
)
def qiskit_progress_bar(self, line='', cell=None): # pylint: disable=W0613
"""A Jupyter magic function to generate progressbar.
"""
args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line)
if args.type == 'html':
HTMLProgressBar()
elif args.type == 'text':
TextProgressBar()
else:
raise qiskit.QiskitError('Invalid progress bar type.')
self.shell.ex(cell)
|
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
# Import libraries for use
from qiskit import *
import numpy as np
from random import random
from qiskit.extensions import Initialize
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit_textbook.tools import random_state, array_to_latex
## SETUP
# Protocol uses 4 qubits and 1 classical bit in a register
qr = QuantumRegister(4, name="q") # Protocol uses 4 qubits
cr = ClassicalRegister(1, name="cr") # and 1 classical bit cr
sign_flip_circuit = QuantumCircuit(qr, cr)
def encoding(qc, q0, q1, q2):
"""Creates encoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target (Use q1 to control q0.)
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
# initialization instruction to create
# |ψ⟩ from the state |0⟩:
p = 1 # p stands for the probability of sign-fliping the state of the qubit
psi = [np.sqrt(1-p), np.sqrt(p)]
init_gate = Initialize(psi) # initialize the superposition state
init_gate.label = "init"
def error_simulation(qc, q0, q1, q2, q3):
"""Creates error simulation using qubits q0 & q1 & q2 & q3"""
qc.append(init_gate, [3]) # create the superposition state for |q3>
measure(qc, 3, 0) # measure the state on |q3>
qc.z(q0).c_if(cr, 1) # apply z gate on q0 if |1> was measured by |q3>
qc.append(init_gate, [3])
measure(qc, 3, 0)
qc.z(q1).c_if(cr, 1) # apply z gate on q1 if |1> was measured by |q3>
qc.append(init_gate, [3])
measure(qc, 3, 0)
qc.z(q2).c_if(cr, 1) # apply z gate on q2 if |1> was measured by |q3>
def measure(qc, q0, cr):
"""Measures qubit q0 """
qc.barrier()
qc.measure(q0,cr)
def decoding(qc, q0, q1, q2):
"""Creates decoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
qc.ccx(q2,q1,q0) # Apply a Toffoli gate |011> <-> |111>
# Let's apply the process above to our circuit:
# step 0. input |0> -> |+>
sign_flip_circuit.h(0)
# step 1. encoding
encoding(sign_flip_circuit, 0, 1, 2)
sign_flip_circuit.h(0)
sign_flip_circuit.h(1)
sign_flip_circuit.h(2)
# step 2. error simulation
error_simulation(sign_flip_circuit, 0, 1, 2, p)
sign_flip_circuit.barrier()
# step 3. decoding
sign_flip_circuit.h(0)
sign_flip_circuit.h(1)
sign_flip_circuit.h(2)
decoding(sign_flip_circuit, 0, 1, 2)
# step 4. measurement
sign_flip_circuit.h(0)
measure(sign_flip_circuit, 0, 0)
# View the circuit:
%matplotlib inline
sign_flip_circuit.draw(output='mpl')
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(sign_flip_circuit, backend, shots=1024).result().get_counts() # No. of measurement shots = 1024
plot_histogram(counts)
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
# import necessary libraries
import numpy as np
from pprint import pprint
from qiskit import QuantumProgram
from qiskit.tools.visualization import plot_histogram
#import Qconfig
# When working worth external backends (more on this below),
# be sure that the working directory has a
# Qconfig.py file for importing your APIToken from
# your IBM Q Experience account.
# An example file has been provided, so for working
# in this notebook you can simply set
# the variable values to your credentials and rename
# this file as 'Qconfig.py'
# This initial state register
# can be realized in python by creating an instance of the
# QISKit QuantumProgram Class with a quantum register of 2 qubits
# and 2 classical ancilla bits for measuring the states
i = QuantumProgram()
n = 2
i_q = i.create_quantum_register("i_q", n)
i_c = i.create_classical_register("i_c", n)
#i.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url
i.available_backends() #check backends - if you've set up your APIToken properly you
#should be able to see the quantum chips and simulators at IBM
for backend in i.available_backends(): #check backend status
print(backend)
pprint(i.get_backend_status(backend))
def execute_and_plot(qp, circuits, backend = "local_qasm_simulator"):
"""Executes circuits and plots the final
state histograms the for each circuit.
Adapted from 'execute_and_plot' function
in the beginners_guide_composer_examples
notebook provided in IBM's QISKit
tutorial library on GitHub.
Args:
qp: QuantumProgram containing the circuits
circuits (list): list of circuits to execute
backend (string): allows for specifying the backend
to execute on. Defaults to local qasm simulator
downloaded with QISKit library, but can be specified
to run on an actual quantum chip by using the string
names of the available backends at IBM.
"""
# Store the results of the circuit implementation
# using the .execute() method
results = qp.execute(circuits, backend = backend)
for circuit in circuits:
plot_histogram(results.get_counts(circuit)) # .get_counts()
# method returns a dictionary that maps each possible
# final state to the number of instances of
# said state over n evaluations
# (n defaults to 1024 for local qasm simulator),
# where multiple evaluations are a necessity since
# quantum computation outputs are statistically
# informed
# Initialize circuit:
cnot_i_00 = i.create_circuit("cnot_i_00", [i_q], [i_c])
# Note: qubits are assumed by QISKit
# to be initialized in the |0> state
# Apply gates according to diagram:
cnot_i_00.cx(i_q[0], i_q[1]) # Apply CNOT on line 2 controlled by line 1
# Measure final state:
cnot_i_00.measure(i_q[0], i_c[0]) # Write qubit 1 state onto classical ancilla bit 1
cnot_i_00.measure(i_q[1], i_c[1]) # Write qubit 2 state onto classical ancilla bit 2
# Display final state probabilities:
execute_and_plot(i, ["cnot_i_00"])
print(i.get_qasm('cnot_i_00'))
# Initialize circuit:
cnot_i_01 = i.create_circuit("cnot_i_01", [i_q], [i_c])
cnot_i_01.x(i_q[0]) # Set the 1st qubit to |1> by flipping
# the initialized |0> with an X gate before implementing
# the circuit
# Apply gates according to diagram:
cnot_i_01.cx(i_q[0], i_q[1]) # Apply CNOT controlled by line 1
# Measure final state:
cnot_i_01.measure(i_q[0], i_c[0])
cnot_i_01.measure(i_q[1], i_c[1])
# Display final state probabilities:
execute_and_plot(i, ["cnot_i_01"])
# Initialize circuit:
cnot_i_10 = i.create_circuit("cnot_i_10", [i_q], [i_c])
cnot_i_10.x(i_q[1]) # Set the 2nd qubit to |1>
# Apply gates according to diagram:
cnot_i_10.cx(i_q[0], i_q[1]) # Apply CNOT controlled by line 1
# Measure final state:
cnot_i_10.measure(i_q[0], i_c[0])
cnot_i_10.measure(i_q[1], i_c[1])
# Display final state probabilities:
execute_and_plot(i, ["cnot_i_10"])
# Initialize circuit:
cnot_i_11 = i.create_circuit("cnot_i_11", [i_q], [i_c])
cnot_i_11.x(i_q[0]) # Set the 1st qubit to |1>
cnot_i_11.x(i_q[1]) # Set the 2nd qubit to |1>
# Apply gates according to diagram:
cnot_i_11.cx(i_q[0], i_q[1]) # Apply CNOT controlled by line 1
# Measure final states:
cnot_i_11.measure(i_q[0], i_c[0])
cnot_i_11.measure(i_q[1], i_c[1])
# Display final state probabilities:
execute_and_plot(i, ["cnot_i_11"])
# For circuit ii, we can again create a QuantumProgram instance to
# realize a quantum register of size 2 with 2 classical ancilla bits
# for measurement
ii = QuantumProgram()
n = 2
ii_q = ii.create_quantum_register("ii_q", n)
ii_c = ii.create_classical_register("ii_c", n)
#ii.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url
ii.available_backends() #check backends - if you've set up your APIToken properly you
#should be able to see the quantum chips and simulators at IBM
for backend in ii.available_backends(): #check backend status
print(backend)
pprint(ii.get_backend_status(backend))
# Initialize circuit:
cnot_ii_00 = ii.create_circuit("cnot_ii_00", [ii_q], [ii_c])
# Apply gates according to diagram:
cnot_ii_00.h(ii_q) # Apply hadamards in parallel, note that specifying
# a register a a gate method argument applies the operation to all
# qubits in the register
cnot_ii_00.cx(ii_q[1], ii_q[0]) #apply CNOT controlled by line 2
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
# Measure final state:
cnot_ii_00.measure(ii_q[0], ii_c[0])
cnot_ii_00.measure(ii_q[1], ii_c[1])
# Display final state probabilities
execute_and_plot(ii, ["cnot_ii_00"])
# Initialize circuit:
cnot_ii_01 = ii.create_circuit("cnot_ii_01", [ii_q], [ii_c])
cnot_ii_01.x(ii_q[0]) # Set the 1st qubit to |1>
# Apply gates according to diagram:
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
cnot_ii_01.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
# Measure final state:
cnot_ii_01.measure(ii_q[0], ii_c[0])
cnot_ii_01.measure(ii_q[1], ii_c[1])
# Display final state probabilities:
execute_and_plot(ii, ["cnot_ii_01"])
# Initialize circuits
cnot_ii_10 = ii.create_circuit("cnot_ii_10", [ii_q], [ii_c])
cnot_ii_10.x(ii_q[1]) # Set the 2nd qubit to |1>
# Apply gates according to diagram:
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
cnot_ii_10.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
# Measure final state:
cnot_ii_10.measure(ii_q[0], ii_c[0])
cnot_ii_10.measure(ii_q[1], ii_c[1])
# Display final state probabilities:
execute_and_plot(ii, ["cnot_ii_10"])
# Initialize circuits:
cnot_ii_11 = ii.create_circuit("cnot_ii_11", [ii_q], [ii_c])
cnot_ii_11.x(ii_q[0]) # Set the 1st qubit to |1>
cnot_ii_11.x(ii_q[1]) # Set the 2nd qubit to |1>
# Apply gates according to diagram:
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
cnot_ii_11.cx(ii_q[1], ii_q[0]) # Apply CNOT controlled by line 2
cnot_ii_00.h(ii_q) # Apply hadamards in parallel
# Measure final state
cnot_ii_11.measure(ii_q[0], ii_c[0])
cnot_ii_11.measure(ii_q[1], ii_c[1])
# Display final state probabilities
execute_and_plot(ii, ["cnot_ii_11"])
def circuit_i():
i = QuantumProgram()
i_q = i.create_quantum_register('i_q', 2)
i_c = i.create_classical_register('i_c', 2)
initial_states = ['00','01','10','11']
initial_circuits = {state: i.create_circuit('%s'%(state), [i_q], [i_c]) \
for state in initial_states}
final_circuits = {}
for state in initial_states:
if state[0] is '1':
initial_circuits[state].x(i_q[0])
if state[1] is '1':
initial_circuits[state].x(i_q[1])
initial_circuits[state].cx(i_q[0], i_q[1])
initial_circuits[state].measure(i_q[0], i_c[0])
initial_circuits[state].measure(i_q[1], i_c[1])
final_circuits[state] = initial_circuits[state]
return i
def circuit_ii():
ii = QuantumProgram()
ii_q = ii.create_quantum_register('ii_q', 2)
ii_c = ii.create_classical_register('ii_c', 2)
initial_states = ['00','01','10','11']
circuits = {state: ii.create_circuit('%s'%(state), [ii_q], [ii_c]) \
for state in initial_states}
for state in initial_states:
if state[0] is '1':
circuits[state].x(ii_q[0])
if state[1] is '1':
circuits[state].x(ii_q[1])
circuits[state].h(ii_q)
circuits[state].cx(ii_q[1], ii_q[0])
circuits[state].h(ii_q)
circuits[state].measure(ii_q[0], ii_c[0])
circuits[state].measure(ii_q[1], ii_c[1])
return ii
i = circuit_i()
ii = circuit_ii()
#i.set_api(Qconfig.APItoken, Qconfig.config['url'])
#ii.set_api(Qconfig.APItoken, Qconfig.config['url'])
results_i = i.execute(list(i.get_circuit_names()))
results_ii = ii.execute(list(ii.get_circuit_names()))
results_i_mapping = {circuit: results_i.get_counts(circuit) for circuit in list(i.get_circuit_names())}
results_ii_mapping = {circuit: results_ii.get_counts(circuit) for circuit in list(ii.get_circuit_names())}
print(results_i_mapping)
print(results_ii_mapping)
|
https://github.com/adamjm/qiskit-portfolio-optimisation-extended
|
adamjm
|
from qiskit import Aer
from qiskit.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.utils import QuantumInstance
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.applications import OptimizationApplication
from qiskit_optimization.converters import QuadraticProgramToQubo
from qiskit_finance import QiskitFinanceError
from qiskit_finance.data_providers import *
from qiskit import IBMQ, assemble, transpile
from qiskit.utils import algorithm_globals
import numpy as np
import matplotlib.pyplot as plt
import datetime
provider = IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
for backend in provider.backends():
print(backend)
for backend in provider.backends():
print(backend.status().to_dict())
#backend = provider.get_backend('ibmq_santiago')
backend = Aer.get_backend('statevector_simulator')
## Load Stock market Data
stocks = ["AEO", "AAPL", "AEP", "AAL"]
try:
data = YahooDataProvider(
tickers = stocks,
start=datetime.datetime(2018, 1, 1),
end=datetime.datetime(2018, 12, 31))
data.run()
except QiskitFinanceError as ex:
data = None
print(ex)
#Plot Tickers over the time period
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.1), ncol=3)
plt.xticks(rotation=90)
plt.show()
# # set number of assets (= number of qubits)
# num_assets = 4
# seed = 124
# # Generate expected return and covariance matrix from (random) time-series
# stocks = [("TICKER%s" % i) for i in range(num_assets)]
# data = RandomDataProvider(tickers=stocks,
# start=datetime.datetime(2016,1,1),
# end=datetime.datetime(2016,1,30),
# seed=seed)
# data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()
print(stocks)
print(mu)
# plot sigma
plt.imshow(sigma, interpolation='nearest')
plt.show()
q = 0.5
num_assets = 4
seed = 123# set risk factor
budget = num_assets // 2 # set budget
penalty = num_assets # set parameter to scale the budget penalty term
portfolio = PortfolioOptimization(expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget)
qp = portfolio.to_quadratic_program()
qp
def index_to_selection(i, num_assets):
s = "{0:b}".format(i).rjust(num_assets)
x = np.array([1 if s[i]=='1' else 0 for i in reversed(range(num_assets))])
return x
def print_result(result):
selection = result.x
value = result.fval
print('Optimal: selection {}, value {:.4f}'.format(selection, value))
eigenstate = result.min_eigen_solver_result.eigenstate
eigenvector = eigenstate if isinstance(eigenstate, np.ndarray) else eigenstate.to_matrix()
probabilities = np.abs(eigenvector)**2
i_sorted = reversed(np.argsort(probabilities))
print('\n----------------- Full result ---------------------')
print('selection\tvalue\t\tprobability')
print('---------------------------------------------------')
for i in i_sorted:
x = index_to_selection(i, num_assets)
value = QuadraticProgramToQubo().convert(qp).objective.evaluate(x)
#value = portfolio.to_quadratic_program().objective.evaluate(x)
probability = probabilities[i]
print('%10s\t%.4f\t\t%.4f' %(x, value, probability))
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(qp)
print_result(result)
## Classical Optimiser
cobyla = COBYLA()
cobyla.set_options(maxiter=5)
#ry == Ansatz
ry = TwoLocal(num_assets, 'ry', 'cz', reps=3, entanglement='full')
print(ry)
#Variation Quantum Eigensolver
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
vqe_mes = VQE(ry, optimizer=cobyla, quantum_instance=quantum_instance)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(qp)
print_result(result)
algorithm_globals.random_seed = 1234
#backend = Aer.get_backend('statevector_simulator')
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
qaoa_mes = QAOA(optimizer=cobyla, reps=3, quantum_instance=quantum_instance)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qp)
print_result(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
|
Qiskit-Extensions
|
from qiskit.circuit.library import EfficientSU2
circuit = EfficientSU2(num_qubits=4, entanglement="circular").decompose()
circuit.assign_parameters([0.4] * len(circuit.parameters), inplace=True)
circuit.draw("mpl", scale=0.8)
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp(["ZZII", "IZZI", "-IIZZ", "XIXI", "ZIZZ", "IXIX"])
from qiskit_ibm_runtime.fake_provider import FakeManilaV2
backend = FakeManilaV2()
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
pass_manager = generate_preset_pass_manager(
optimization_level=1, backend=backend, initial_layout=[0, 1, 2, 3]
)
transpiled_qc = pass_manager.run(circuit)
print(f"Transpiled circuit depth: {transpiled_qc.depth(lambda x: len(x[1]) >= 2)}")
transpiled_qc.draw("mpl", scale=0.4, idle_wires=False, fold=-1)
from circuit_knitting.cutting import cut_gates
# Find the indices of the distant gates
cut_indices = [
i
for i, instruction in enumerate(circuit.data)
if {circuit.find_bit(q)[0] for q in instruction.qubits} == {0, 3}
]
# Decompose distant CNOTs into TwoQubitQPDGate instances
qpd_circuit, bases = cut_gates(circuit, cut_indices)
qpd_circuit.draw("mpl", scale=0.8)
import numpy as np
from circuit_knitting.cutting import generate_cutting_experiments
# Generate the subexperiments and sampling coefficients
subexperiments, coefficients = generate_cutting_experiments(
circuits=qpd_circuit, observables=observable.paulis, num_samples=np.inf
)
print(f"Sampling overhead: {np.prod([basis.overhead for basis in bases])}")
# Transpile the decomposed circuit to the same layout
transpiled_qpd_circuit = pass_manager.run(subexperiments[100])
print(
f"Original circuit depth after transpile: {transpiled_qc.depth(lambda x: len(x[1]) >= 2)}"
)
print(
f"QPD subexperiment depth after transpile: {transpiled_qpd_circuit.depth(lambda x: len(x[1]) >= 2)}"
)
transpiled_qpd_circuit.draw("mpl", scale=0.8, idle_wires=False, fold=-1)
from qiskit_ibm_runtime import SamplerV2
# Transpile the subeperiments to the backend's instruction set architecture (ISA)
isa_subexperiments = pass_manager.run(subexperiments)
# Set up the Qiskit Runtime Sampler primitive. For a fake backend, this will use a local simulator.
sampler = SamplerV2(backend)
# Submit the subexperiments
job = sampler.run(isa_subexperiments)
# Retrieve the results
results = job.result()
from circuit_knitting.cutting import reconstruct_expectation_values
reconstructed_expvals = reconstruct_expectation_values(
results,
coefficients,
observable.paulis,
)
# Reconstruct final expectation value
final_expval = np.dot(reconstructed_expvals, observable.coeffs)
from qiskit_aer.primitives import EstimatorV2
estimator = EstimatorV2()
exact_expval = estimator.run([(circuit, observable)]).result()[0].data.evs
print(f"Reconstructed expectation value: {np.real(np.round(final_expval, 8))}")
print(f"Exact expectation value: {np.round(exact_expval, 8)}")
print(f"Error in estimation: {np.real(np.round(final_expval-exact_expval, 8))}")
print(
f"Relative error in estimation: {np.real(np.round((final_expval-exact_expval) / exact_expval, 8))}"
)
|
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.
"""
The General Logical Expression-based Quantum Oracle.
"""
import logging
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.aqua import AquaError
from qiskit.aqua.circuits import CNF, DNF
from .oracle import Oracle
from ._pyeda_check import _check_pluggable_valid as check_pyeda_valid
logger = logging.getLogger(__name__)
class LogicalExpressionOracle(Oracle):
CONFIGURATION = {
'name': 'LogicalExpressionOracle',
'description': 'Logical Expression Oracle',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'logical_expression_oracle_schema',
'type': 'object',
'properties': {
'expression': {
'type': ['string', 'null'],
'default': None
},
"optimization": {
"type": "string",
"default": "off",
'oneOf': [
{
'enum': [
'off',
'espresso'
]
}
]
},
'mct_mode': {
'type': 'string',
'default': 'basic',
'oneOf': [
{
'enum': [
'basic',
'basic-dirty-ancilla',
'advanced',
'noancilla'
]
}
]
},
},
'additionalProperties': False
}
}
def __init__(self, expression=None, optimization='off', mct_mode='basic'):
"""
Constructor.
Args:
expression (str): The string of the desired logical expression.
It could be either in the DIMACS CNF format,
or a general boolean logical expression, such as 'a ^ b' and 'v[0] & (~v[1] | v[2])'
optimization (str): The mode of optimization to use for minimizing the circuit.
Currently, besides no optimization ('off'), Aqua also supports an 'espresso' mode
<https://en.wikipedia.org/wiki/Espresso_heuristic_logic_minimizer>
mct_mode (str): The mode to use for building Multiple-Control Toffoli.
"""
self.validate(locals())
super().__init__()
self._mct_mode = mct_mode
self._optimization = optimization
from pyeda.boolalg.expr import ast2expr, expr
from pyeda.parsing.dimacs import parse_cnf
if expression is None:
raw_expr = expr(None)
else:
try:
raw_expr = expr(expression)
except:
try:
raw_expr = ast2expr(parse_cnf(expression.strip(), varname='v'))
except:
raise AquaError('Failed to parse the input expression: {}.'.format(expression))
self._expr = raw_expr
self._process_expr()
self.construct_circuit()
@staticmethod
def check_pluggable_valid():
check_pyeda_valid(LogicalExpressionOracle.CONFIGURATION['name'])
@staticmethod
def _normalize_literal_indices(raw_ast, raw_indices):
idx_mapping = {r: i + 1 for r, i in zip(sorted(raw_indices), range(len(raw_indices)))}
if raw_ast[0] == 'and' or raw_ast[0] == 'or':
clauses = []
for c in raw_ast[1:]:
if c[0] == 'lit':
clauses.append(('lit', (idx_mapping[c[1]]) if c[1] > 0 else (-idx_mapping[-c[1]])))
elif (c[0] == 'or' or c[0] == 'and') and (raw_ast[0] != c[0]):
clause = []
for l in c[1:]:
clause.append(('lit', (idx_mapping[l[1]]) if l[1] > 0 else (-idx_mapping[-l[1]])))
clauses.append((c[0], *clause))
else:
raise AquaError('Unrecognized logical expression: {}'.format(raw_ast))
elif raw_ast[0] == 'const' or raw_ast[0] == 'lit':
return raw_ast
else:
raise AquaError('Unrecognized root expression type: {}.'.format(raw_ast[0]))
return (raw_ast[0], *clauses)
def _process_expr(self):
from pyeda.inter import espresso_exprs
from pyeda.boolalg.expr import AndOp, OrOp, Variable
self._num_vars = self._expr.degree
ast = self._expr.to_ast() if self._expr.is_cnf() else self._expr.to_cnf().to_ast()
ast = LogicalExpressionOracle._normalize_literal_indices(ast, self._expr.usupport)
if self._optimization == 'off':
if ast[0] == 'or':
self._nf = DNF(ast, num_vars=self._num_vars)
else:
self._nf = CNF(ast, num_vars=self._num_vars)
else: # self._optimization == 'espresso':
expr_dnf = self._expr.to_dnf()
if expr_dnf.is_zero() or expr_dnf.is_one():
self._nf = CNF(('const', 0 if expr_dnf.is_zero() else 1), num_vars=self._num_vars)
else:
expr_dnf_m = espresso_exprs(expr_dnf)[0]
expr_dnf_m_ast = LogicalExpressionOracle._normalize_literal_indices(
expr_dnf_m.to_ast(), expr_dnf_m.usupport
)
if isinstance(expr_dnf_m, AndOp) or isinstance(expr_dnf_m, Variable):
self._nf = CNF(expr_dnf_m_ast, num_vars=self._num_vars)
elif isinstance(expr_dnf_m, OrOp):
self._nf = DNF(expr_dnf_m_ast, num_vars=self._num_vars)
else:
raise AquaError('Unexpected espresso optimization result expr: {}'.format(expr_dnf_m))
@property
def variable_register(self):
return self._variable_register
@property
def ancillary_register(self):
return self._ancillary_register
@property
def output_register(self):
return self._output_register
def construct_circuit(self):
if self._circuit is None:
if self._nf is not None:
self._circuit = self._nf.construct_circuit(mct_mode=self._mct_mode)
self._variable_register = self._nf.variable_register
self._output_register = self._nf.output_register
self._ancillary_register = self._nf.ancillary_register
else:
self._variable_register = QuantumRegister(self._num_vars, name='v')
self._output_register = QuantumRegister(1, name='o')
self._ancillary_register = None
self._circuit = QuantumCircuit(self._variable_register, self._output_register)
return self._circuit
def evaluate_classically(self, measurement):
from pyeda.boolalg.expr import AndOp, OrOp, Variable
assignment = [(var + 1) * (int(tf) * 2 - 1) for tf, var in zip(measurement[::-1], range(len(measurement)))]
if self._expr.is_zero():
return False, assignment
elif self._expr.is_one():
return True, assignment
else:
prime_implicants = self._expr.complete_sum()
if prime_implicants.is_zero():
sols = []
elif isinstance(prime_implicants, AndOp):
prime_implicants_ast = LogicalExpressionOracle._normalize_literal_indices(
prime_implicants.to_ast(), prime_implicants.usupport
)
sols = [[l[1] for l in prime_implicants_ast[1:]]]
elif isinstance(prime_implicants, OrOp):
expr_complete_sum = self._expr.complete_sum()
complete_sum_ast = LogicalExpressionOracle._normalize_literal_indices(
expr_complete_sum.to_ast(), expr_complete_sum.usupport
)
sols = [[c[1]] if c[0] == 'lit' else [l[1] for l in c[1:]] for c in complete_sum_ast[1:]]
elif isinstance(prime_implicants, Variable):
sols = [[prime_implicants.to_ast()[1]]]
else:
raise AquaError('Unexpected solution: {}'.format(prime_implicants))
for sol in sols:
if set(sol).issubset(assignment):
return True, assignment
else:
return False, assignment
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 12345
from qiskit_machine_learning.datasets import ad_hoc_data
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, 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,
)
import matplotlib.pyplot as plt
import numpy as np
def plot_features(ax, features, labels, class_label, marker, face, edge, label):
# A train plot
ax.scatter(
# x coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 0],
# y coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 1],
marker=marker,
facecolors=face,
edgecolors=edge,
label=label,
)
def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total):
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],
)
# A train plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train")
# B train plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train")
# A test plot
plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test")
# B test plot
plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset")
plt.show()
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit_machine_learning.kernels import FidelityQuantumKernel
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
sampler = Sampler()
fidelity = ComputeUncompute(sampler=sampler)
adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map)
from sklearn.svm import SVC
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, train_labels)
adhoc_score_callable_function = adhoc_svc.score(test_features, test_labels)
print(f"Callable kernel classification test score: {adhoc_score_callable_function}")
adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features)
adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(
np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues"
)
axs[0].set_title("Ad hoc training kernel matrix")
axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds")
axs[1].set_title("Ad hoc testing kernel matrix")
plt.show()
adhoc_svc = SVC(kernel="precomputed")
adhoc_svc.fit(adhoc_matrix_train, train_labels)
adhoc_score_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels)
print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}")
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=adhoc_kernel)
qsvc.fit(train_features, train_labels)
qsvc_score = qsvc.score(test_features, test_labels)
print(f"QSVC classification test score: {qsvc_score}")
print(f"Classification Model | Accuracy Score")
print(f"---------------------------------------------------------")
print(f"SVC using kernel as a callable function | {adhoc_score_callable_function:10.2f}")
print(f"SVC using precomputed kernel matrix | {adhoc_score_precomputed_kernel:10.2f}")
print(f"QSVC | {qsvc_score:10.2f}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=0,
n=adhoc_dimension,
gap=0.6,
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],
)
# A label plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "B")
# B label plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for clustering")
plt.show()
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
adhoc_kernel = FidelityQuantumKernel(feature_map=adhoc_feature_map)
adhoc_matrix = adhoc_kernel.evaluate(x_vec=train_features)
plt.figure(figsize=(5, 5))
plt.imshow(np.asmatrix(adhoc_matrix), interpolation="nearest", origin="upper", cmap="Greens")
plt.title("Ad hoc clustering kernel matrix")
plt.show()
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score
adhoc_spectral = SpectralClustering(2, affinity="precomputed")
cluster_labels = adhoc_spectral.fit_predict(adhoc_matrix)
cluster_score = normalized_mutual_info_score(cluster_labels, train_labels)
print(f"Clustering score: {cluster_score}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=10,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement="linear")
qpca_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=feature_map)
matrix_train = qpca_kernel.evaluate(x_vec=train_features)
matrix_test = qpca_kernel.evaluate(x_vec=test_features, y_vec=test_features)
from sklearn.decomposition import KernelPCA
kernel_pca_rbf = KernelPCA(n_components=2, kernel="rbf")
kernel_pca_rbf.fit(train_features)
train_features_rbf = kernel_pca_rbf.transform(train_features)
test_features_rbf = kernel_pca_rbf.transform(test_features)
kernel_pca_q = KernelPCA(n_components=2, kernel="precomputed")
train_features_q = kernel_pca_q.fit_transform(matrix_train)
test_features_q = kernel_pca_q.fit_transform(matrix_test)
from sklearn.linear_model import LogisticRegression
logistic_regression = LogisticRegression()
logistic_regression.fit(train_features_q, train_labels)
logistic_score = logistic_regression.score(test_features_q, test_labels)
print(f"Logistic regression score: {logistic_score}")
fig, (q_ax, rbf_ax) = plt.subplots(1, 2, figsize=(10, 5))
plot_features(q_ax, train_features_q, train_labels, 0, "s", "w", "b", "A train")
plot_features(q_ax, train_features_q, train_labels, 1, "o", "w", "r", "B train")
plot_features(q_ax, test_features_q, test_labels, 0, "s", "b", "w", "A test")
plot_features(q_ax, test_features_q, test_labels, 1, "o", "r", "w", "A test")
q_ax.set_ylabel("Principal component #1")
q_ax.set_xlabel("Principal component #0")
q_ax.set_title("Projection of training and test data\n using KPCA with Quantum Kernel")
# Plotting the linear separation
h = 0.01 # step size in the mesh
# create a mesh to plot in
x_min, x_max = train_features_q[:, 0].min() - 1, train_features_q[:, 0].max() + 1
y_min, y_max = train_features_q[:, 1].min() - 1, train_features_q[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
predictions = logistic_regression.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
predictions = predictions.reshape(xx.shape)
q_ax.contourf(xx, yy, predictions, cmap=plt.cm.RdBu, alpha=0.2)
plot_features(rbf_ax, train_features_rbf, train_labels, 0, "s", "w", "b", "A train")
plot_features(rbf_ax, train_features_rbf, train_labels, 1, "o", "w", "r", "B train")
plot_features(rbf_ax, test_features_rbf, test_labels, 0, "s", "b", "w", "A test")
plot_features(rbf_ax, test_features_rbf, test_labels, 1, "o", "r", "w", "A test")
rbf_ax.set_ylabel("Principal component #1")
rbf_ax.set_xlabel("Principal component #0")
rbf_ax.set_title("Projection of training data\n using KernelPCA")
plt.show()
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 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-function-docstring, missing-module-docstring
import unittest
from inspect import signature
from math import pi
import numpy as np
from scipy.linalg import expm
from ddt import data, ddt, unpack
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute
from qiskit.exceptions import QiskitError
from qiskit.circuit.exceptions import CircuitError
from qiskit.test import QiskitTestCase
from qiskit.circuit import Gate, ControlledGate
from qiskit.circuit.library import (
U1Gate,
U2Gate,
U3Gate,
CU1Gate,
CU3Gate,
XXMinusYYGate,
XXPlusYYGate,
RZGate,
XGate,
YGate,
GlobalPhaseGate,
)
from qiskit import BasicAer
from qiskit.quantum_info import Pauli
from qiskit.quantum_info.operators.predicates import matrix_equal, is_unitary_matrix
from qiskit.utils.optionals import HAS_TWEEDLEDUM
from qiskit.quantum_info import Operator
from qiskit import transpile
class TestStandard1Q(QiskitTestCase):
"""Standard Extension Test. Gates with a single Qubit"""
def setUp(self):
super().setUp()
self.qr = QuantumRegister(3, "q")
self.qr2 = QuantumRegister(3, "r")
self.cr = ClassicalRegister(3, "c")
self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr)
def test_barrier(self):
self.circuit.barrier(self.qr[1])
self.assertEqual(len(self.circuit), 1)
self.assertEqual(self.circuit[0].operation.name, "barrier")
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_barrier_wires(self):
self.circuit.barrier(1)
self.assertEqual(len(self.circuit), 1)
self.assertEqual(self.circuit[0].operation.name, "barrier")
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_barrier_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.barrier, self.cr[0])
self.assertRaises(CircuitError, qc.barrier, self.cr)
self.assertRaises(CircuitError, qc.barrier, (self.qr, "a"))
self.assertRaises(CircuitError, qc.barrier, 0.0)
def test_conditional_barrier_invalid(self):
qc = self.circuit
barrier = qc.barrier(self.qr)
self.assertRaises(QiskitError, barrier.c_if, self.cr, 0)
def test_barrier_reg(self):
self.circuit.barrier(self.qr)
self.assertEqual(len(self.circuit), 1)
self.assertEqual(self.circuit[0].operation.name, "barrier")
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2]))
def test_barrier_none(self):
self.circuit.barrier()
self.assertEqual(len(self.circuit), 1)
self.assertEqual(self.circuit[0].operation.name, "barrier")
self.assertEqual(
self.circuit[0].qubits,
(self.qr[0], self.qr[1], self.qr[2], self.qr2[0], self.qr2[1], self.qr2[2]),
)
def test_ccx(self):
self.circuit.ccx(self.qr[0], self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "ccx")
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2]))
def test_ccx_wires(self):
self.circuit.ccx(0, 1, 2)
self.assertEqual(self.circuit[0].operation.name, "ccx")
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2]))
def test_ccx_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.ccx, self.cr[0], self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.ccx, self.qr[0], self.qr[0], self.qr[2])
self.assertRaises(CircuitError, qc.ccx, 0.0, self.qr[0], self.qr[2])
self.assertRaises(CircuitError, qc.ccx, self.cr, self.qr, self.qr)
self.assertRaises(CircuitError, qc.ccx, "a", self.qr[1], self.qr[2])
def test_ch(self):
self.circuit.ch(self.qr[0], self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "ch")
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_ch_wires(self):
self.circuit.ch(0, 1)
self.assertEqual(self.circuit[0].operation.name, "ch")
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_ch_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.ch, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.ch, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.ch, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.ch, (self.qr, 3), self.qr[0])
self.assertRaises(CircuitError, qc.ch, self.cr, self.qr)
self.assertRaises(CircuitError, qc.ch, "a", self.qr[1])
def test_cif_reg(self):
self.circuit.h(self.qr[0]).c_if(self.cr, 7)
self.assertEqual(self.circuit[0].operation.name, "h")
self.assertEqual(self.circuit[0].qubits, (self.qr[0],))
self.assertEqual(self.circuit[0].operation.condition, (self.cr, 7))
def test_cif_single_bit(self):
self.circuit.h(self.qr[0]).c_if(self.cr[0], True)
self.assertEqual(self.circuit[0].operation.name, "h")
self.assertEqual(self.circuit[0].qubits, (self.qr[0],))
self.assertEqual(self.circuit[0].operation.condition, (self.cr[0], True))
def test_crz(self):
self.circuit.crz(1, self.qr[0], self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "crz")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_cry(self):
self.circuit.cry(1, self.qr[0], self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "cry")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_crx(self):
self.circuit.crx(1, self.qr[0], self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "crx")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_crz_wires(self):
self.circuit.crz(1, 0, 1)
self.assertEqual(self.circuit[0].operation.name, "crz")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_cry_wires(self):
self.circuit.cry(1, 0, 1)
self.assertEqual(self.circuit[0].operation.name, "cry")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_crx_wires(self):
self.circuit.crx(1, 0, 1)
self.assertEqual(self.circuit[0].operation.name, "crx")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1]))
def test_crz_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.crz, 0, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.crz, 0, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.crz, 0, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.crz, self.qr[2], self.qr[1], self.qr[0])
self.assertRaises(CircuitError, qc.crz, 0, self.qr[1], self.cr[2])
self.assertRaises(CircuitError, qc.crz, 0, (self.qr, 3), self.qr[1])
self.assertRaises(CircuitError, qc.crz, 0, self.cr, self.qr)
# TODO self.assertRaises(CircuitError, qc.crz, 'a', self.qr[1], self.qr[2])
def test_cry_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.cry, 0, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.cry, 0, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.cry, 0, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.cry, self.qr[2], self.qr[1], self.qr[0])
self.assertRaises(CircuitError, qc.cry, 0, self.qr[1], self.cr[2])
self.assertRaises(CircuitError, qc.cry, 0, (self.qr, 3), self.qr[1])
self.assertRaises(CircuitError, qc.cry, 0, self.cr, self.qr)
# TODO self.assertRaises(CircuitError, qc.cry, 'a', self.qr[1], self.qr[2])
def test_crx_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.crx, 0, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.crx, 0, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.crx, 0, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.crx, self.qr[2], self.qr[1], self.qr[0])
self.assertRaises(CircuitError, qc.crx, 0, self.qr[1], self.cr[2])
self.assertRaises(CircuitError, qc.crx, 0, (self.qr, 3), self.qr[1])
self.assertRaises(CircuitError, qc.crx, 0, self.cr, self.qr)
# TODO self.assertRaises(CircuitError, qc.crx, 'a', self.qr[1], self.qr[2])
def test_cswap(self):
self.circuit.cswap(self.qr[0], self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "cswap")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2]))
def test_cswap_wires(self):
self.circuit.cswap(0, 1, 2)
self.assertEqual(self.circuit[0].operation.name, "cswap")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2]))
def test_cswap_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.cswap, self.qr[1], self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.cswap, self.qr[1], 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.qr[0])
self.assertRaises(CircuitError, qc.cswap, self.qr[0], self.qr[0], self.qr[1])
self.assertRaises(CircuitError, qc.cswap, 0.0, self.qr[0], self.qr[1])
self.assertRaises(CircuitError, qc.cswap, (self.qr, 3), self.qr[0], self.qr[1])
self.assertRaises(CircuitError, qc.cswap, self.cr, self.qr[0], self.qr[1])
self.assertRaises(CircuitError, qc.cswap, "a", self.qr[1], self.qr[2])
def test_cu1(self):
self.circuit.append(CU1Gate(1), [self.qr[1], self.qr[2]])
self.assertEqual(self.circuit[0].operation.name, "cu1")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cu1_wires(self):
self.circuit.append(CU1Gate(1), [1, 2])
self.assertEqual(self.circuit[0].operation.name, "cu1")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cu3(self):
self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr[2]])
self.assertEqual(self.circuit[0].operation.name, "cu3")
self.assertEqual(self.circuit[0].operation.params, [1, 2, 3])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cu3_wires(self):
self.circuit.append(CU3Gate(1, 2, 3), [1, 2])
self.assertEqual(self.circuit[0].operation.name, "cu3")
self.assertEqual(self.circuit[0].operation.params, [1, 2, 3])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cx(self):
self.circuit.cx(self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "cx")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cx_wires(self):
self.circuit.cx(1, 2)
self.assertEqual(self.circuit[0].operation.name, "cx")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cx_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.cx, self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.cx, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.cx, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.cx, (self.qr, 3), self.qr[0])
self.assertRaises(CircuitError, qc.cx, self.cr, self.qr)
self.assertRaises(CircuitError, qc.cx, "a", self.qr[1])
def test_cy(self):
self.circuit.cy(self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "cy")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cy_wires(self):
self.circuit.cy(1, 2)
self.assertEqual(self.circuit[0].operation.name, "cy")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cy_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.cy, self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.cy, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.cy, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.cy, (self.qr, 3), self.qr[0])
self.assertRaises(CircuitError, qc.cy, self.cr, self.qr)
self.assertRaises(CircuitError, qc.cy, "a", self.qr[1])
def test_cz(self):
self.circuit.cz(self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "cz")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cz_wires(self):
self.circuit.cz(1, 2)
self.assertEqual(self.circuit[0].operation.name, "cz")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_cz_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.cz, self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.cz, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.cz, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.cz, (self.qr, 3), self.qr[0])
self.assertRaises(CircuitError, qc.cz, self.cr, self.qr)
self.assertRaises(CircuitError, qc.cz, "a", self.qr[1])
def test_h(self):
self.circuit.h(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "h")
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_h_wires(self):
self.circuit.h(1)
self.assertEqual(self.circuit[0].operation.name, "h")
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_h_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.h, self.cr[0])
self.assertRaises(CircuitError, qc.h, self.cr)
self.assertRaises(CircuitError, qc.h, (self.qr, 3))
self.assertRaises(CircuitError, qc.h, (self.qr, "a"))
self.assertRaises(CircuitError, qc.h, 0.0)
def test_h_reg(self):
instruction_set = self.circuit.h(self.qr)
self.assertEqual(len(instruction_set), 3)
self.assertEqual(instruction_set[0].operation.name, "h")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
def test_h_reg_inv(self):
instruction_set = self.circuit.h(self.qr).inverse()
self.assertEqual(len(instruction_set), 3)
self.assertEqual(instruction_set[0].operation.name, "h")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
def test_iden(self):
self.circuit.i(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "id")
self.assertEqual(self.circuit[0].operation.params, [])
def test_iden_wires(self):
self.circuit.i(1)
self.assertEqual(self.circuit[0].operation.name, "id")
self.assertEqual(self.circuit[0].operation.params, [])
def test_iden_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.i, self.cr[0])
self.assertRaises(CircuitError, qc.i, self.cr)
self.assertRaises(CircuitError, qc.i, (self.qr, 3))
self.assertRaises(CircuitError, qc.i, (self.qr, "a"))
self.assertRaises(CircuitError, qc.i, 0.0)
def test_iden_reg(self):
instruction_set = self.circuit.i(self.qr)
self.assertEqual(len(instruction_set), 3)
self.assertEqual(instruction_set[0].operation.name, "id")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
def test_iden_reg_inv(self):
instruction_set = self.circuit.i(self.qr).inverse()
self.assertEqual(len(instruction_set), 3)
self.assertEqual(instruction_set[0].operation.name, "id")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
def test_rx(self):
self.circuit.rx(1, self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "rx")
self.assertEqual(self.circuit[0].operation.params, [1])
def test_rx_wires(self):
self.circuit.rx(1, 1)
self.assertEqual(self.circuit[0].operation.name, "rx")
self.assertEqual(self.circuit[0].operation.params, [1])
def test_rx_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.rx, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.rx, self.qr[1], 0)
self.assertRaises(CircuitError, qc.rx, 0, self.cr[0])
self.assertRaises(CircuitError, qc.rx, 0, 0.0)
self.assertRaises(CircuitError, qc.rx, self.qr[2], self.qr[1])
self.assertRaises(CircuitError, qc.rx, 0, (self.qr, 3))
self.assertRaises(CircuitError, qc.rx, 0, self.cr)
# TODO self.assertRaises(CircuitError, qc.rx, 'a', self.qr[1])
self.assertRaises(CircuitError, qc.rx, 0, "a")
def test_rx_reg(self):
instruction_set = self.circuit.rx(1, self.qr)
self.assertEqual(len(instruction_set), 3)
self.assertEqual(instruction_set[0].operation.name, "rx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_rx_reg_inv(self):
instruction_set = self.circuit.rx(1, self.qr).inverse()
self.assertEqual(len(instruction_set), 3)
self.assertEqual(instruction_set[0].operation.name, "rx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_rx_pi(self):
qc = self.circuit
qc.rx(pi / 2, self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "rx")
self.assertEqual(self.circuit[0].operation.params, [pi / 2])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_ry(self):
self.circuit.ry(1, self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "ry")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_ry_wires(self):
self.circuit.ry(1, 1)
self.assertEqual(self.circuit[0].operation.name, "ry")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_ry_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.ry, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.ry, self.qr[1], 0)
self.assertRaises(CircuitError, qc.ry, 0, self.cr[0])
self.assertRaises(CircuitError, qc.ry, 0, 0.0)
self.assertRaises(CircuitError, qc.ry, self.qr[2], self.qr[1])
self.assertRaises(CircuitError, qc.ry, 0, (self.qr, 3))
self.assertRaises(CircuitError, qc.ry, 0, self.cr)
# TODO self.assertRaises(CircuitError, qc.ry, 'a', self.qr[1])
self.assertRaises(CircuitError, qc.ry, 0, "a")
def test_ry_reg(self):
instruction_set = self.circuit.ry(1, self.qr)
self.assertEqual(instruction_set[0].operation.name, "ry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_ry_reg_inv(self):
instruction_set = self.circuit.ry(1, self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "ry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_ry_pi(self):
qc = self.circuit
qc.ry(pi / 2, self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "ry")
self.assertEqual(self.circuit[0].operation.params, [pi / 2])
def test_rz(self):
self.circuit.rz(1, self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "rz")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_rz_wires(self):
self.circuit.rz(1, 1)
self.assertEqual(self.circuit[0].operation.name, "rz")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_rz_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.rz, self.cr[0], self.cr[1])
self.assertRaises(CircuitError, qc.rz, self.qr[1], 0)
self.assertRaises(CircuitError, qc.rz, 0, self.cr[0])
self.assertRaises(CircuitError, qc.rz, 0, 0.0)
self.assertRaises(CircuitError, qc.rz, self.qr[2], self.qr[1])
self.assertRaises(CircuitError, qc.rz, 0, (self.qr, 3))
self.assertRaises(CircuitError, qc.rz, 0, self.cr)
# TODO self.assertRaises(CircuitError, qc.rz, 'a', self.qr[1])
self.assertRaises(CircuitError, qc.rz, 0, "a")
def test_rz_reg(self):
instruction_set = self.circuit.rz(1, self.qr)
self.assertEqual(instruction_set[0].operation.name, "rz")
self.assertEqual(instruction_set[2].operation.params, [1])
def test_rz_reg_inv(self):
instruction_set = self.circuit.rz(1, self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "rz")
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_rz_pi(self):
self.circuit.rz(pi / 2, self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "rz")
self.assertEqual(self.circuit[0].operation.params, [pi / 2])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_rzz(self):
self.circuit.rzz(1, self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "rzz")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_rzz_wires(self):
self.circuit.rzz(1, 1, 2)
self.assertEqual(self.circuit[0].operation.name, "rzz")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_rzz_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.rzz, 1, self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.rzz, 1, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.rzz, 1, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.rzz, 1, (self.qr, 3), self.qr[0])
self.assertRaises(CircuitError, qc.rzz, 1, self.cr, self.qr)
self.assertRaises(CircuitError, qc.rzz, 1, "a", self.qr[1])
self.assertRaises(CircuitError, qc.rzz, 0.1, self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.rzz, 0.1, self.qr[0], self.qr[0])
def test_s(self):
self.circuit.s(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "s")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_s_wires(self):
self.circuit.s(1)
self.assertEqual(self.circuit[0].operation.name, "s")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_s_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.s, self.cr[0])
self.assertRaises(CircuitError, qc.s, self.cr)
self.assertRaises(CircuitError, qc.s, (self.qr, 3))
self.assertRaises(CircuitError, qc.s, (self.qr, "a"))
self.assertRaises(CircuitError, qc.s, 0.0)
def test_s_reg(self):
instruction_set = self.circuit.s(self.qr)
self.assertEqual(instruction_set[0].operation.name, "s")
self.assertEqual(instruction_set[2].operation.params, [])
def test_s_reg_inv(self):
instruction_set = self.circuit.s(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "sdg")
self.assertEqual(instruction_set[2].operation.params, [])
def test_sdg(self):
self.circuit.sdg(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "sdg")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_sdg_wires(self):
self.circuit.sdg(1)
self.assertEqual(self.circuit[0].operation.name, "sdg")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_sdg_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.sdg, self.cr[0])
self.assertRaises(CircuitError, qc.sdg, self.cr)
self.assertRaises(CircuitError, qc.sdg, (self.qr, 3))
self.assertRaises(CircuitError, qc.sdg, (self.qr, "a"))
self.assertRaises(CircuitError, qc.sdg, 0.0)
def test_sdg_reg(self):
instruction_set = self.circuit.sdg(self.qr)
self.assertEqual(instruction_set[0].operation.name, "sdg")
self.assertEqual(instruction_set[2].operation.params, [])
def test_sdg_reg_inv(self):
instruction_set = self.circuit.sdg(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "s")
self.assertEqual(instruction_set[2].operation.params, [])
def test_swap(self):
self.circuit.swap(self.qr[1], self.qr[2])
self.assertEqual(self.circuit[0].operation.name, "swap")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_swap_wires(self):
self.circuit.swap(1, 2)
self.assertEqual(self.circuit[0].operation.name, "swap")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2]))
def test_swap_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.swap, self.cr[1], self.cr[2])
self.assertRaises(CircuitError, qc.swap, self.qr[0], self.qr[0])
self.assertRaises(CircuitError, qc.swap, 0.0, self.qr[0])
self.assertRaises(CircuitError, qc.swap, (self.qr, 3), self.qr[0])
self.assertRaises(CircuitError, qc.swap, self.cr, self.qr)
self.assertRaises(CircuitError, qc.swap, "a", self.qr[1])
self.assertRaises(CircuitError, qc.swap, self.qr, self.qr2[[1, 2]])
self.assertRaises(CircuitError, qc.swap, self.qr[:2], self.qr2)
def test_t(self):
self.circuit.t(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "t")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_t_wire(self):
self.circuit.t(1)
self.assertEqual(self.circuit[0].operation.name, "t")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_t_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.t, self.cr[0])
self.assertRaises(CircuitError, qc.t, self.cr)
self.assertRaises(CircuitError, qc.t, (self.qr, 3))
self.assertRaises(CircuitError, qc.t, (self.qr, "a"))
self.assertRaises(CircuitError, qc.t, 0.0)
def test_t_reg(self):
instruction_set = self.circuit.t(self.qr)
self.assertEqual(instruction_set[0].operation.name, "t")
self.assertEqual(instruction_set[2].operation.params, [])
def test_t_reg_inv(self):
instruction_set = self.circuit.t(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "tdg")
self.assertEqual(instruction_set[2].operation.params, [])
def test_tdg(self):
self.circuit.tdg(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "tdg")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_tdg_wires(self):
self.circuit.tdg(1)
self.assertEqual(self.circuit[0].operation.name, "tdg")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_tdg_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.tdg, self.cr[0])
self.assertRaises(CircuitError, qc.tdg, self.cr)
self.assertRaises(CircuitError, qc.tdg, (self.qr, 3))
self.assertRaises(CircuitError, qc.tdg, (self.qr, "a"))
self.assertRaises(CircuitError, qc.tdg, 0.0)
def test_tdg_reg(self):
instruction_set = self.circuit.tdg(self.qr)
self.assertEqual(instruction_set[0].operation.name, "tdg")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_tdg_reg_inv(self):
instruction_set = self.circuit.tdg(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "t")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_u1(self):
self.circuit.append(U1Gate(1), [self.qr[1]])
self.assertEqual(self.circuit[0].operation.name, "u1")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u1_wires(self):
self.circuit.append(U1Gate(1), [1])
self.assertEqual(self.circuit[0].operation.name, "u1")
self.assertEqual(self.circuit[0].operation.params, [1])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u1_reg(self):
instruction_set = self.circuit.append(U1Gate(1), [self.qr])
self.assertEqual(instruction_set[0].operation.name, "u1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_u1_reg_inv(self):
instruction_set = self.circuit.append(U1Gate(1), [self.qr]).inverse()
self.assertEqual(instruction_set[0].operation.name, "u1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_u1_pi(self):
qc = self.circuit
qc.append(U1Gate(pi / 2), [self.qr[1]])
self.assertEqual(self.circuit[0].operation.name, "u1")
self.assertEqual(self.circuit[0].operation.params, [pi / 2])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u2(self):
self.circuit.append(U2Gate(1, 2), [self.qr[1]])
self.assertEqual(self.circuit[0].operation.name, "u2")
self.assertEqual(self.circuit[0].operation.params, [1, 2])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u2_wires(self):
self.circuit.append(U2Gate(1, 2), [1])
self.assertEqual(self.circuit[0].operation.name, "u2")
self.assertEqual(self.circuit[0].operation.params, [1, 2])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u2_reg(self):
instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr])
self.assertEqual(instruction_set[0].operation.name, "u2")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [1, 2])
def test_u2_reg_inv(self):
instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr]).inverse()
self.assertEqual(instruction_set[0].operation.name, "u2")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [-pi - 2, -1 + pi])
def test_u2_pi(self):
self.circuit.append(U2Gate(pi / 2, 0.3 * pi), [self.qr[1]])
self.assertEqual(self.circuit[0].operation.name, "u2")
self.assertEqual(self.circuit[0].operation.params, [pi / 2, 0.3 * pi])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u3(self):
self.circuit.append(U3Gate(1, 2, 3), [self.qr[1]])
self.assertEqual(self.circuit[0].operation.name, "u3")
self.assertEqual(self.circuit[0].operation.params, [1, 2, 3])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u3_wires(self):
self.circuit.append(U3Gate(1, 2, 3), [1])
self.assertEqual(self.circuit[0].operation.name, "u3")
self.assertEqual(self.circuit[0].operation.params, [1, 2, 3])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_u3_reg(self):
instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr])
self.assertEqual(instruction_set[0].operation.name, "u3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [1, 2, 3])
def test_u3_reg_inv(self):
instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr]).inverse()
self.assertEqual(instruction_set[0].operation.name, "u3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2])
def test_u3_pi(self):
self.circuit.append(U3Gate(pi, pi / 2, 0.3 * pi), [self.qr[1]])
self.assertEqual(self.circuit[0].operation.name, "u3")
self.assertEqual(self.circuit[0].operation.params, [pi, pi / 2, 0.3 * pi])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_x(self):
self.circuit.x(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "x")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_x_wires(self):
self.circuit.x(1)
self.assertEqual(self.circuit[0].operation.name, "x")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_x_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.x, self.cr[0])
self.assertRaises(CircuitError, qc.x, self.cr)
self.assertRaises(CircuitError, qc.x, (self.qr, "a"))
self.assertRaises(CircuitError, qc.x, 0.0)
def test_x_reg(self):
instruction_set = self.circuit.x(self.qr)
self.assertEqual(instruction_set[0].operation.name, "x")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_x_reg_inv(self):
instruction_set = self.circuit.x(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "x")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_y(self):
self.circuit.y(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "y")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_y_wires(self):
self.circuit.y(1)
self.assertEqual(self.circuit[0].operation.name, "y")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_y_invalid(self):
qc = self.circuit
self.assertRaises(CircuitError, qc.y, self.cr[0])
self.assertRaises(CircuitError, qc.y, self.cr)
self.assertRaises(CircuitError, qc.y, (self.qr, "a"))
self.assertRaises(CircuitError, qc.y, 0.0)
def test_y_reg(self):
instruction_set = self.circuit.y(self.qr)
self.assertEqual(instruction_set[0].operation.name, "y")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_y_reg_inv(self):
instruction_set = self.circuit.y(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "y")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_z(self):
self.circuit.z(self.qr[1])
self.assertEqual(self.circuit[0].operation.name, "z")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_z_wires(self):
self.circuit.z(1)
self.assertEqual(self.circuit[0].operation.name, "z")
self.assertEqual(self.circuit[0].operation.params, [])
self.assertEqual(self.circuit[0].qubits, (self.qr[1],))
def test_z_reg(self):
instruction_set = self.circuit.z(self.qr)
self.assertEqual(instruction_set[0].operation.name, "z")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_z_reg_inv(self):
instruction_set = self.circuit.z(self.qr).inverse()
self.assertEqual(instruction_set[0].operation.name, "z")
self.assertEqual(instruction_set[1].qubits, (self.qr[1],))
self.assertEqual(instruction_set[2].operation.params, [])
def test_global_phase(self):
qc = self.circuit
qc.append(GlobalPhaseGate(0.1), [])
self.assertEqual(self.circuit[0].operation.name, "global_phase")
self.assertEqual(self.circuit[0].operation.params, [0.1])
self.assertEqual(self.circuit[0].qubits, ())
def test_global_phase_inv(self):
instruction_set = self.circuit.append(GlobalPhaseGate(0.1), []).inverse()
self.assertEqual(len(instruction_set), 1)
self.assertEqual(instruction_set[0].operation.params, [-0.1])
def test_global_phase_matrix(self):
"""Test global_phase matrix."""
theta = 0.1
np.testing.assert_allclose(
np.array(GlobalPhaseGate(theta)),
np.array([[np.exp(1j * theta)]], dtype=complex),
atol=1e-7,
)
def test_global_phase_consistency(self):
"""Tests compatibility of GlobalPhaseGate with QuantumCircuit.global_phase"""
theta = 0.1
qc1 = QuantumCircuit(0, global_phase=theta)
qc2 = QuantumCircuit(0)
qc2.append(GlobalPhaseGate(theta), [])
np.testing.assert_allclose(
Operator(qc1),
Operator(qc2),
atol=1e-7,
)
def test_transpile_global_phase_consistency(self):
"""Tests compatibility of transpiled GlobalPhaseGate with QuantumCircuit.global_phase"""
qc1 = QuantumCircuit(0, global_phase=0.3)
qc2 = QuantumCircuit(0, global_phase=0.2)
qc2.append(GlobalPhaseGate(0.1), [])
np.testing.assert_allclose(
Operator(transpile(qc1, basis_gates=["u"])),
Operator(transpile(qc2, basis_gates=["u"])),
atol=1e-7,
)
@ddt
class TestStandard2Q(QiskitTestCase):
"""Standard Extension Test. Gates with two Qubits"""
def setUp(self):
super().setUp()
self.qr = QuantumRegister(3, "q")
self.qr2 = QuantumRegister(3, "r")
self.cr = ClassicalRegister(3, "c")
self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr)
def test_barrier_reg_bit(self):
self.circuit.barrier(self.qr, self.qr2[0])
self.assertEqual(len(self.circuit), 1)
self.assertEqual(self.circuit[0].operation.name, "barrier")
self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2], self.qr2[0]))
def test_ch_reg_reg(self):
instruction_set = self.circuit.ch(self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "ch")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_ch_reg_reg_inv(self):
instruction_set = self.circuit.ch(self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "ch")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_ch_reg_bit(self):
instruction_set = self.circuit.ch(self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "ch")
self.assertEqual(
instruction_set[1].qubits,
(
self.qr[1],
self.qr2[1],
),
)
self.assertEqual(instruction_set[2].operation.params, [])
def test_ch_reg_bit_inv(self):
instruction_set = self.circuit.ch(self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "ch")
self.assertEqual(
instruction_set[1].qubits,
(
self.qr[1],
self.qr2[1],
),
)
self.assertEqual(instruction_set[2].operation.params, [])
def test_ch_bit_reg(self):
instruction_set = self.circuit.ch(self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "ch")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_crz_reg_reg(self):
instruction_set = self.circuit.crz(1, self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "crz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_crz_reg_reg_inv(self):
instruction_set = self.circuit.crz(1, self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "crz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_crz_reg_bit(self):
instruction_set = self.circuit.crz(1, self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "crz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_crz_reg_bit_inv(self):
instruction_set = self.circuit.crz(1, self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "crz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_crz_bit_reg(self):
instruction_set = self.circuit.crz(1, self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "crz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_crz_bit_reg_inv(self):
instruction_set = self.circuit.crz(1, self.qr[1], self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "crz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cry_reg_reg(self):
instruction_set = self.circuit.cry(1, self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_cry_reg_reg_inv(self):
instruction_set = self.circuit.cry(1, self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cry_reg_bit(self):
instruction_set = self.circuit.cry(1, self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "cry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_cry_reg_bit_inv(self):
instruction_set = self.circuit.cry(1, self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cry_bit_reg(self):
instruction_set = self.circuit.cry(1, self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_cry_bit_reg_inv(self):
instruction_set = self.circuit.cry(1, self.qr[1], self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cry")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_crx_reg_reg(self):
instruction_set = self.circuit.crx(1, self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "crx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_crx_reg_reg_inv(self):
instruction_set = self.circuit.crx(1, self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "crx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_crx_reg_bit(self):
instruction_set = self.circuit.crx(1, self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "crx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_crx_reg_bit_inv(self):
instruction_set = self.circuit.crx(1, self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "crx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_crx_bit_reg(self):
instruction_set = self.circuit.crx(1, self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "crx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_crx_bit_reg_inv(self):
instruction_set = self.circuit.crx(1, self.qr[1], self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "crx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cu1_reg_reg(self):
instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2])
self.assertEqual(instruction_set[0].operation.name, "cu1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_cu1_reg_reg_inv(self):
instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cu1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cu1_reg_bit(self):
instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]])
self.assertEqual(instruction_set[0].operation.name, "cu1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_cu1_reg_bit_inv(self):
instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cu1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cu1_bit_reg(self):
instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2])
self.assertEqual(instruction_set[0].operation.name, "cu1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1])
def test_cu1_bit_reg_inv(self):
instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cu1")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1])
def test_cu3_reg_reg(self):
instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2])
self.assertEqual(instruction_set[0].operation.name, "cu3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1, 2, 3])
def test_cu3_reg_reg_inv(self):
instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cu3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2])
def test_cu3_reg_bit(self):
instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]])
self.assertEqual(instruction_set[0].operation.name, "cu3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1, 2, 3])
def test_cu3_reg_bit_inv(self):
instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cu3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2])
def test_cu3_bit_reg(self):
instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2])
self.assertEqual(instruction_set[0].operation.name, "cu3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [1, 2, 3])
def test_cu3_bit_reg_inv(self):
instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cu3")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2])
def test_cx_reg_reg(self):
instruction_set = self.circuit.cx(self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cx_reg_reg_inv(self):
instruction_set = self.circuit.cx(self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cx_reg_bit(self):
instruction_set = self.circuit.cx(self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "cx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cx_reg_bit_inv(self):
instruction_set = self.circuit.cx(self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cx_bit_reg(self):
instruction_set = self.circuit.cx(self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cx_bit_reg_inv(self):
instruction_set = self.circuit.cx(self.qr[1], self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cy_reg_reg(self):
instruction_set = self.circuit.cy(self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cy")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cy_reg_reg_inv(self):
instruction_set = self.circuit.cy(self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cy")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cy_reg_bit(self):
instruction_set = self.circuit.cy(self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "cy")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cy_reg_bit_inv(self):
instruction_set = self.circuit.cy(self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cy")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cy_bit_reg(self):
instruction_set = self.circuit.cy(self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cy")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cy_bit_reg_inv(self):
instruction_set = self.circuit.cy(self.qr[1], self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cy")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cz_reg_reg(self):
instruction_set = self.circuit.cz(self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cz_reg_reg_inv(self):
instruction_set = self.circuit.cz(self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cz_reg_bit(self):
instruction_set = self.circuit.cz(self.qr, self.qr2[1])
self.assertEqual(instruction_set[0].operation.name, "cz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cz_reg_bit_inv(self):
instruction_set = self.circuit.cz(self.qr, self.qr2[1]).inverse()
self.assertEqual(instruction_set[0].operation.name, "cz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cz_bit_reg(self):
instruction_set = self.circuit.cz(self.qr[1], self.qr2)
self.assertEqual(instruction_set[0].operation.name, "cz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cz_bit_reg_inv(self):
instruction_set = self.circuit.cz(self.qr[1], self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "cz")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_swap_reg_reg(self):
instruction_set = self.circuit.swap(self.qr, self.qr2)
self.assertEqual(instruction_set[0].operation.name, "swap")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_swap_reg_reg_inv(self):
instruction_set = self.circuit.swap(self.qr, self.qr2).inverse()
self.assertEqual(instruction_set[0].operation.name, "swap")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1]))
self.assertEqual(instruction_set[2].operation.params, [])
@unpack
@data(
(0, 0, np.eye(4)),
(
np.pi / 2,
np.pi / 2,
np.array(
[
[np.sqrt(2) / 2, 0, 0, -np.sqrt(2) / 2],
[0, 1, 0, 0],
[0, 0, 1, 0],
[np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2],
]
),
),
(
np.pi,
np.pi / 2,
np.array([[0, 0, 0, -1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]),
),
(
2 * np.pi,
np.pi / 2,
np.array([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]),
),
(
np.pi / 2,
np.pi,
np.array(
[
[np.sqrt(2) / 2, 0, 0, 1j * np.sqrt(2) / 2],
[0, 1, 0, 0],
[0, 0, 1, 0],
[1j * np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2],
]
),
),
(4 * np.pi, 0, np.eye(4)),
)
def test_xx_minus_yy_matrix(self, theta: float, beta: float, expected: np.ndarray):
"""Test XX-YY matrix."""
gate = XXMinusYYGate(theta, beta)
np.testing.assert_allclose(np.array(gate), expected, atol=1e-7)
def test_xx_minus_yy_exponential_formula(self):
"""Test XX-YY exponential formula."""
theta, beta = np.random.uniform(-10, 10, size=2)
gate = XXMinusYYGate(theta, beta)
x = np.array(XGate())
y = np.array(YGate())
xx = np.kron(x, x)
yy = np.kron(y, y)
rz1 = np.kron(np.array(RZGate(beta)), np.eye(2))
np.testing.assert_allclose(
np.array(gate),
rz1 @ expm(-0.25j * theta * (xx - yy)) @ rz1.T.conj(),
atol=1e-7,
)
def test_xx_plus_yy_exponential_formula(self):
"""Test XX+YY exponential formula."""
theta, beta = np.random.uniform(-10, 10, size=2)
gate = XXPlusYYGate(theta, beta)
x = np.array(XGate())
y = np.array(YGate())
xx = np.kron(x, x)
yy = np.kron(y, y)
rz0 = np.kron(np.eye(2), np.array(RZGate(beta)))
np.testing.assert_allclose(
np.array(gate),
rz0.T.conj() @ expm(-0.25j * theta * (xx + yy)) @ rz0,
atol=1e-7,
)
class TestStandard3Q(QiskitTestCase):
"""Standard Extension Test. Gates with three Qubits"""
def setUp(self):
super().setUp()
self.qr = QuantumRegister(3, "q")
self.qr2 = QuantumRegister(3, "r")
self.qr3 = QuantumRegister(3, "s")
self.cr = ClassicalRegister(3, "c")
self.circuit = QuantumCircuit(self.qr, self.qr2, self.qr3, self.cr)
def test_ccx_reg_reg_reg(self):
instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3)
self.assertEqual(instruction_set[0].operation.name, "ccx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_ccx_reg_reg_inv(self):
instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3).inverse()
self.assertEqual(instruction_set[0].operation.name, "ccx")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cswap_reg_reg_reg(self):
instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3)
self.assertEqual(instruction_set[0].operation.name, "cswap")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1]))
self.assertEqual(instruction_set[2].operation.params, [])
def test_cswap_reg_reg_inv(self):
instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3).inverse()
self.assertEqual(instruction_set[0].operation.name, "cswap")
self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1]))
self.assertEqual(instruction_set[2].operation.params, [])
class TestStandardMethods(QiskitTestCase):
"""Standard Extension Test."""
@unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test")
def test_to_matrix(self):
"""test gates implementing to_matrix generate matrix which matches definition."""
from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate
from qiskit.circuit.library.generalized_gates.pauli import PauliGate
from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression
params = [0.1 * (i + 1) for i in range(10)]
gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__()
simulator = BasicAer.get_backend("unitary_simulator")
for gate_class in gate_class_list:
if hasattr(gate_class, "__abstractmethods__"):
# gate_class is abstract
continue
sig = signature(gate_class)
free_params = len(set(sig.parameters) - {"label", "ctrl_state"})
try:
if gate_class == PauliGate:
# special case due to PauliGate using string parameters
gate = gate_class("IXYZ")
elif gate_class == BooleanExpression:
gate = gate_class("x")
elif gate_class == PauliEvolutionGate:
gate = gate_class(Pauli("XYZ"))
else:
gate = gate_class(*params[0:free_params])
except (CircuitError, QiskitError, AttributeError, TypeError):
self.log.info("Cannot init gate with params only. Skipping %s", gate_class)
continue
if gate.name in ["U", "CX"]:
continue
circ = QuantumCircuit(gate.num_qubits)
circ.append(gate, range(gate.num_qubits))
try:
gate_matrix = gate.to_matrix()
except CircuitError:
# gate doesn't implement to_matrix method: skip
self.log.info('to_matrix method FAILED for "%s" gate', gate.name)
continue
definition_unitary = execute([circ], simulator).result().get_unitary()
with self.subTest(gate_class):
# TODO check for exact equality once BasicAer can handle global phase
self.assertTrue(matrix_equal(definition_unitary, gate_matrix, ignore_phase=True))
self.assertTrue(is_unitary_matrix(gate_matrix))
@unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test")
def test_to_matrix_op(self):
"""test gates implementing to_matrix generate matrix which matches
definition using Operator."""
from qiskit.circuit.library.generalized_gates.gms import MSGate
from qiskit.circuit.library.generalized_gates.pauli import PauliGate
from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate
from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression
params = [0.1 * i for i in range(1, 11)]
gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__()
for gate_class in gate_class_list:
if hasattr(gate_class, "__abstractmethods__"):
# gate_class is abstract
continue
sig = signature(gate_class)
if gate_class == MSGate:
# due to the signature (num_qubits, theta, *, n_qubits=Noe) the signature detects
# 3 arguments but really its only 2. This if can be removed once the deprecated
# n_qubits argument is no longer supported.
free_params = 2
else:
free_params = len(set(sig.parameters) - {"label", "ctrl_state"})
try:
if gate_class == PauliGate:
# special case due to PauliGate using string parameters
gate = gate_class("IXYZ")
elif gate_class == BooleanExpression:
gate = gate_class("x")
elif gate_class == PauliEvolutionGate:
gate = gate_class(Pauli("XYZ"))
else:
gate = gate_class(*params[0:free_params])
except (CircuitError, QiskitError, AttributeError, TypeError):
self.log.info("Cannot init gate with params only. Skipping %s", gate_class)
continue
if gate.name in ["U", "CX"]:
continue
try:
gate_matrix = gate.to_matrix()
except CircuitError:
# gate doesn't implement to_matrix method: skip
self.log.info('to_matrix method FAILED for "%s" gate', gate.name)
continue
if not hasattr(gate, "definition") or not gate.definition:
continue
definition_unitary = Operator(gate.definition).data
self.assertTrue(matrix_equal(definition_unitary, gate_matrix))
self.assertTrue(is_unitary_matrix(gate_matrix))
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
import sys, getpass
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
print('Qconfig loaded from %s.' % Qconfig.__file__)
except:
APItoken = getpass.getpass('Please input your token and hit enter: ')
qx_config = {
"APItoken": APItoken,
"url":"https://quantumexperience.ng.bluemix.net/api"}
print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.')
import qiskit as qk
import numpy as np
from scipy.optimize import curve_fit
from qiskit.tools.qcvv.fitters import exp_fit_fun, osc_fit_fun, plot_coherence
# function for padding with QId gates
def pad_QId(circuit,N,qr):
# circuit to add to, N = number of QId gates to add, qr = qubit reg
for ii in range(N):
circuit.barrier(qr)
circuit.iden(qr)
return circuit
qk.register(qx_config['APItoken'], qx_config['url'])
# backend and token settings
backend = qk.get_backend('ibmqx4') # the device to run on
shots = 1024 # the number of shots in the experiment
# Select qubit whose T1 is to be measured
qubit=1
# Creating registers
qr = qk.QuantumRegister(5)
cr = qk.ClassicalRegister(5)
# the delay times are all set in terms of single-qubit gates
# so we need to calculate the time from these parameters
params = backend.parameters['qubits'][qubit]
pulse_length=params['gateTime']['value'] # single-qubit gate time
buffer_length=params['buffer']['value'] # spacing between pulses
unit = params['gateTime']['unit']
steps=10
gates_per_step=120
max_gates=(steps-1)*gates_per_step+1
tot_length=buffer_length+pulse_length
time_per_step=gates_per_step*tot_length
qc_dict={}
for ii in range(steps):
step_num='step_%s'%(str(ii))
qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)})
qc_dict[step_num].x(qr[qubit])
qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit])
qc_dict[step_num].barrier(qr[qubit])
qc_dict[step_num].measure(qr[qubit], cr[qubit])
circuits=list(qc_dict.values())
# run the program
status = backend.status
if status['operational'] == False or status['pending_jobs'] > 10:
print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible')
t1_job=qk.execute(circuits, backend, shots=shots)
# arrange the data from the run
result_t1 = t1_job.result()
keys_0_1=list(result_t1.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001'
data=np.zeros(len(qc_dict.keys())) # numpy array for data
sigma_data = np.zeros(len(qc_dict.keys()))
# change unit from ns to microseconds
plot_factor=1
if unit.find('ns')>-1:
plot_factor=1000
punit='$\mu$s'
xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps in microseconds
for ii,key in enumerate(qc_dict.keys()):
# get the data in terms of counts for the excited state normalized to the total number of counts
data[ii]=float(result_t1.get_counts(qc_dict[key])[keys_0_1[1]])/shots
sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots)
# fit the data to an exponential
fitT1, fcov = curve_fit(exp_fit_fun, xvals, data, bounds=([-1,2,0], [1., 500, 1]))
ferr = np.sqrt(np.diag(fcov))
plot_coherence(xvals, data, sigma_data, fitT1, exp_fit_fun, punit, 'T$_1$ ', qubit)
print("a: " + str(round(fitT1[0],2)) + u" \u00B1 " + str(round(ferr[0],2)))
print("T1: " + str(round(fitT1[1],2))+ " µs" + u" \u00B1 " + str(round(ferr[1],2)) + ' µs')
print("c: " + str(round(fitT1[2],2)) + u" \u00B1 " + str(round(ferr[2],2)))
str(params['T1']['value']) +' ' + params['T1']['unit']
# Select qubit on which to measure T2*
qubit=1
# Creating registers
qr = qk.QuantumRegister(5)
cr = qk.ClassicalRegister(5)
params = backend.parameters['qubits'][qubit]
pulse_length=params['gateTime']['value'] # single-qubit gate time
buffer_length=params['buffer']['value'] # spacing between pulses
unit = params['gateTime']['unit']
steps=35
gates_per_step=20
max_gates=(steps-1)*gates_per_step+2
num_osc=5
tot_length=buffer_length+pulse_length
time_per_step=gates_per_step*tot_length
qc_dict={}
for ii in range(steps):
step_num='step_%s'%(str(ii))
qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)})
qc_dict[step_num].h(qr[qubit])
qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit])
qc_dict[step_num].u1(2*np.pi*num_osc*ii/(steps-1),qr[qubit])
qc_dict[step_num].h(qr[qubit])
qc_dict[step_num].barrier(qr[qubit])
qc_dict[step_num].measure(qr[qubit], cr[qubit])
circuits=list(qc_dict.values())
# run the program
status = backend.status
if status['operational'] == False or status['pending_jobs'] > 10:
print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible')
t2star_job=qk.execute(circuits, backend, shots=shots)
# arrange the data from the run
result_t2star = t2star_job.result()
keys_0_1=list(result_t2star.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001'
# change unit from ns to microseconds
plot_factor=1
if unit.find('ns')>-1:
plot_factor=1000
punit='$\mu$s'
xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps
data=np.zeros(len(qc_dict.keys())) # numpy array for data
sigma_data = np.zeros(len(qc_dict.keys()))
for ii,key in enumerate(qc_dict.keys()):
# get the data in terms of counts for the excited state normalized to the total number of counts
data[ii]=float(result_t2star.get_counts(qc_dict[key])[keys_0_1[1]])/shots
sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots)
fitT2s, fcov = curve_fit(osc_fit_fun, xvals, data, p0=[0.5, 100, 1/10, np.pi, 0], bounds=([0.3,0,0,0,0], [0.5, 200, 1/2,2*np.pi,1]))
ferr = np.sqrt(np.diag(fcov))
plot_coherence(xvals, data, sigma_data, fitT2s, osc_fit_fun, punit, '$T_2^*$ ', qubit)
print("a: " + str(round(fitT2s[0],2)) + u" \u00B1 " + str(round(ferr[0],2)))
print("T2*: " + str(round(fitT2s[1],2))+ " µs"+ u" \u00B1 " + str(round(ferr[1],2)) + ' µs')
print("f: " + str(round(10**3*fitT2s[2],3)) + 'kHz' + u" \u00B1 " + str(round(10**6*ferr[2],3)) + 'kHz')
print("phi: " + str(round(fitT2s[3],2)) + u" \u00B1 " + str(round(ferr[3],2)))
print("c: " + str(round(fitT2s[4],2)) + u" \u00B1 " + str(round(ferr[4],2)))
# Select qubit to measure T2 echo on
qubit=1
# Creating registers
qr = qk.QuantumRegister(5)
cr = qk.ClassicalRegister(5)
params = backend.parameters['qubits'][qubit]
pulse_length=params['gateTime']['value'] # single-qubit gate time
buffer_length=params['buffer']['value'] # spacing between pulses
unit = params['gateTime']['unit']
steps=18
gates_per_step=28
tot_length=buffer_length+pulse_length
max_gates=(steps-1)*2*gates_per_step+3
time_per_step=(2*gates_per_step)*tot_length
qc_dict={}
for ii in range(steps):
step_num='step_%s'%(str(ii))
qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)})
qc_dict[step_num].h(qr[qubit])
qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit])
qc_dict[step_num].x(qr[qubit])
qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit])
qc_dict[step_num].h(qr[qubit])
qc_dict[step_num].barrier(qr[qubit])
qc_dict[step_num].measure(qr[qubit], cr[qubit])
circuits=list(qc_dict.values())
# run the program
status = backend.status
if status['operational'] == False or status['pending_jobs'] > 10:
print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible')
t2echo_job=qk.execute(circuits, backend, shots=shots)
# arrange the data from the run
result_t2echo = t2echo_job.result()
keys_0_1=list(result_t2echo.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001'
# change unit from ns to microseconds
plot_factor=1
if unit.find('ns')>-1:
plot_factor=1000
punit='$\mu$s'
xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps
data=np.zeros(len(qc_dict.keys())) # numpy array for data
sigma_data = np.zeros(len(qc_dict.keys()))
for ii,key in enumerate(qc_dict.keys()):
# get the data in terms of counts for the excited state normalized to the total number of counts
data[ii]=float(result_t2echo.get_counts(qc_dict[key])[keys_0_1[1]])/shots
sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots)
fitT2e, fcov = curve_fit(exp_fit_fun, xvals, data, bounds=([-1,10,0], [1, 150, 1]))
ferr = np.sqrt(np.diag(fcov))
plot_coherence(xvals, data, sigma_data, fitT2e, exp_fit_fun, punit, '$T_{2echo}$ ', qubit)
print("a: " + str(round(fitT2e[0],2)) + u" \u00B1 " + str(round(ferr[0],2)))
print("T2: " + str(round(fitT2e[1],2))+ ' µs' + u" \u00B1 " + str(round(ferr[1],2)) + ' µs')
print("c: " + str(round(fitT2e[2],2)) + u" \u00B1 " + str(round(ferr[2],2)))
str(params['T2']['value']) +' ' + params['T2']['unit']
# Select qubit for CPMG measurement of T2
qubit=1
# Creating registers
qr = qk.QuantumRegister(5)
cr = qk.ClassicalRegister(5)
params = backend.parameters['qubits'][qubit]
pulse_length=params['gateTime']['value'] # single-qubit gate time
buffer_length=params['buffer']['value'] # spacing between pulses
unit = params['gateTime']['unit']
steps=10
gates_per_step=18
num_echo=5 # has to be odd number to end up in excited state at the end
tot_length=buffer_length+pulse_length
time_per_step=((num_echo+1)*gates_per_step+num_echo)*tot_length
max_gates=num_echo*(steps-1)*gates_per_step+num_echo+2
qc_dict={}
for ii in range(steps):
step_num='step_%s'%(str(ii))
qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)})
qc_dict[step_num].h(qr[qubit])
for iii in range(num_echo):
qc_dict[step_num]=pad_QId(qc_dict[step_num], gates_per_step*ii, qr[qubit])
qc_dict[step_num].x(qr[qubit])
qc_dict[step_num]=pad_QId(qc_dict[step_num], gates_per_step*ii, qr[qubit])
qc_dict[step_num].h(qr[qubit])
qc_dict[step_num].barrier(qr[qubit])
qc_dict[step_num].measure(qr[qubit], cr[qubit])
circuits=list(qc_dict.values())
# run the program
status = backend.status
if status['operational'] == False or status['pending_jobs'] > 10:
print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible')
t2cpmg_job=qk.execute(circuits, backend, shots=shots)
# arrange the data from the run
result_t2cpmg = t2cpmg_job.result()
keys_0_1=list(result_t2cpmg.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001'
# change unit from ns to microseconds
plot_factor=1
if unit.find('ns')>-1:
plot_factor=1000
punit='$\mu$s'
xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps
data=np.zeros(len(qc_dict.keys())) # numpy array for data
sigma_data = np.zeros(len(qc_dict.keys()))
for ii,key in enumerate(qc_dict.keys()):
# get the data in terms of counts for the excited state normalized to the total number of counts
data[ii]=float(result_t2cpmg.get_counts(qc_dict[key])[keys_0_1[1]])/shots
sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots)
fitT2cpmg, fcov = curve_fit(exp_fit_fun, xvals, data, bounds=([-1,10,0], [1, 150, 1]))
ferr = np.sqrt(np.diag(fcov))
plot_coherence(xvals, data, sigma_data, fitT2cpmg, exp_fit_fun, punit, '$T_{2cpmg}$ ', qubit)
print("a: " + str(round(fitT2cpmg[0],2)) + u" \u00B1 " + str(round(ferr[0],2)))
print("T2: " + str(round(fitT2cpmg[1],2))+ ' µs' + u" \u00B1 " + str(round(ferr[1],2)) + ' µs')
print("c: " + str(round(fitT2cpmg[2],2)) + u" \u00B1 " + str(round(ferr[2],2)))
|
https://github.com/magn5452/QiskitQaoa
|
magn5452
|
from qiskit import QuantumCircuit
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from VehicleRouting.framework.interfaces.MinimumEigenSolver import MinimumEigenSolver
class QAOAMinimumEigenSolver(MinimumEigenSolver):
def __init__(self, factory):
self.qaoa = factory.create_qaoa()
self.optimizer = MinimumEigenOptimizer(self.qaoa)
def solve(self, quadratic_program):
return self.optimizer.solve(quadratic_program)
def get_optimal_circuit(self) -> QuantumCircuit:
return self.qaoa.get_optimal_circuit()
def get_optimal_vector(self):
return self.qaoa.get_optimal_vector()
def get_optimal_cost(self):
return self.qaoa.get_optimal_cost()
def get_probabilities(self):
return self.qaoa.get_probabilities_for_counts()
def get_optimizer(self):
return self.optimizer
def get_qaoa(self):
return self.qaoa
class ExactMinimumEigenSolver(MinimumEigenSolver):
def __init__(self):
self.exact_minimum_eigen_solver = NumPyMinimumEigensolver()
self.optimizer = MinimumEigenOptimizer(self.exact_minimum_eigen_solver)
def solve(self, quadratic_program):
return self.optimizer.solve(quadratic_program)
def get_optimizer(self):
return self.optimizer
def get_exact_minimum_eigen_solver(self):
return self.exact_minimum_eigen_solver
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from docplex.mp.model import Model
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import CobylaOptimizer, MinimumEigenOptimizer
from qiskit_optimization.algorithms.admm_optimizer import ADMMParameters, ADMMOptimizer
from qiskit_optimization.translators import from_docplex_mp
# If CPLEX is installed, you can uncomment this line to import the CplexOptimizer.
# CPLEX can be used in this tutorial to solve the convex continuous problem,
# but also as a reference to solve the QUBO, or even the full problem.
#
# from qiskit.optimization.algorithms import CplexOptimizer
# define COBYLA optimizer to handle convex continuous problems.
cobyla = CobylaOptimizer()
# define QAOA via the minimum eigen optimizer
qaoa = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA()))
# exact QUBO solver as classical benchmark
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver()) # to solve QUBOs
# in case CPLEX is installed it can also be used for the convex problems, the QUBO,
# or as a benchmark for the full problem.
#
# cplex = CplexOptimizer()
# construct model using docplex
mdl = Model("ex6")
v = mdl.binary_var(name="v")
w = mdl.binary_var(name="w")
t = mdl.binary_var(name="t")
u = mdl.continuous_var(name="u")
mdl.minimize(v + w + t + 5 * (u - 2) ** 2)
mdl.add_constraint(v + 2 * w + t + u <= 3, "cons1")
mdl.add_constraint(v + w + t >= 1, "cons2")
mdl.add_constraint(v + w == 1, "cons3")
# load quadratic program from docplex model
qp = from_docplex_mp(mdl)
print(qp.prettyprint())
admm_params = ADMMParameters(
rho_initial=1001, beta=1000, factor_c=900, maxiter=100, three_block=True, tol=1.0e-6
)
# define QUBO optimizer
qubo_optimizer = exact
# qubo_optimizer = cplex # uncomment to use CPLEX instead
# define classical optimizer
convex_optimizer = cobyla
# convex_optimizer = cplex # uncomment to use CPLEX instead
# initialize ADMM with classical QUBO and convex optimizer
admm = ADMMOptimizer(
params=admm_params, qubo_optimizer=qubo_optimizer, continuous_optimizer=convex_optimizer
)
# run ADMM to solve problem
result = admm.solve(qp)
print(result.prettyprint())
plt.plot(result.state.residuals)
plt.xlabel("Iterations")
plt.ylabel("Residuals")
plt.show()
# define QUBO optimizer
qubo_optimizer = qaoa
# define classical optimizer
convex_optimizer = cobyla
# convex_optimizer = cplex # uncomment to use CPLEX instead
# initialize ADMM with quantum QUBO optimizer and classical convex optimizer
admm_q = ADMMOptimizer(
params=admm_params, qubo_optimizer=qubo_optimizer, continuous_optimizer=convex_optimizer
)
# run ADMM to solve problem
result_q = admm_q.solve(qp)
print(result.prettyprint())
plt.clf()
plt.plot(result_q.state.residuals)
plt.xlabel("Iterations")
plt.ylabel("Residuals")
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
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
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
|
https://github.com/anpaschool/quantum-computing
|
anpaschool
|
from qiskit import *
from math import pi
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(1)
qc.u3(pi/4,pi/4,pi/4,0)
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
plot_bloch_multivector(out)
qc = QuantumCircuit(1)
qc.u2(pi/4,pi/4,0)
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
plot_bloch_multivector(out)
qc = QuantumCircuit(1)
qc.x(0)
qc.u1(pi/4,0)
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
plot_bloch_multivector(out)
qc = QuantumCircuit(1)
qc.rx(pi/2,0)
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
plot_bloch_multivector(out)
qc = QuantumCircuit(1)
qc.ry(pi/2,0)
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
plot_bloch_multivector(out)
qc = QuantumCircuit(1)
qc.rz(pi/2,0)
qc.draw(output='mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
plot_bloch_multivector(out)
|
https://github.com/vm6502q/qiskit-qrack-provider
|
vm6502q
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Shared functionality and helpers for the unit tests.
"""
from enum import Enum
import inspect
import logging
import os
import unittest
from unittest.util import safe_repr
from itertools import repeat
from random import choice, sample
from math import pi
import numpy as np
import fixtures
from qiskit.quantum_info import Operator, Statevector
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.providers.aer import __path__ as main_path
from qiskit.test.base import FullQiskitTestCase
class Path(Enum):
"""Helper with paths commonly used during the tests."""
MAIN = main_path[0]
TEST = os.path.dirname(__file__)
# Examples path: examples/
EXAMPLES = os.path.join(MAIN, '../examples')
class QiskitAerTestCase(FullQiskitTestCase):
"""Helper class that contains common functionality."""
def setUp(self):
super().setUp()
self.useFixture(fixtures.Timeout(120, gentle=False))
@classmethod
def setUpClass(cls):
super().setUpClass()
allow_DeprecationWarning_modules = [
"cvxpy",
]
# for mod in allow_DeprecationWarning_modules:
# warnings.filterwarnings("default", category=DeprecationWarning, module=mod)
cls.moduleName = os.path.splitext(inspect.getfile(cls))[0]
cls.log = logging.getLogger(cls.__name__)
# Set logging to file and stdout if the LOG_LEVEL environment variable
# is set.
if os.getenv("LOG_LEVEL"):
# Set up formatter.
log_fmt = "{}.%(funcName)s:%(levelname)s:%(asctime)s:" " %(message)s".format(
cls.__name__
)
formatter = logging.Formatter(log_fmt)
# Set up the file handler.
log_file_name = "%s.log" % cls.moduleName
file_handler = logging.FileHandler(log_file_name)
file_handler.setFormatter(formatter)
cls.log.addHandler(file_handler)
# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(os.getenv("LOG_LEVEL"), logging.INFO)
cls.log.setLevel(level)
@staticmethod
def _get_resource_path(filename, path=Path.TEST):
""" Get the absolute path to a resource.
Args:
filename (string): filename or relative path to the resource.
path (Path): path used as relative to the filename.
Returns:
str: the absolute path to the resource.
"""
return os.path.normpath(os.path.join(path.value, filename))
# def assertNoLogs(self, logger=None, level=None):
# """
# Context manager to test that no message is sent to the specified
# logger and level (the opposite of TestCase.assertLogs()).
# """
# # pylint: disable=invalid-name
# return _AssertNoLogsContext(self, logger, level)
def assertSuccess(self, result):
"""Assert that simulation executed without errors"""
success = getattr(result, 'success', False)
msg = result.status
if not success:
for i, res in enumerate(getattr(result, 'results', [])):
if res.status != 'DONE':
msg += ', (Circuit {}) {}'.format(i, res.status)
self.assertTrue(success, msg=msg)
@staticmethod
def gate_circuit(gate_cls, num_params=0, rng=None):
"""Construct a circuit from a gate class."""
if num_params:
if rng is None:
rng = np.random.default_rng()
params = rng.random(num_params)
gate = gate_cls(*params, label=None)
else:
gate = gate_cls()
circ = QuantumCircuit(gate.num_qubits)
circ.append(gate, range(gate.num_qubits))
return circ
@staticmethod
def check_position(obj, items, precision=15):
"""Return position of numeric object in a list."""
for pos, item in enumerate(items):
# Try numeric difference first
try:
delta = round(np.linalg.norm(np.array(obj) - np.array(item)),
precision)
if delta == 0:
return pos
# If objects aren't numeric try direct equality comparison
except:
try:
if obj == item:
return pos
except:
return None
return None
@staticmethod
def remove_if_found(obj, items, precision=15):
"""If obj is in list of items, remove first instance"""
pos = QiskitAerTestCase.check_position(obj, items)
if pos is not None:
items.pop(pos)
def compare_statevector(self, result, circuits, targets,
ignore_phase=True, atol=1e-8, rtol=1e-5):
"""Compare final statevectors to targets."""
for pos, test_case in enumerate(zip(circuits, targets)):
circuit, target = test_case
target = Statevector(target)
output = Statevector(result.get_statevector(circuit))
test_msg = "Circuit ({}/{}):".format(pos + 1, len(circuits))
with self.subTest(msg=test_msg):
msg = " {} != {}".format(output, target)
delta = matrix_equal(output.data, target.data,
ignore_phase=True,
atol=atol, rtol=rtol)
self.assertTrue(delta, msg=msg)
def compare_unitary(self, result, circuits, targets,
ignore_phase=True, atol=1e-8, rtol=1e-5):
"""Compare final unitary matrices to targets."""
for pos, test_case in enumerate(zip(circuits, targets)):
circuit, target = test_case
target = Operator(target)
output = Operator(result.get_unitary(circuit))
test_msg = "Circuit ({}/{}):".format(pos + 1, len(circuits))
with self.subTest(msg=test_msg):
msg = test_msg + " {} != {}".format(output.data, target.data)
delta = matrix_equal(output.data, target.data,
ignore_phase=True,
atol=atol, rtol=rtol)
self.assertTrue(delta, msg=msg)
def compare_counts(self, result, circuits, targets, hex_counts=True, delta=0):
"""Compare counts dictionary to targets."""
for pos, test_case in enumerate(zip(circuits, targets)):
circuit, target = test_case
if hex_counts:
# Don't use get_counts method which converts hex
output = result.data(circuit)["counts"]
else:
# Use get counts method which converts hex
output = result.get_counts(circuit)
test_msg = "Circuit ({}/{}):".format(pos + 1, len(circuits))
with self.subTest(msg=test_msg):
msg = test_msg + " {} != {}".format(output, target)
self.assertDictAlmostEqual(
output, target, delta=delta, msg=msg)
def compare_memory(self, result, circuits, targets, hex_counts=True):
"""Compare memory list to target."""
for pos, test_case in enumerate(zip(circuits, targets)):
circuit, target = test_case
self.assertIn("memory", result.data(circuit))
if hex_counts:
# Don't use get_counts method which converts hex
output = result.data(circuit)["memory"]
else:
# Use get counts method which converts hex
output = result.get_memory(circuit)
test_msg = "Circuit ({}/{}):".format(pos + 1, len(circuits))
with self.subTest(msg=test_msg):
msg = " {} != {}".format(output, target)
self.assertEqual(output, target, msg=msg)
def compare_result_metadata(self, result, circuits, key, targets):
"""Compare result metadata key value."""
if not isinstance(targets, (list, tuple)):
targets = len(circuits) * [targets]
for pos, test_case in enumerate(zip(circuits, targets)):
circuit, target = test_case
value = None
metadata = getattr(result.results[0], 'metadata')
if metadata:
value = metadata.get(key)
test_msg = "Circuit ({}/{}):".format(pos + 1, len(circuits))
with self.subTest(msg=test_msg):
msg = " metadata {} value {} != {}".format(key, value, target)
self.assertEqual(value, target, msg=msg)
def assertDictAlmostEqual(self, dict1, dict2, delta=None, msg=None,
places=None, default_value=0):
"""
Assert two dictionaries with numeric values are almost equal.
Fail if the two dictionaries are unequal as determined by
comparing that the difference between values with the same key are
not greater than delta (default 1e-8), or that difference rounded
to the given number of decimal places is not zero. If a key in one
dictionary is not in the other the default_value keyword argument
will be used for the missing value (default 0). If the two objects
compare equal then they will automatically compare almost equal.
Args:
dict1 (dict): a dictionary.
dict2 (dict): a dictionary.
delta (number): threshold for comparison (defaults to 1e-8).
msg (str): return a custom message on failure.
places (int): number of decimal places for comparison.
default_value (number): default value for missing keys.
Raises:
TypeError: raises TestCase failureException if the test fails.
"""
if dict1 == dict2:
# Shortcut
return
if delta is not None and places is not None:
raise TypeError("specify delta or places not both")
if places is not None:
success = True
standard_msg = ''
# check value for keys in target
keys1 = set(dict1.keys())
for key in keys1:
val1 = dict1.get(key, default_value)
val2 = dict2.get(key, default_value)
if round(abs(val1 - val2), places) != 0:
success = False
standard_msg += '(%s: %s != %s), ' % (safe_repr(key),
safe_repr(val1),
safe_repr(val2))
# check values for keys in counts, not in target
keys2 = set(dict2.keys()) - keys1
for key in keys2:
val1 = dict1.get(key, default_value)
val2 = dict2.get(key, default_value)
if round(abs(val1 - val2), places) != 0:
success = False
standard_msg += '(%s: %s != %s), ' % (safe_repr(key),
safe_repr(val1),
safe_repr(val2))
if success is True:
return
standard_msg = standard_msg[:-2] + ' within %s places' % places
else:
if delta is None:
delta = 1e-8 # default delta value
success = True
standard_msg = ''
# check value for keys in target
keys1 = set(dict1.keys())
for key in keys1:
val1 = dict1.get(key, default_value)
val2 = dict2.get(key, default_value)
if abs(val1 - val2) > delta:
success = False
standard_msg += '(%s: %s != %s), ' % (safe_repr(key),
safe_repr(val1),
safe_repr(val2))
# check values for keys in counts, not in target
keys2 = set(dict2.keys()) - keys1
for key in keys2:
val1 = dict1.get(key, default_value)
val2 = dict2.get(key, default_value)
if abs(val1 - val2) > delta:
success = False
standard_msg += '(%s: %s != %s), ' % (safe_repr(key),
safe_repr(val1),
safe_repr(val2))
if success is True:
return
standard_msg = standard_msg[:-2] + ' within %s delta' % delta
msg = self._formatMessage(msg, standard_msg)
raise self.failureException(msg)
# class _AssertNoLogsContext(unittest.case._AssertLogsContext):
# """A context manager used to implement TestCase.assertNoLogs()."""
#
# # pylint: disable=inconsistent-return-statements
# def __exit__(self, exc_type, exc_value, tb):
# """
# This is a modified version of TestCase._AssertLogsContext.__exit__(...)
# """
# self.logger.handlers = self.old_handlers
# self.logger.propagate = self.old_propagate
# self.logger.setLevel(self.old_level)
# if exc_type is not None:
# # let unexpected exceptions pass through
# return False
#
# if self.watcher.records:
# msg = 'logs of level {} or higher triggered on {}:\n'.format(
# logging.getLevelName(self.level), self.logger.name)
# for record in self.watcher.records:
# msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname,
# record.lineno,
# record.getMessage())
#
# self._raiseFailure(msg)
def _is_ci_fork_pull_request():
"""
Check if the tests are being run in a CI environment and if it is a pull
request.
Returns:
bool: True if the tests are executed inside a CI tool, and the changes
are not against the "master" branch.
"""
if os.getenv('TRAVIS'):
# Using Travis CI.
if os.getenv('TRAVIS_PULL_REQUEST_BRANCH'):
return True
elif os.getenv('APPVEYOR'):
# Using AppVeyor CI.
if os.getenv('APPVEYOR_PULL_REQUEST_NUMBER'):
return True
return False
def generate_random_circuit(n_qubits, n_gates, gate_types):
"""
Generation of a random circuit has a history in Qiskit.
Terra used to have a file _random_circuit_generator.py, but it is not there anymore.
This file was located in folder `test`,
hence accessible only to Qiskit developers and not to users.
Currently, as far as I know, each test that requires random circuits has its own
implementation of a random circuit generator.
This includes tests in qiskit-addon-sympy and test_visualization in terra.
Aqua had an issue of writing a random circuit generator, which was closed
with the justification that it is moved to ignes.
"""
qr = QuantumRegister(n_qubits, 'qr')
cr = ClassicalRegister(n_qubits, 'cr')
circuit = QuantumCircuit(qr, cr)
for _ in repeat(None, n_gates):
# Choose the next gate
op_name = choice(gate_types)
if op_name == 'id':
op_name = 'iden'
operation = eval('QuantumCircuit.' + op_name)
# Check if operation is one of u1, u2, u3
if op_name[0] == 'u' and op_name[1].isdigit():
# Number of angles
n_angles = int(op_name[1])
# Number of qubits manipulated by the gate
n_params = 1
else:
n_angles = 0
if op_name == 'measure':
n_params = 1
else:
n_params = len(inspect.signature(operation).parameters) - 1
# Choose qubits
qubit_indices = sample(range(n_qubits), n_params)
qubits = [qr[i] for i in qubit_indices]
# Choose angles
angles = np.random.rand(n_angles) * pi
# Measurement operation
# In all measure operations, the classical register is not random,
# but has the same index as the quantum register
if op_name == 'measure':
classical_regs = [cr[i] for i in qubit_indices]
else:
classical_regs = []
# Add operation to the circuit
operation(circuit, *angles, *qubits, *classical_regs)
return circuit
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import QFT
def create_qpe_circuit(theta, num_qubits):
'''Creates a QPE circuit given theta and num_qubits.'''
# Step 1: Create a circuit with two quantum registers and one classical register.
first = QuantumRegister(size=num_qubits, name='first') # the first register for phase estimation
second = QuantumRegister(size=1, name='second') # the second register for storing eigenvector |psi>
classical = ClassicalRegister(size=num_qubits, name='readout') # classical register for readout
qpe_circuit = QuantumCircuit(first, second, classical)
# Step 2: Initialize the qubits.
# All qubits are initialized in |0> by default, no extra code is needed to initialize the first register.
qpe_circuit.x(second) # Initialize the second register with state |psi>, which is |1> in this example.
# Step 3: Create superposition in the first register.
qpe_circuit.barrier() # Add barriers to separate each step of the algorithm for better visualization.
qpe_circuit.h(first)
# Step 4: Apply a controlled-U^(2^j) black box.
qpe_circuit.barrier()
for j in range(num_qubits):
qpe_circuit.cp(theta*2*np.pi*(2**j), j, num_qubits) # Theta doesn't contain the 2 pi factor.
# Step 5: Apply an inverse QFT to the first register.
qpe_circuit.barrier()
qpe_circuit.compose(QFT(num_qubits, inverse=True), inplace=True)
# Step 6: Measure the first register.
qpe_circuit.barrier()
qpe_circuit.measure(first, classical)
return qpe_circuit
num_qubits = 4
qpe_circuit_fixed_phase = create_qpe_circuit(1/2, num_qubits) # Create a QPE circuit with fixed theta=1/2.
qpe_circuit_fixed_phase.draw('mpl')
from qiskit.circuit import Parameter
theta = Parameter('theta') # Create a parameter `theta` whose values can be assigned later.
qpe_circuit_parameterized = create_qpe_circuit(theta, num_qubits)
qpe_circuit_parameterized.draw('mpl')
number_of_phases = 21
phases = np.linspace(0, 2, number_of_phases)
individual_phases = [[ph] for ph in phases] # Phases need to be expressed as a list of lists.
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
results = Sampler().run(
[qpe_circuit_parameterized]*len(individual_phases),
parameter_values=individual_phases
).result()
from qiskit.tools.visualization import plot_histogram
idx = 6
plot_histogram(results.quasi_dists[idx].binary_probabilities(), legend=[f'$\\theta$={phases[idx]:.3f}'])
def most_likely_bitstring(results_dict):
'''Finds the most likely outcome bit string from a result dictionary.'''
return max(results_dict, key=results_dict.get)
def find_neighbors(bitstring):
'''Finds the neighbors of a bit string.
Example:
For bit string '1010', this function returns ('1001', '1011')
'''
if bitstring == len(bitstring)*'0':
neighbor_left = len(bitstring)*'1'
else:
neighbor_left = format((int(bitstring,2)-1), '0%sb'%len(bitstring))
if bitstring == len(bitstring)*'1':
neighbor_right = len(bitstring)*'0'
else:
neighbor_right = format((int(bitstring,2)+1), '0%sb'%len(bitstring))
return (neighbor_left, neighbor_right)
def estimate_phase(results_dict):
'''Estimates the phase from a result dictionary of a QPE circuit.'''
# Find the most likely outcome bit string N1 and its neighbors.
num_1_key = most_likely_bitstring(results_dict)
neighbor_left, neighbor_right = find_neighbors(num_1_key)
# Get probabilities of N1 and its neighbors.
num_1_prob = results_dict.get(num_1_key)
neighbor_left_prob = results_dict.get(neighbor_left)
neighbor_right_prob = results_dict.get(neighbor_right)
# Find the second most likely outcome N2 and its probability P2 among the neighbors.
if neighbor_left_prob is None:
# neighbor_left doesn't exist
if neighbor_right_prob is None:
# both neighbors don't exist, N2 is N1
num_2_key = num_1_key
num_2_prob = num_1_prob
else:
# If only neighbor_left doesn't exist, N2 is neighbor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
elif neighbor_right_prob is None:
# If only neighbor_right doesn't exist, N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
elif neighbor_left_prob > neighbor_right_prob:
# Both neighbors exist and neighbor_left has higher probability, so N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
else:
# Both neighbors exist and neighbor_right has higher probability, so N2 is neighor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
# Calculate the estimated phases for N1 and N2.
num_qubits = len(num_1_key)
num_1_phase = (int(num_1_key, 2) / 2**num_qubits)
num_2_phase = (int(num_2_key, 2) / 2**num_qubits)
# Calculate the weighted average phase from N1 and N2.
phase_estimated = (num_1_phase * num_1_prob + num_2_phase * num_2_prob) / (num_1_prob + num_2_prob)
return phase_estimated
qpe_solutions = []
for idx, result_dict in enumerate(results.quasi_dists):
qpe_solutions.append(estimate_phase(result_dict.binary_probabilities()))
ideal_solutions = np.append(
phases[:(number_of_phases-1)//2], # first period
np.subtract(phases[(number_of_phases-1)//2:-1], 1) # second period
)
ideal_solutions = np.append(ideal_solutions, np.subtract(phases[-1], 2)) # starting point of the third period
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 6))
plt.plot(phases, ideal_solutions, '--', label='Ideal solutions')
plt.plot(phases, qpe_solutions, 'o', label='QPE solutions')
plt.title('Quantum Phase Estimation Algorithm')
plt.xlabel('Input Phase')
plt.ylabel('Output Phase')
plt.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mlvqc/Byskit
|
mlvqc
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import *
from qiskit.aqua.algorithms import Grover
# First princinple for two parent nodes and one child
class byskit():
def __init__(self, backend,network, loaded_net, evd = None):
self.backend = backend
self.network = network
self.net_keys = [key for key in self.network]
self.loaded_net = loaded_net
self.reg = {}
self.create_circ()
self.root_init()
child_index = np.array([0,0])
parent_index = np.array([0, 0])
for index in range(len(self.net_keys)-1):
parent_key = self.net_keys[index]
child_key = self.net_keys[index+1]
if parent_key != 'root':
parent_index = np.array([parent_index[1], parent_index[1] + self.network[self.net_keys[index + 1]]])
child_index = np.array([child_index[1],child_index[1]+self.network[self.net_keys[index+1]]])
self.child_init(parent_key,parent_index,child_key,child_index)
def create_circ(self):
self.n_anc = 0
self.n_tgt = 0
for key in self.network:
if key == 'root':
n = self.network['root']
self.reg['cntrl'] = QuantumRegister(self.network['root'], 'cntrl')
else:
self.n_anc = max(n-1,self.n_anc)
self.n_tgt += self.network[key]
n = self.network[key]
self.reg['anc'] = QuantumRegister(self.n_anc,'anc')
self.reg['tgt'] = QuantumRegister(self.n_tgt, 'tgt')
self.circ = QuantumCircuit(self.reg['cntrl'],self.reg['anc'],self.reg['tgt'])
def root_init(self):
for i in range(self.network['root']):
theta = self.calc_theta(self.loaded_net['root'][2*i], self.loaded_net['root'][2*i+1])
self.circ.ry(theta, i)
self.circ.barrier()
def child_init(self,parent_key,parent_index,child_key,child_index):
parent_index = parent_index[0]
child_index = child_index[0]
self.a = np.arange(0, 2 ** self.network[parent_key])
self.gates = []
for i in self.a:
s = str(np.binary_repr(i, width=self.network[parent_key]))
self.gates.append(s)
for i in range(2**self.network[parent_key]):
self.xgate(self.gates[i],parent_index)
for j in range(self.network[child_key]):
theta = self.calc_theta(self.loaded_net[child_key][2 * i + 1,j], self.loaded_net[child_key][2 * i,j])
self.cn_ry(theta,j,parent_key,parent_index,child_key,child_index)
self.xgate(self.gates[i],parent_index)
self.circ.barrier()
def xgate(self,gate,parent_index):
for index, item in enumerate(gate):
if int(item) == 0:
self.circ.x(index+parent_index)
#RY gates
def cn_ry(self,theta,target,parent_key,parent_index,child_key,child_index):
# compute
if parent_key == 'root':
self.circ.ccx(self.reg['cntrl'][0], self.reg['cntrl'][1], self.reg['anc'][0])
for i in range(2, self.network[parent_key]):
self.circ.ccx(self.reg['cntrl'][i], self.reg['anc'][i - 2], self.reg['anc'][i - 1])
# copy
self.circ.cry(theta,self.reg['anc'][self.network[parent_key] - 2], self.reg['tgt'][target])
# uncompute
for i in range(self.network[parent_key] - 1, 1, -1):
self.circ.ccx(self.reg['cntrl'][i], self.reg['anc'][i - 2], self.reg['anc'][i - 1])
self.circ.ccx(self.reg['cntrl'][0], self.reg['cntrl'][1], self.reg['anc'][0])
else:
self.circ.ccx(self.reg['tgt'][parent_index+0], self.reg['tgt'][parent_index+1], self.reg['anc'][0])
for i in range(2, self.network[parent_key]):
self.circ.ccx(self.reg['tgt'][parent_index+i], self.reg['anc'][i - 2], self.reg['anc'][i - 1])
# copy
self.circ.cry(theta,self.reg['anc'][self.network[parent_key] - 2], self.reg['tgt'][child_index+target])
# uncompute
for i in range(self.network[parent_key] - 1, 1, -1):
self.circ.ccx(self.reg['tgt'][parent_index+i], self.reg['anc'][i - 2], self.reg['anc'][i - 1])
self.circ.ccx(self.reg['tgt'][parent_index+0], self.reg['tgt'][parent_index+1], self.reg['anc'][0])
def calc_theta(self,p1,p0):
return 2 * np.arctan(np.sqrt((p1)/(p0)))
def plot(self):
self.circ.draw(output='mpl')
plt.show()
def execute_circ(self):
self.circ.measure_all()
results = execute(self.circ, self.backend, shots=4321)
return results
def rejection_sampling(self, evidence, shots=5000, amplitude_amplification=False):
# Run job many times to get multiple samples
samples_list = []
self.n_samples = shots
if amplitude_amplification==True:
self.amplitude_amplification(evidence)
self.circ.measure_all()
for i in range(self.n_samples):
job = execute(self.circ, backend=self.backend, shots=1)
result = list(job.result().get_counts(self.circ).keys())[0]
accept = True
for e in evidence:
if result[evidence[e]['n']]==evidence[e]['state']:
pass
else:
accept=False
if accept == True:
#print('Accepted result ', result)
samples_list.append(result)
print()
print(self.n_samples, 'samples drawn:', len(samples_list), 'samples accepted,', self.n_samples - len(samples_list),
'samples rejected.')
print('Percentage of samples rejected: ', 100 * (1 - (len(samples_list) / self.n_samples)), '%')
return samples_list
def evaluate(self, samples_list, observations):
p_o = 0
for sample in samples_list:
accept = True
for o in observations:
if sample[observations[o]['n']] == observations[o]['state']:
pass
else:
accept = False
if accept == True:
#print('Observation true given evidence')
p_o += 1
p_o /= len(samples_list)
print('Probabilty of observations given evidence = ', p_o)
return p_o
def amplitude_amplification(self,evidence):
self.state_preparation = self.circ
self.oracle = QuantumCircuit(self.ctrl, self.anc, self.tgt)
for index, e in enumerate(evidence):
if evidence[e]['state'] == '1':
self.oracle.z([evidence[e]['n']])
self.grover_op = Grover(self.oracle, state_preparation=self.state_preparation)
self.grover_op.draw()
def oracle(self):
pass
def u_gate(self):
pass
def gen_random_net(network):
np.random.seed(0)
loaded_net = {}
for key in network:
if key == 'root':
n_parent = network[key]
p = np.random.rand(n_parent)
parents = []
for i in p:
parents.append(i)
parents.append(1 - i)
loaded_net[key] = np.array(parents)
else:
n_child = network[key]
child = np.random.rand(2 ** (n_parent + 1), n_child)
for i in range(n_child):
for j in range(2 ** (n_parent)):
child[2 * j + 1, i] = 1 - child[2 * j, i]
loaded_net[key] = child
n_parent = n_child
return loaded_net
if __name__=='__main__':
from qiskit import IBMQ
IBMQ.load_account()
#provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = IBMQ.get_provider(hub='ibm-q-oxford', group='on-boarding', project='on-boarding-proj')
from qiskit import Aer #BasicAer
#backend = BasicAer.get_backend('unitary_simulator')
backend = Aer.get_backend('qasm_simulator')
#network = {'root':2,'child-1':3,'child-2':3,'child-3':2}
network = {'root':2,'child-1':3,'child-2':3}
loaded_net = gen_random_net(network)
b = byskit(backend, network, loaded_net)
b.plot()
evidence = {
'one':{
'n':1,
'state':'1'
},
'two':{
'n':5,
'state':'0'
}
}
#b.rejection_sampling(evidence,amplitude_amplification=True)
sample_list = b.rejection_sampling(evidence, shots=1000,amplitude_amplification=False)
observations = {
'one':{
'n':2,
'state':'0'
},
'two': {
'n': 4,
'state': '1'
}
}
prob = b.evaluate(sample_list, observations)
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
from qiskit import Aer
backend = Aer.get_backend('qasm_simulator')
network = {'root':2,'child-1':3,'child-2':3}
loaded_net = gen_random_net(network)
b = byskit(backend, network, loaded_net)
b.plot()
evidence = {
'one':{
'n':1,
'state':'1'
},
'two':{
'n':5,
'state':'0'
}
}
sample_list = b.rejection_sampling(evidence, shots=1000, amplitude_amplification=True)
observations = {
'one':{
'n':2,
'state':'0'
},
'two': {
'n': 4,
'state': '1'
}
}
prob = b.evaluate(sample_list, observations)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXDebugging())
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Create a Quantum Register with 3 qubits.
q = QuantumRegister(3, 'q')
# Create a Quantum Circuit acting on the q register
circ = QuantumCircuit(q)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(q[0])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(q[0], q[1])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(q[0], q[2])
circ.draw()
# Import Aer
from qiskit import BasicAer
# Run the quantum circuit on a statevector simulator backend
backend = BasicAer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
from qiskit.tools.visualization import plot_state_city
plot_state_city(outputstate)
# Run the quantum circuit on a unitary simulator backend
backend = BasicAer.get_backend('unitary_simulator')
job = execute(circ, backend)
result = job.result()
# Show the results
print(result.get_unitary(circ, decimals=3))
# Create a Classical Register with 3 bits.
c = ClassicalRegister(3, 'c')
# Create a Quantum Circuit
meas = QuantumCircuit(q, c)
meas.barrier(q)
# map the quantum measurement to the classical bits
meas.measure(q,c)
# The Qiskit circuit object supports composition using
# the addition operator.
qc = circ+meas
#drawing the circuit
qc.draw()
# Use Aer's qasm_simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = execute(qc, backend_sim, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
from qiskit import IBMQ
IBMQ.load_accounts()
print("Available backends:")
IBMQ.backends()
from qiskit.providers.ibmq import least_busy
large_enough_devices = IBMQ.backends(filters=lambda x: x.configuration().n_qubits > 4 and
not x.configuration().simulator)
backend = least_busy(large_enough_devices)
print("The best backend is " + backend.name())
from qiskit.tools.monitor import job_monitor
shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots.
max_credits = 3 # Maximum number of credits to spend on executions.
job_exp = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job_exp)
result_exp = job_exp.result()
counts_exp = result_exp.get_counts(qc)
plot_histogram([counts_exp,counts])
backend = IBMQ.get_backend('ibmq_qasm_simulator', hub=None)
shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots.
max_credits = 3 # Maximum number of credits to spend on executions.
job_hpc = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
result_hpc = job_hpc.result()
counts_hpc = result_hpc.get_counts(qc)
plot_histogram(counts_hpc)
jobID = job_exp.job_id()
print('JOB ID: {}'.format(jobID))
job_get=backend.retrieve_job(jobID)
job_get.result().get_counts(qc)
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
groverCircuit.x(qr)
groverCircuit.cz(qr[0],qr[1])
groverCircuit.x(qr)
groverCircuit.h(qr)
groverCircuit.z(qr)
groverCircuit.cz(qr[0],qr[1])
groverCircuit.h(qr)
groverCircuit.draw(output="mpl")
backend_sim = Aer.get_backend('statevector_simulator')
job_sim = execute(groverCircuit, backend_sim)
statevec = job_sim.result().get_statevector()
print(statevec)
groverCircuit.measure(qr,cr)
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load IBM Q account and get the least busy backend device
provider = IBMQ.load_account()
device = least_busy(provider.backends(simulator=False))
print("Running on current least busy device: ", device)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
job = execute(groverCircuit, backend=device, shots=1024, max_credits=10)
job_monitor(job, interval = 2)
# Get the results from the computation
results = job.result()
answer = results.get_counts(groverCircuit)
plot_histogram(answer)
def phase_oracle(circuit, register):
circuit.cz(qr[2],qr[0])
circuit.cz(qr[2],qr[1])
def n_controlled_Z(circuit, controls, target):
"""Implement a Z gate with multiple controls"""
if (len(controls) > 2):
raise ValueError('The controlled Z with more than 2 controls is not implemented')
elif (len(controls) == 1):
circuit.h(target)
circuit.cx(controls[0], target)
circuit.h(target)
elif (len(controls) == 2):
circuit.h(target)
circuit.ccx(controls[0], controls[1], target)
circuit.h(target)
def inversion_about_average(circuit, register, n, barriers):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
if barriers:
circuit.barrier()
n_controlled_Z(circuit, [register[j] for j in range(n-1)], register[n-1])
if barriers:
circuit.barrier()
circuit.x(register)
circuit.h(register)
barriers = True
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
groverCircuit = QuantumCircuit(qr,cr)
groverCircuit.h(qr)
if barriers:
groverCircuit.barrier()
phase_oracle(groverCircuit, qr)
if barriers:
groverCircuit.barrier()
inversion_about_average(groverCircuit, qr, 3, barriers)
if barriers:
groverCircuit.barrier()
groverCircuit.measure(qr,cr)
groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(groverCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results from the computation
results = job.result()
answer = results.get_counts(groverCircuit)
plot_histogram(answer)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
# initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# set the length of the $n$-bit string.
n = 2
# set the oracle, b for balanced, c for constant
oracle = "b"
# if the oracle is balanced, set the hidden bitstring, b
if oracle == "b":
b = 3 # np.random.randint(1,2**n) uncomment for a random value
# if the oracle is constant, set c = 0 or 1 randomly.
if oracle == "c":
c = np.random.randint(2)
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1)
cr = ClassicalRegister(n)
djCircuit = QuantumCircuit(qr, cr)
barriers = True
# Since all qubits are initialized to |0>, we need to flip the second register qubit to the the |1> state
djCircuit.x(qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to all qubits
djCircuit.h(qr)
# Apply barrier
if barriers:
djCircuit.barrier()
# Query the oracle
if oracle == "c": # if the oracle is constant, return c
if c == 1:
djCircuit.x(qr[n])
else:
djCircuit.iden(qr[n])
else: # otherwise, the oracle is balanced and it returns the inner product of the input with b (non-zero bitstring)
for i in range(n):
if (b & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to the first register after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measure the first register
for i in range(n):
djCircuit.measure(qr[i], cr[i])
djCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(djCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
IBMQ.load_account()
IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(djCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
qiskit.__qiskit_version__
|
https://github.com/anpaschool/qiskit-toolkit
|
anpaschool
|
%matplotlib inline
import numpy as np
import IPython
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import seaborn as sns
sns.set()
from helper import *
import os
import glob
import moviepy.editor as mpy
qc1 = QuantumCircuit(1)
qc1.rz(np.pi/4, 0)
style = {'backgroundcolor': 'lavender'}
qc1.draw(output='mpl', style = style)
getStateVector(qc1)
getBlochSphere(qc1)
qc2 = QuantumCircuit(2)
qc2.rz(np.pi/4, 0)
qc2.rz(np.pi/4, 1)
style = {'backgroundcolor': 'lavender'}
qc2.draw(output='mpl', style = style)
qc_e1 = QuantumCircuit(1)
qc_e1.h(0)
qc_e1.barrier()
for i in range(10):
qc_e1.rz(np.pi/5, 0)
qc_e1.barrier()
qc_e1.h(0)
style = {'backgroundcolor': 'lavender'}
qc_e1.draw(output='mpl', style = style)
qc = QuantumCircuit(2)
qc.h(0)
qc.u3(np.pi/4,np.pi/4,0,1)
qc.barrier()
for i in range(8):
qc.rz(np.pi/4, 0)
qc.rz(np.pi/4, 1)
qc.barrier()
qc.h(0)
qc.u3(-np.pi/4,-np.pi/4,0,1)
style = {'backgroundcolor': 'lavender'}
qc.draw(output='mpl', style = style)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from docplex.mp.model import Model
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import CobylaOptimizer, MinimumEigenOptimizer
from qiskit_optimization.algorithms.admm_optimizer import ADMMParameters, ADMMOptimizer
from qiskit_optimization.translators import from_docplex_mp
# If CPLEX is installed, you can uncomment this line to import the CplexOptimizer.
# CPLEX can be used in this tutorial to solve the convex continuous problem,
# but also as a reference to solve the QUBO, or even the full problem.
#
# from qiskit.optimization.algorithms import CplexOptimizer
# define COBYLA optimizer to handle convex continuous problems.
cobyla = CobylaOptimizer()
# define QAOA via the minimum eigen optimizer
qaoa = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA()))
# exact QUBO solver as classical benchmark
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver()) # to solve QUBOs
# in case CPLEX is installed it can also be used for the convex problems, the QUBO,
# or as a benchmark for the full problem.
#
# cplex = CplexOptimizer()
# construct model using docplex
mdl = Model("ex6")
v = mdl.binary_var(name="v")
w = mdl.binary_var(name="w")
t = mdl.binary_var(name="t")
u = mdl.continuous_var(name="u")
mdl.minimize(v + w + t + 5 * (u - 2) ** 2)
mdl.add_constraint(v + 2 * w + t + u <= 3, "cons1")
mdl.add_constraint(v + w + t >= 1, "cons2")
mdl.add_constraint(v + w == 1, "cons3")
# load quadratic program from docplex model
qp = from_docplex_mp(mdl)
print(qp.prettyprint())
admm_params = ADMMParameters(
rho_initial=1001, beta=1000, factor_c=900, maxiter=100, three_block=True, tol=1.0e-6
)
# define QUBO optimizer
qubo_optimizer = exact
# qubo_optimizer = cplex # uncomment to use CPLEX instead
# define classical optimizer
convex_optimizer = cobyla
# convex_optimizer = cplex # uncomment to use CPLEX instead
# initialize ADMM with classical QUBO and convex optimizer
admm = ADMMOptimizer(
params=admm_params, qubo_optimizer=qubo_optimizer, continuous_optimizer=convex_optimizer
)
# run ADMM to solve problem
result = admm.solve(qp)
print(result.prettyprint())
plt.plot(result.state.residuals)
plt.xlabel("Iterations")
plt.ylabel("Residuals")
plt.show()
# define QUBO optimizer
qubo_optimizer = qaoa
# define classical optimizer
convex_optimizer = cobyla
# convex_optimizer = cplex # uncomment to use CPLEX instead
# initialize ADMM with quantum QUBO optimizer and classical convex optimizer
admm_q = ADMMOptimizer(
params=admm_params, qubo_optimizer=qubo_optimizer, continuous_optimizer=convex_optimizer
)
# run ADMM to solve problem
result_q = admm_q.solve(qp)
print(result.prettyprint())
plt.clf()
plt.plot(result_q.state.residuals)
plt.xlabel("Iterations")
plt.ylabel("Residuals")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mspronesti/qlearnkit
|
mspronesti
|
from .encoding_map import EncodingMap
from qiskit import QuantumCircuit
import numpy as np
class BasisEncoding(EncodingMap):
def __init__(self, n_features: int = 2):
"""
Initializes Basis Encoding Map
"""
super().__init__(n_features)
# basis encoding requires 1 qubit
# for each feature
self._num_qubits = n_features
def construct_circuit(self, x) -> QuantumCircuit:
"""
Retrieves the quantum circuit encoding via
Basis Encoding
Args:
x: the data vector to encode
Returns:
the quantum encoding circuit
Note:
All data values must be either 1s or 0s
"""
if isinstance(x, list):
x = np.array(x)
self._check_feature_vector(x)
x = np.array(x)
x_reversed = x[::-1] # match Qiskit qubit ordering
qc = QuantumCircuit(self.num_qubits)
one_indices = np.where(x_reversed == 1)[0]
for i in one_indices:
qc.x(i)
return qc
def _check_feature_vector(self, x):
if np.count_nonzero(x == 0) + np.count_nonzero(x == 1) != len(x):
raise ValueError("All features must be either 0 or 1 for Basis Encoding.")
super()._check_feature_vector(x)
|
https://github.com/Qiskit/feedback
|
Qiskit
|
import qiskit_alt
qiskit_alt.project.ensure_init(calljulia="juliacall", compile=False)
julia = qiskit_alt.project.julia
Main = julia.Main
julia.Main.zeros(3)
type(julia.Main.zeros(3))
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import ElectronicStructureDriverType, ElectronicStructureMoleculeDriver
# Specify the geometry of the H_2 molecule
geometry = [['H', [0., 0., 0.]],
['H', [0., 0., 0.735]]]
basis = 'sto3g'
molecule = Molecule(geometry=geometry,
charge=0, multiplicity=1)
driver = ElectronicStructureMoleculeDriver(molecule, basis=basis, driver_type=ElectronicStructureDriverType.PYSCF)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
es_problem = ElectronicStructureProblem(driver)
second_q_op = es_problem.second_q_ops()
fermionic_hamiltonian = second_q_op[0]
qubit_converter = QubitConverter(mapper=JordanWignerMapper())
nature_qubit_op = qubit_converter.convert(fermionic_hamiltonian)
nature_qubit_op.primitive
import qiskit_alt.electronic_structure
fermi_op = qiskit_alt.electronic_structure.fermionic_hamiltonian(geometry, basis)
pauli_op = qiskit_alt.electronic_structure.jordan_wigner(fermi_op)
pauli_op.simplify() # The Julia Pauli operators use a different sorting convention; we sort again for comparison.
%run ../bench/jordan_wigner_nature_time.py
nature_times
%run ../bench/jordan_wigner_alt_time.py
alt_times
[t_nature / t_qk_alt for t_nature, t_qk_alt in zip(nature_times, alt_times)]
%run ../bench/fermionic_nature_time.py
nature_times
%run ../bench/fermionic_alt_time.py
alt_times
[t_nature / t_qk_alt for t_nature, t_qk_alt in zip(nature_times, alt_times)]
from qiskit_alt.pauli_operators import QuantumOps, PauliSum_to_SparsePauliOp
import numpy as np
m = np.random.rand(2**3, 2**3) # 3-qubit operator
m = Main.convert(Main.Matrix, m) # Convert PythonCall.PyArray to a native Julia type
pauli_sum = QuantumOps.PauliSum(m) # This is a wrapped Julia object
PauliSum_to_SparsePauliOp(pauli_sum) # Convert to qiskit.quantum_info.SparsePauliOp
%run ../bench/from_matrix_quantum_info.py
%run ../bench/from_matrix_alt.py
[t_pyqk / t_qk_alt for t_pyqk, t_qk_alt in zip(pyqk_times, qk_alt_times)]
%run ../bench/pauli_from_list_qinfo.py
%run ../bench/pauli_from_list_alt.py
[x / y for x,y in zip(quantum_info_times, qkalt_times)]
import qiskit.tools.jupyter
d = qiskit.__qiskit_version__._version_dict
d['qiskit_alt'] = qiskit_alt.__version__
%qiskit_version_table
# %load_ext julia.magic
# %julia using Random: randstring
#%julia pauli_strings = [randstring("IXYZ", 10) for _ in 1:1000]
# None;
# %julia import Pkg; Pkg.add("BenchmarkTools")
#%julia using BenchmarkTools: @btime
#%julia @btime QuantumOps.PauliSum($pauli_strings)
#None;
#%julia pauli_sum = QuantumOps.PauliSum(pauli_strings);
#%julia println(length(pauli_sum))
#%julia println(pauli_sum[1])
#6.9 * 2.29 / .343 # Ratio of time to construct PauliSum via qiskit_alt to time in pure Julia
|
https://github.com/abbarreto/qiskit3
|
abbarreto
| |
https://github.com/TendTo/Quantum-random-walk-simulation
|
TendTo
|
import numpy as np
import networkx as nx
from networkx import hypercube_graph
from networkx.drawing.nx_agraph import graphviz_layout
import matplotlib.pyplot as plt
from typing import Callable
from qiskit import QuantumCircuit, Aer, QuantumRegister, ClassicalRegister, transpile
from qiskit.quantum_info import Operator
from qiskit.tools.visualization import plot_histogram, plot_bloch_vector
from qiskit_aer import AerSimulator
from numpy import pi
coords = [1, np.pi / 2, 0] # [Radius, Theta, Phi]
plot_bloch_vector(coords, coord_type="spherical")
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.x(0)
qc.y(1)
qc.h(0)
qc.draw("mpl", initial_state=True)
qc = QuantumCircuit(2)
qc.x(0)
qc.cx(0, 1)
qc.x(0)
qc.draw("mpl", initial_state=True)
pos = {1: [0.75, 1.0], 2: [0.75, 0.15], 3: [0.5, -0.5], 4: [1.0, -0.5]}
U = [
[0.1, 0.2, 0.6, 0.1],
[0.4, 0.3, 0.2, 0.1],
[0.4, 0.2, 0.1, 0.3],
[0.1, 0.0, 0.1, 0.8],
]
G = nx.DiGraph(directed=True)
for i in range(1, 5):
G.add_node(i)
for j in range(1, 5):
G.add_edge(i, j, weight=U[i - 1][j - 1])
nx.draw(G, pos=pos, with_labels=True)
nx.draw_networkx_edge_labels(
G, pos=pos, edge_labels=nx.get_edge_attributes(G, "weight")
)
plt.show()
n_steps = 50 # Number of steps the walker will take
pr = 0.5 # Probability of the walker stepping to the right
initial_position = 0 # Initial position of our walker
def random_walk(pr: float, n_steps: int, initial_pos: int) -> int:
"""Run a random walk with N steps and a probability of stepping to the right of pr.
Args:
pr: probability of stepping to the right
N: number of steps
i: initial position
Returns:
The final position of the walker
"""
position = initial_pos
for _ in range(n_steps):
coin_flip = list(
np.random.choice(2, 1, p=[1 - pr, pr])
) # Flips our weighted coin
position += 2 * coin_flip[0] - 1 # Moves the walker according to the coin flip
return position
print(f"The walker is located at: x = {random_walk(pr, n_steps, initial_position)}")
def dist(n_runs: int, n_steps: int):
"""Plot the distribution of the random walk.
Args:
runs: number of runs
N: number of steps
"""
positions = range(-1 * n_steps, n_steps + 1)
instances = [0 for _ in range(-1 * n_steps, n_steps + 1)]
for _ in range(n_runs):
result = random_walk(pr, n_steps, initial_position)
instances[positions.index(result)] += 1
plt.bar(positions, [n / n_runs for n in instances])
plt.show()
dist(10000, n_steps)
# Number of qubits
n = 3
# Initial state
initial_state = np.array([1] + [0] * (2**n - 1))
assert initial_state.size == 2**n
# Hadamard gate
hadamard_gate_base = 1 / np.sqrt(2) * np.array([[1, 1], [1, -1]])
hadamard_gate = hadamard_gate_base
for i in range(n - 1):
hadamard_gate = np.kron(hadamard_gate, hadamard_gate_base)
# Grover's gate
grover_gate = np.full((2**n, 2**n), 1 / 2 ** (n - 1)) - np.eye(2**n)
# Apply gates
hadamard_res = np.dot(initial_state, hadamard_gate)
hadamard_res = np.square(hadamard_res)
grover_res = np.dot(initial_state, grover_gate)
grover_res = np.square(grover_res)
# Plot results
fig, axes = plt.subplots(2)
plt.suptitle("Hadamard vs Grover gates (|000>)")
for ax, res in zip(axes, [hadamard_res, grover_res]):
ax.set_ylabel("Probability")
ax.set_ylim(0, 1)
ax.bar(tuple(bin(i)[2:].zfill(n) for i in range(res.size)), res)
plt.show()
n_walker_qubits = 4 # The number of qubits used to represent the position of the walker
def coined_walk_circuit(
n_walker_qubits: int,
) -> tuple[QuantumCircuit, QuantumRegister, QuantumRegister, ClassicalRegister]:
"""Create a quantum circuit for the quantum walk.
Args:
n_walker_qubits: number of qubits used to represent the position of the walker
Returns:
a tuple containing the circuit, the walker qubits, the coin qubits and the classical register to store the output
"""
walker_r = QuantumRegister(n_walker_qubits, name="w")
coin_r = QuantumRegister(1, name="c") # The coin requires only one qubit
classic_r = ClassicalRegister(n_walker_qubits, name="output")
qc = QuantumCircuit(walker_r, coin_r, classic_r)
return qc, walker_r, coin_r, classic_r
qc, _, _, _ = coined_walk_circuit(n_walker_qubits)
qc.draw(output="mpl", initial_state=True)
initial_position = 2 ** (
n_walker_qubits - 1
) # The initial position of the walker is the middle of all possible positions
initial_coin_value = 1 # The initial value of the coin is 0
def initialize_coined_walk_circuit(
qc: QuantumCircuit,
walker_r: QuantumRegister,
coin_r: QuantumRegister,
initial_position: int,
initial_coin_value: int,
) -> QuantumCircuit:
"""Initialize the circuit with the initial position of the walker and the initial value of the coin.
Args:
qc: the quantum circuit
walker_r: the quantum register containing the walker's position qubits
coin_r: the quantum register containing the coin qubit
initial_position: the initial position of the walker
initial_coin_value: the initial value of the coin
Returns:
the initialized quantum circuit
"""
if initial_coin_value == 1:
qc.x(coin_r)
for i in range(n_walker_qubits):
if initial_position & (1 << i):
qc.x(walker_r[n_walker_qubits - i - 1])
qc.barrier()
return qc
qc, walker_r, coin_r, _ = coined_walk_circuit(n_walker_qubits)
qc = initialize_coined_walk_circuit(
qc, walker_r, coin_r, initial_position, initial_coin_value
)
qc.draw(output="mpl", initial_state=True)
def coined_walk_step(
qc: QuantumCircuit, walker_r: QuantumRegister, coin_r: QuantumRegister
) -> QuantumCircuit:
"""Single step of the quantum walk.
Args:
qc: quantum circuit
walker_r: the quantum register containing the walker's position qubits
coin_r: the quantum register containing the coin qubit
Returns:
quantum circuit with an added walk step
"""
# "Flip" the coin vector
qc.h(coin_r)
# Implement the Addition Operator
for i in reversed(range(len(walker_r))):
# Qubits with less significant bits than the current one
controls = [walker_r[v] for v in range(len(walker_r) - 1, i, -1)]
controls.append(coin_r) # The coin qubit is also used as a control
qc.mcx(controls, walker_r[i]) # Multi-controlled X gate
if i != 0:
qc.x(walker_r[i]) # Flip the qubit
# Switch the coin vector
qc.x(coin_r)
# Implement the Subtraction Operator
for i in range(len(walker_r)):
if i != 0:
qc.x(walker_r[i]) # Reverse the flip
# Qubits with less significant bits than the current one
controls = [walker_r[v] for v in range(len(walker_r) - 1, i, -1)]
controls.append(coin_r) # The coin qubit is also used as a control
qc.mcx(controls, walker_r[i]) # Multi-controlled X gate
# Revert the switch of the coin vector
qc.x(coin_r)
return qc
qc, walker_r, coin_r, _ = coined_walk_circuit(n_walker_qubits)
qc = coined_walk_step(qc, walker_r, coin_r)
qc.draw(output="mpl", initial_state=True)
n_steps = 5 # The number of steps of the quantum walk
def coined_walk(
n_walker_qubits: int,
n_steps: int,
initial_position: int,
initial_coin_value: int,
init_func: Callable,
) -> QuantumCircuit:
"""Create a quantum circuit for the quantum walk.
Args:
n_walker_qubits: number of qubits used to represent the position of the walker
n_steps: number of steps of the quantum walk
initial_position: initial position of the walker
initial_coin_value: initial value of the coin
init_func: function used to initialize the circuit
Returns:
quantum circuit for the quantum walk
"""
qc, walker_r, coin_r, classic_r = coined_walk_circuit(n_walker_qubits)
qc = init_func(qc, walker_r, coin_r, initial_position, initial_coin_value)
for i in range(n_steps):
step_gate = coined_walk_step(QuantumCircuit(walker_r, coin_r), walker_r, coin_r)
qc.append(step_gate.to_gate(label=f"Step #{i + 1}"), walker_r[:] + coin_r[:])
qc.barrier()
qc.measure(walker_r, reversed(classic_r))
return qc
qc = coined_walk(
n_walker_qubits,
n_steps,
initial_position,
initial_coin_value,
initialize_coined_walk_circuit,
)
qc.draw(output="mpl", initial_state=True)
n_walker_qubits = 6 # The number of qubits used to represent the position of the walker
n_steps = 30 # The number of steps of the quantum walk
initial_position = 2 ** (
n_walker_qubits - 1
) # The initial position of the walker is the middle of all possible positions
initial_coin_value = 0 # The initial value of the coin is 0
n_runs = 5000 # The number of runs of the quantum circuit
qc = coined_walk(
n_walker_qubits,
n_steps,
initial_position,
initial_coin_value,
initialize_coined_walk_circuit,
)
def plot_results(qc: QuantumCircuit, n_runs: int, title: str):
"""Plot the results of the quantum walk.
Args:
qc: quantum circuit for the quantum walk
n_runs: number of runs of the quantum circuit
Returns:
histogram of the results of the quantum walk
"""
simulator: AerSimulator = Aer.get_backend("aer_simulator")
transpiled_qc = transpile(qc, simulator)
results = simulator.run(transpiled_qc, shots=n_runs).result()
counts = results.get_counts(transpiled_qc)
counts = {int(k, 2): v for k, v in counts.items()}
return plot_histogram(counts, title=title)
plot_results(qc, n_runs, "Quantum Coined Walk")
def initialize_balance_coined_walk_circuit(
qc: QuantumCircuit,
walker_r: QuantumRegister,
coin_r: QuantumRegister,
initial_position: int,
initial_coin_value: int,
) -> QuantumCircuit:
"""Initialize the circuit with the initial position of the walker and the initial value of the coin.
Set the coin qubit to |+> and apply the S gate to it to make sure that the coin operator keeps being balanced.
Args:
qc: the quantum circuit
walker_r: the quantum register containing the walker's position qubits
coin_r: the quantum register containing the coin qubit
initial_position: the initial position of the walker
initial_coin_value: the initial value of the coin
Returns:
the initialized quantum circuit
"""
if initial_coin_value == 1:
qc.x(coin_r)
qc.h(coin_r)
qc.s(coin_r)
for i in range(n_walker_qubits):
if initial_position & (1 << i):
qc.x(walker_r[n_walker_qubits - i - 1])
qc.barrier()
return qc
qc, walker_r, coin_r, _ = coined_walk_circuit(n_walker_qubits)
qc = initialize_balance_coined_walk_circuit(
qc, walker_r, coin_r, initial_position, initial_coin_value
)
qc.draw(output="mpl", initial_state=True)
n_walker_qubits = 6 # The number of qubits used to represent the position of the walker
n_steps = 30 # The number of steps of the quantum walk
initial_position = 2 ** (
n_walker_qubits - 1
) # The initial position of the walker is the middle of all possible positions
initial_coin_value = 0 # The initial value of the coin is 0
n_runs = 5000 # The number of runs of the quantum circuit
qc = coined_walk(
n_walker_qubits,
n_steps,
initial_position,
initial_coin_value,
initialize_balance_coined_walk_circuit,
)
plot_results(qc, n_runs, "Balanced Quantum Coined Walk")
n = 3 # Number of qubits
G = hypercube_graph(n) # Create hypercube graph
# Draw graph
nx.draw(
G,
with_labels=True,
pos=graphviz_layout(G, prog="dot"),
node_color="#dddddd",
node_size=2500,
)
plt.show()
n = 2 # Dimension of the hypercube
def graph_walk_circuit(
n: int,
) -> tuple[QuantumCircuit, QuantumRegister, QuantumRegister, ClassicalRegister]:
"""Create a quantum circuit for the graph walk.
Args:
n: number of qubits used to represent the position of the walker
Returns:
quantum circuit for the graph walk, walker register, coin register, and output register
"""
walker_r = QuantumRegister(2**n, name="w")
coin_r = QuantumRegister(n, name="c")
classic_r = ClassicalRegister(2**n, name="output")
qc = QuantumCircuit(walker_r, coin_r, classic_r)
return qc, walker_r, coin_r, classic_r
qc, _, _, _ = graph_walk_circuit(n)
qc.draw(output="mpl", initial_state=True)
n = 2 # Dimension of the hypercube
def grover_coin(coin_r: QuantumRegister) -> Operator:
matrix_size = 2 ** len(coin_r)
grover_matrix = np.full((matrix_size, matrix_size), 2 / matrix_size) - np.eye(
matrix_size
)
return Operator(grover_matrix)
coin_r = QuantumRegister(n, name="c")
qc = QuantumCircuit(coin_r)
gc = grover_coin(coin_r)
qc.unitary(gc, coin_r[:], label="Grover Coin")
qc.draw(output="mpl", initial_state=True)
n = 2 # Dimension of the hypercube
def shift_operator(
walker_r: QuantumRegister, coin_r: QuantumRegister
) -> QuantumCircuit:
"""Create a quantum circuit for the shift operator.
Args:
walker_r: the quantum register containing the walker's position qubits
coin_r: the quantum register containing the coin qubit
Returns:
quantum circuit for the shift operator
"""
qc = QuantumCircuit(walker_r, coin_r)
for i in reversed(range(len(walker_r))):
qc.mcx(coin_r, walker_r[i])
qc.x(coin_r[-1])
for j in range(1, len(coin_r)):
if i & ((1 << j) - 1) == 0:
qc.x(coin_r[-(j + 1)])
return qc
qc, walker_r, coin_r, _ = graph_walk_circuit(n)
qc = shift_operator(walker_r, coin_r)
qc.draw(output="mpl", initial_state=True)
n = 2 # Dimension of the hypercube
def graph_walk_step(
walker_r: QuantumRegister, coin_r: QuantumRegister
) -> QuantumCircuit:
"""Create a quantum circuit for one step of the graph walk.
Args:
walker_r: the quantum register containing the walker's position qubits
coin_r: the quantum register containing the coin qubit
Returns:
quantum circuit for one step of the graph walk
"""
shift = shift_operator(walker_r, coin_r)
gc = grover_coin(coin_r)
walk_step = QuantumCircuit(walker_r, coin_r)
walk_step.unitary(gc, coin_r, label="Grover Coin")
walk_step.compose(shift, inplace=True)
return walk_step
walk_step = graph_walk_step(walker_r, coin_r)
walk_step.draw(output="mpl", initial_state=True)
n = 2 # Dimension of the hypercube
n_steps = 3 # Number of steps of the quantum walk
def graph_walk(
n: int,
n_steps: int,
) -> QuantumCircuit:
"""Create a quantum circuit for the quantum walk over a graph.
Args:
n: dimension of the hypercube
n_steps: number of steps of the quantum walk
initial_position: initial position of the walker
initial_coin_value: initial value of the coin
Returns:
quantum circuit for the quantum walk over a graph
"""
qc, walker_r, coin_r, classic_r = graph_walk_circuit(n)
for i in range(n_steps):
step_gate = graph_walk_step(walker_r, coin_r).to_gate(label=f"Step #{i + 1}")
qc.append(step_gate, walker_r[:] + coin_r[:])
qc.barrier()
qc.measure(walker_r, reversed(classic_r))
return qc
qc = graph_walk(n, n_steps)
qc.draw(output="mpl", initial_state=True)
n = 2 # Dimension of the hypercube
n_steps = 30 # Number of steps of the quantum walk
n_runs = 5000 # Number of runs of the quantum circuit
qc = graph_walk(n, n_steps)
plot_results(qc, n_runs, "Quantum Walk on a Hypercube")
|
https://github.com/Raunak-Singh-Inventor/quantum_algorithms_in_qiskit
|
Raunak-Singh-Inventor
|
import numpy as np
def grovers_dist(num_qubits, marked_item, n_iterations):
dist = {}
for i in range(2**num_qubits):
key = bin(i)[2:].zfill(num_qubits)
theta = np.arcsin(1/np.sqrt(2 ** num_qubits))
if i == marked_item:
dist[key] = np.sin((2*n_iterations+1)*theta)**2
else:
dist[key] = (np.cos((2*n_iterations+1)*theta)/(np.sqrt(2 ** num_qubits - 1)))**2
return dist
num_qubits = 4
marked_item = 6
n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4)
grovers_dist(num_qubits, marked_item, n_iterations)
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
from qiskit_chemistry import QiskitChemistry
from qiskit import Aer
qiskit_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'}
}
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')
solver = QiskitChemistry()
%time result = solver.run(qiskit_chemistry_dict, backend=backend)
from qiskit_qcgpu_provider import QCGPUProvider
backend = QCGPUProvider().get_backend('statevector_simulator')
solver = QiskitChemistry()
%time result = solver.run(qiskit_chemistry_dict, backend=backend)
for line in result['printable']:
print(line)
|
https://github.com/quantumjim/qreative
|
quantumjim
|
import sys
sys.path.append('../')
import CreativeQiskit
from qiskit import IBMQ
IBMQ.load_accounts()
L = CreativeQiskit.layout('ibmq_16_melbourne')
L.num
L.pairs
L.pos
L.plot()
colors = {}
labels = {}
sizes = {}
import random
for node in L.pos:
colors[node] = (random.random(),random.random(),random.random())
labels[node] = random.choice([';',':','8']) + random.choice([')','(','D'])
sizes[node] = 1000+2000*(random.random())
L.plot(colors=colors,labels=labels,sizes=sizes)
stats = CreativeQiskit.bitstring_superposer(['1100011001111100','0110010101011001'])
print(stats)
probs = L.calculate_probs(stats)
print(probs)
L.plot(probs=probs)
L.plot(probs=probs,colors={0:(0.5,0.5,0.5)})
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, execute, Aer
import numpy as np
qr = QuantumRegister(16)
cr = ClassicalRegister(16)
qc = QuantumCircuit(qr, cr)
correct_pairs = ['A','P','D','N','H','I']
for pair in correct_pairs:
qc.rx(random.random()*np.pi,qr[L.pairs[pair][0]])
qc.cx(qr[L.pairs[pair][0]],qr[L.pairs[pair][1]])
qc.measure(qr,cr)
device = 'qasm_simulator'
backend = CreativeQiskit.get_backend(device)
noisy = True
noise_model = CreativeQiskit.get_noise(noisy)
try:
job = execute(qc,backend,noise_model=noise_model)
except:
job = execute(qc,backend)
stats = job.result().get_counts()
probs = L.calculate_probs(stats)
pair_labels = {}
for node in L.pos:
if type(node)==str:
pair_labels[node] = node
chosen_pairs = []
colors = {}
while len(chosen_pairs)<6:
L.plot(probs=probs,labels=pair_labels,colors=colors)
pair = str.upper(input(" > Type the name of a pair of qubits whose numbers are the same (or very similar)...\n"))
chosen_pairs.append( pair )
colors[pair] = (0.5,0.5,0.5)
for j in range(2):
colors[L.pairs[pair][j]] = (0.5,0.5,0.5)
L.plot(probs=probs,labels=pair_labels,colors=colors)
if set(chosen_pairs)==set(correct_pairs):
print("\n **You got all the correct pairs! :) **\n")
else:
print("\n **You didn't get all the correct pairs! :( **\n")
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
from qiskit import BasicAer
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle
from qiskit.tools.visualization import plot_histogram
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 Part Combinations', bar_labels=True)
|
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/trevorpiltch/Grovers-Algorithm
|
trevorpiltch
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
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 qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
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)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/coder-bean/kisskitqiskit
|
coder-bean
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
import numpy as np
#prepares the initial quantum states for the BB84 protocol by generating a list of quantum states and their associated bases.
def prepare_bb84_states(num_qubits):
states = []
bases = []
for _ in range(num_qubits):
state, basis = generate_bb84_state()
states.append(state)
bases.append(basis)
return states, bases
#generates a single BB84 quantum state and its associated measurement basis.
def generate_bb84_state():
basis = np.random.randint(2) # 0 for rectilinear basis, 1 for diagonal basis
if np.random.rand() < 0.5:
state = QuantumCircuit(1, 1)
if basis == 0:
state.h(0)
else:
state.s(0)
state.h(0)
else:
state = QuantumCircuit(1, 1)
if basis == 0:
state.x(0)
state.h(0)
else:
state.x(0)
state.s(0)
state.h(0)
return state, basis
#measures the quantum states with the appropriate basis and returns the measurement results
def measure_bb84_states(states, bases):
measurements = []
for state, basis in zip(states, bases):
if basis == 0:
state.measure(0, 0)
else:
state.h(0)
state.measure(0, 0)
measurements.append(state)
return measurements
#sifts the keys by comparing Alice and Bob's measurement bases and bits. It checks if the measurement bases match (the same basis) and appends the corresponding bits to the sifted keys
def sift_keys(alice_bases, bob_bases, alice_bits, bob_bits):
sifted_alice_bits = []
sifted_bob_bits = []
for a_basis, b_basis, a_bit, b_bit in zip(alice_bases, bob_bases, alice_bits, bob_bits):
if a_basis == b_basis:
sifted_alice_bits.append(a_bit)
sifted_bob_bits.append(b_bit)
return sifted_alice_bits, sifted_bob_bits
#calculates the error rate between Alice's and Bob's sifted bits
def error_rate(alice_bits, bob_bits):
errors = sum([1 for a, b in zip(alice_bits, bob_bits) if a != b])
return errors / len(alice_bits)
# simulates the BB84 protocol
num_qubits = 100
num_qubits = 100
alice_states, alice_bases = prepare_bb84_states(num_qubits)
bob_bases = np.random.randint(2, size=num_qubits)
bob_measurements = measure_bb84_states(alice_states, bob_bases)
alice_bits = []
for state in alice_states:
result = execute(state, Aer.get_backend('qasm_simulator')).result()
counts = result.get_counts(state)
max_count = max(counts, key=counts.get)
alice_bits.append(int(max_count))
bob_bits = []
for state in bob_measurements:
result = execute(state, Aer.get_backend('qasm_simulator')).result()
counts = result.get_counts(state)
max_count = max(counts, key=counts.get)
bob_bits.append(int(max_count))
sifted_alice_bits, sifted_bob_bits = sift_keys(alice_bases, bob_bases, alice_bits, bob_bits)
error = error_rate(sifted_alice_bits, sifted_bob_bits)
final_key = privacy_amplification(sifted_alice_bits)
print("Sifted key length:", len(sifted_alice_bits))
print("Error rate:", error)
print("Final secret key:", final_key)
|
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
|
PacktPublishing
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020, Updated March 2022
@author: hassi
"""
print("Ch 8: Qubit properties")
print("----------------------")
from qiskit import IBMQ
print("Getting providers...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
def select_backend():
# Get all available and operational backends.
print("Getting backends...")
available_backends = provider.backends(filters=lambda b: not b.configuration().simulator and b.configuration().num_qubits > 0 and b.status().operational)
# Fish out criteria to compare
print("{0:20} {1:<10}".format("Name","#Qubits"))
print("{0:20} {1:<10}".format("----","-------"))
for n in range(0, len(available_backends)):
backend = provider.get_backend(str(available_backends[n]))
print("{0:20} {1:<10}".format(backend.name(),backend.configuration().num_qubits))
select_backend=input("Select a backend ('exit' to end): ")
if select_backend!="exit":
backend = provider.get_backend(select_backend)
else:
backend=select_backend
return(backend)
def display_information(backend):
basis_gates=backend.configuration().basis_gates
num_qubits=backend.configuration().num_qubits
if num_qubits>1:
coupling_map=backend.configuration().coupling_map
else:
coupling_map=[]
micro=10**6
for qubit in range(num_qubits):
print("\nQubit:",qubit)
print("T1:",int(backend.properties().t1(qubit)*micro),"\u03BCs")
print("T2:",int(backend.properties().t2(qubit)*micro),"\u03BCs")
print("Readout error:",round(backend.properties().readout_error(qubit)*100,2),"%")
for bg in basis_gates:
if bg!="cx" and bg!="reset":
if backend.properties().gate_length(bg,[qubit])!=0:
print(bg,round(backend.properties().gate_length(bg,[0])*micro,2),"\u03BCs", "Err:",round(backend.properties().gate_error(bg,[qubit])*100,2),"%")
else:
print(bg,round(backend.properties().gate_length(bg,[0])*micro,2),"\u03BCs", "Err:",round(backend.properties().gate_error(bg,[qubit])*100,2),"%")
if num_qubits>0:
for cm in coupling_map:
if qubit in cm:
print("cx",cm,round(backend.properties().gate_length("cx",cm)*micro,2),"\u03BCs", "Err:",round(backend.properties().gate_error("cx",cm)*100,2),"%")
# Main
def main():
backend=select_backend()
display_information(backend)
if __name__ == '__main__':
main()
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
# from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2*dt,0)
qc.rz(2*dt,1)
qc.h(1)
qc.cx(1,0)
qc.rz(-2*dt, 0)
qc.rx(-2*dt, 1)
qc.rz(2*dt, 1)
qc.cx(1,0)
qc.h(1)
qc.rz(2*dt, 0)
return qc.to_instruction() if to_instruction else qc
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
Trot_gate = trotter_gate(dt)
# Number of trotter steps
trotter_steps = 15 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, [qr[3], qr[5]])
qc.cx(qr[3], qr[1])
qc.cx(qr[5], qr[3])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time/trotter_steps})
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw("mpl") # only view trotter gates
st_qcs[13].draw("mpl")
# Pauli Twirling
# TODO: 一度挙動を調べる
def pauli_twirling(circ: str) -> QuantumCircuit:
"""
そのまま使う: 修正は後回し
"""
#! qasm ベタ書き
def apply_pauli(num: int, qb: int) -> str:
if (num == 0):
return f'id q[{qb}];\n'
elif (num == 1):
return f'x q[{qb}];\n'
elif (num == 2):
return f'y q[{qb}];\n'
else:
return f'z q[{qb}];\n'
paulis = [(i,j) for i in range(0,4) for j in range(0,4)]
paulis.remove((0,0))
paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)]
new_circ = ''
ops = circ.qasm().splitlines(True) #! 生のqasmコードを持ってきてる: オペレータに分解
for op in ops:
if (op[:2] == 'cx'): # can add for cz, etc.
num = random.randrange(len(paulis)) #! permute paulis
qbs = re.findall('q\[(.)\]', op)
new_circ += apply_pauli(paulis[num][0], qbs[0])
new_circ += apply_pauli(paulis[num][1], qbs[1])
new_circ += op
new_circ += apply_pauli(paulis_map[num][0], qbs[0])
new_circ += apply_pauli(paulis_map[num][1], qbs[1])
else:
new_circ += op
return qiskit.circuit.QuantumCircuit.from_qasm_str(new_circ)
# ZNE
# 3種類の実行方法
# 1. state tomography回路全体をzne
# 2. state tomography前の回路をzne
# 3. 2-qubitの状態だけzne
# 今回は1を実装する
def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0]):
"""
"""
folded_qcs = [] #! ZNE用の回路
for qc in qcs:
folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用
folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化
folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] #! 後からPauli Twirlingを施す!
return folded_qcs
# subspace expansion
# TODO: 実装はとりあえず後回し
def se_wrapper(qcs):
"""
"""
folded_qcs = []
for qc in qcs:
pass
return folded_qcs
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# backend = provider.get_backend("ibmq_jakarta")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3)
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
def make_basis3():
n = 3
basis = []
for q0 in range(4):
for q1 in range(4):
for q2 in range(4):
basis.append([q0, q1, q2])
return basis
def make_basis(n):
basis = np.zeros((1 << n, n), dtype="int")
for i in range(4):
for j in range(4):
for k in range(4):
for in range(4):
return basis
def make_state_tomography_circuits(qc, basis):
basis = make_basis3()
st_qcs = []
for v in basis:
mqc = QuantumCircuit(3)
for i in v:
if i == 0:
continue
elif i == 1:
mqc.measure()
elif i == 2:
ret = np.kron(ret, Y)
elif i == 3:
ret = np.kron(ret, Z)
else:
raise Exception
st_qcs.append(qc.compose(mqc, [0,1,2]))
def measurement_basis(v):
I = np.array([[1,0],[0,1]], dtype="complex")
X = np.array([[0,1],[1,0]], dtype="complex")
Y = np.array([[0,-1j],[1j,0]], dtype="complex")
Z = np.array([[1,0],[0,-1]], dtype="complex")
ret = I
for i in v:
if i == 0:
ret = np.kron(ret, I)
elif i == 1:
ret = np.kron(ret, X)
elif i == 2:
ret = np.kron(ret, Y)
elif i == 3:
ret = np.kron(ret, Z)
else:
raise Exception
return ret
def state_tomography(n, expvals, vs):
rho = np.zeros((1 << n, 1 << n), dtype="complex")
for i, v in enumerate(vs):
rho += expvals[i] * measurement_basis(v)
return rho / (1 << n)
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(expvals, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
stf = StateTomographyFitter(job.result(), st_qcs)
stf._data
from IPython.core.debugger import Pdb; Pdb().set_trace()
data, basis_matrix, weights = stf._fitter_data(True, 0.5)
next(iter(stf._data))
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
fids = []
for job in jobs:
fid = state_tomo(job.result(), st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/jakelishman/qiskit-qasm2
|
jakelishman
|
import qiskit_qasm2
project = 'Qiskit OpenQASM 2 Tools'
copyright = '2022, Jake Lishman'
author = 'Jake Lishman'
version = qiskit_qasm2.__version__
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
]
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# Document the docstring for the class and the __init__ method together.
autoclass_content = "both"
html_theme = 'alabaster'
intersphinx_mapping = {
"qiskit-terra": ("https://qiskit.org/documentation", None),
}
|
https://github.com/Hayatto9217/Qiskit15
|
Hayatto9217
|
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
import random
circ = QuantumCircuit(40, 40)
circ.h(range(40))
qubit_indices = [i for i in range(40)]
for i in range(10):
control, target, t = random.sample(qubit_indices, 3)
circ.cx(control, target)
circ.t(t)
circ.measure(range(40), range(40))
# Create statevector method simulator
statevector_simulator = AerSimulator(method='statevector')
# Transpile circuit for backend
tcirc = transpile(circ, statevector_simulator)
# Try and run circuit
statevector_result = statevector_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(statevector_result.success))
print('Why not? {}'.format(statevector_result.status))
extended_stabilizer_simulator =AerSimulator(method='extended_stabilizer')
tcirc = transpile(circ, extended_stabilizer_simulator)
extended_stabilizier_result = extended_stabilizer_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(extended_stabilizier_result.success))
#Extended Stabilizerメソッドは2つの部分から構成
small_circ = QuantumCircuit(2,2)
small_circ.h(0)
small_circ.cx(0, 1)
small_circ.t(0)
small_circ.measure([0,1],[0,1])
expected_results={'00':50, '11':50}
tsmall_circ =transpile(small_circ,extended_stabilizer_simulator)
result = extended_stabilizer_simulator.run(
tsmall_circ, shots=100).result()
counts =result.get_counts(0)
print('100 shots in {}s'.format(result.time_taken))
plot_histogram([expected_results, counts],
legend=['Expected', 'Extended Stabilizer'])
# Add runtime options for extended stabilizer simulator
opts = {'extended_stabilizer_approximation_error': 0.03}
reduced_error = extended_stabilizer_simulator.run(
tsmall_circ, shots=100, **opts).result()
reduced_error_counts = reduced_error.get_counts(0)
print('100 shots in {}s'.format(reduced_error.time_taken))
plot_histogram([expected_results, reduced_error_counts],
legend=['Expected', 'Extended Stabilizer'])
print("The curcuit above, with 100 shots at precision 0.03 "
"and default mixing time, needed {}s".format(int(reduced_error.time_taken)))
opts = {
'extended_stabilizer_approximation_error': 0.03,
'extended_stabilizer_mixing_time':100
}
optimized = extended_stabilizer_simulator.run(
tsmall_circ, shots=100, **opts).result()
print('Dialing down the mixing time, we completed in just {}s'.format(optimized.time_taken))
opts = {'extended_stabilizer_mixing_time': 150}
multishot = extended_stabilizer_simulator.run(
tcirc, shots=150, **opts).result()
print("100 shots took {} s".format(multishot.time_taken))
opts = {
'extended_stabilizer_measure_sampling': True,
'extended_stabilizer_mixing_time': 150
}
measure_sampling = extended_stabilizer_simulator.run(
circ, shots=150, **opts).result()
print("With the optimization, 100 shots took {} s".format(result.time_taken))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import itertools
import qiskit
from qiskit import QuantumRegister, QuantumCircuit
from qiskit import Aer
import qiskit.ignis.verification.tomography as tomo
from qiskit.quantum_info import state_fidelity
I = np.array([[1,0],[0,1]])
X = np.array([[0,1],[1,0]])
Y = np.array([[0,-1j],[1j,0]])
Z = np.array([[1,0],[0,-1]])
def HS_product(A,B):
return 0.5*np.trace(np.conj(B).T @ A)
PX0 = 0.5*np.array([[1, 1], [1, 1]])
PX1 = 0.5*np.array([[1, -1], [-1, 1]])
PY0 = 0.5*np.array([[1, -1j], [1j, 1]])
PY1 = 0.5*np.array([[1, 1j], [-1j, 1]])
PZ0 = np.array([[1, 0], [0, 0]])
PZ1 = np.array([[0, 0], [0, 1]])
projectors = [PX0, PX1, PY0, PY1, PZ0, PZ1]
M = np.array([p.flatten() for p in projectors])
M
M_dg = np.conj(M).T
linear_inversion_matrix = np.linalg.inv(M_dg @ M) @ M_dg
projectors_2 = [np.kron(p1, p2) for (p1, p2) in itertools.product(projectors, repeat = 2)]
M_2 = np.array([p.flatten() for p in projectors_2])
M_dg_2 = np.conj(M_2).T
linear_inversion_matrix_2 = np.linalg.inv(M_dg_2 @ M_2) @ M_dg_2
q2 = QuantumRegister(2)
bell = QuantumCircuit(q2)
bell.h(q2[0])
bell.cx(q2[0], q2[1])
bell.qasm()
qst_bell = tomo.state_tomography_circuits(bell, q2)
job = qiskit.execute(qst_bell, Aer.get_backend('qasm_simulator'), shots=5000)
statefit = tomo.StateTomographyFitter(job.result(), qst_bell)
statefit.data
p, M, weights = statefit._fitter_data(True, 0.5)
M_dg = np.conj(M).T
linear_inversion_matrix = np.linalg.inv(M_dg @ M) @ M_dg
rho_bell = linear_inversion_matrix @ p
rho_bell = np.reshape(rho_bell, (4, 4))
print(rho_bell)
job = qiskit.execute(bell, Aer.get_backend('statevector_simulator'))
psi_bell = job.result().get_statevector(bell)
F_bell = state_fidelity(psi_bell, rho_bell)
print('Fit Fidelity linear inversion =', F_bell)
rho_cvx_bell = statefit.fit(method='cvx')
F_bell = state_fidelity(psi_bell, rho_cvx_bell)
print('Fit Fidelity CVX fit =', F_bell)
rho_mle_bell = statefit.fit(method='lstsq')
F_bell = state_fidelity(psi_bell, rho_mle_bell)
print('Fit Fidelity MLE fit =', F_bell)
|
https://github.com/arian-code/nptel_quantum_assignments
|
arian-code
|
from sympy import *
from sympy.physics.quantum.state import Ket, Bra
from sympy.physics.quantum import TensorProduct
import numpy as np
init_printing(use_unicode=True)
#One Q bit gates
H=Matrix([[1/sqrt(2), 1/sqrt(2)],[1/sqrt(2), -1/sqrt(2)]])
S=Matrix([[0, 1],[1, I]])
X=Matrix([[0, 1],[1, 0]])
Y=Matrix([[0, -I],[I, 0]])
Z=Matrix([[1, 0],[0, -1]])
Identity=Matrix([[1, 0],[0, 1]])
H, S, X, Y, Z, Identity
#Two Q bit gates
CNOT=Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
CNOT
HI=TensorProduct(H, Identity) #Example only
CNOT, HI
#option A
lhs=CNOT*TensorProduct(Y, Identity)*CNOT
rhs=TensorProduct(Y, Y)
print (lhs)
print (rhs)
if (lhs==rhs):
print ("It is true")
else:
print ("It is false")
#option B
lhs=CNOT*TensorProduct(Y, Identity)*CNOT
rhs=TensorProduct(Y, X)
print (lhs)
print (rhs)
if (lhs==rhs):
print ("It is true")
else:
print ("It is false")
#option C
lhs=CNOT*TensorProduct(Identity, Y)*CNOT
rhs=TensorProduct(Y, Y)
print (lhs)
print (rhs)
if (lhs==rhs):
print ("It is true")
else:
print ("It is false")
#option D
lhs=CNOT*TensorProduct(Identity, Y)*CNOT
rhs=TensorProduct(Z, Y)
print (lhs)
print (rhs)
if (lhs==rhs):
print ("It is true")
else:
print ("It is false")
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
from qiskit.primitives import BackendEstimator
from qiskit.providers.fake_provider import FakeNairobi # We need noise!
from zne import zne
ZNEEstimator = zne(BackendEstimator) # Any implementation of BaseEstimator is valid
backend = FakeNairobi()
estimator = ZNEEstimator(backend=backend)
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
circuit = random_circuit(2, 4, seed=1).decompose(reps=1)
observable = SparsePauliOp("ZZ")
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.primitives import Estimator
circuit = random_circuit(2, 4, seed=1).decompose(reps=1)
observable = SparsePauliOp("ZZ")
job = Estimator().run(circuit, observable) # !!!
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from zne import ZNEStrategy
circuit = random_circuit(2, 4, seed=1).decompose(reps=1)
observable = SparsePauliOp("ZZ")
zne_strategy = ZNEStrategy(noise_factors=[1, 3, 5])
job = estimator.run(circuit, observable, zne_strategy=zne_strategy) # !!!
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from zne.utils.serialization import EstimatorResultEncoder
print(EstimatorResultEncoder.dumps(result, indent=2))
from zne.noise_amplification import LocalFoldingAmplifier, GlobalFoldingAmplifier
global_amplifier = GlobalFoldingAmplifier()
local_amplifier = LocalFoldingAmplifier(gates_to_fold=2) # Fold two-qubit gates
zne_strategy = ZNEStrategy(
noise_factors=range(1, 9),
noise_amplifier=local_amplifier,
)
from zne.extrapolation import PolynomialExtrapolator
extrapolator = PolynomialExtrapolator(degree=2)
zne_strategy = ZNEStrategy(
noise_factors=[1.0, 1.5, 2.0],
extrapolator=extrapolator
)
from zne.extrapolation import Extrapolator, ReckoningResult
from zne.noise_amplification import NoiseAmplifier
############################ NOISE AMPLIFIER ############################
class CustomAmplifier(NoiseAmplifier):
def amplify_circuit_noise(self, circuit, noise_factor):
return circuit.copy() # Dummy, nonperforming
def amplify_dag_noise(self, dag, noise_factor):
return super().amplify_dag_noise(dag, noise_factor)
############################ EXTRAPOLATOR ############################
class CustomExtrapolator(Extrapolator):
@property
def min_points(self):
return 2
def _extrapolate_zero(self, x_data, y_data, sigma_x, sigma_y):
value = 1.0
std_error = 1.0
metadata = {"meta": "data"}
return ReckoningResult(value, std_error, metadata) # Dummy, nonperforming
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
observable = SparsePauliOp("ZZ")
zne_strategy = ZNEStrategy(
noise_factors=(1, 3),
noise_amplifier=CustomAmplifier(),
extrapolator=CustomExtrapolator(),
)
job = estimator.run(circuit, observable, zne_strategy=zne_strategy)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.circuit.random import random_circuit
from qiskit.primitives import BackendEstimator
from qiskit.providers.fake_provider import FakeNairobi
from qiskit.quantum_info import SparsePauliOp
from zne import zne, ZNEStrategy
from zne.noise_amplification import LocalFoldingAmplifier
from zne.extrapolation import PolynomialExtrapolator
## Build ZNEEstimator
ZNEEstimator = zne(BackendEstimator)
backend = FakeNairobi()
estimator = ZNEEstimator(backend=backend)
## Build our input circuit and observable
circuit = random_circuit(2, 4, seed=1).decompose(reps=1)
observable = SparsePauliOp("ZZ")
## Build a ZNE strategy
zne_strategy = ZNEStrategy(
noise_factors=range(1, 9),
noise_amplifier=LocalFoldingAmplifier(gates_to_fold=2),
extrapolator=PolynomialExtrapolator(degree=2),
)
## Run experiment
job = estimator.run(circuit, observable, zne_strategy=zne_strategy) # !!!
result = job.result()
## Display results
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams["figure.dpi"] = 300
plt.rcParams.update({"text.usetex": True, "font.family": "Computer Modern Roman"})
############################ DATA ############################
exact = 1 # From simulation above
mitigated = result.values[0]
noise_factors = result.metadata[0]["zne"]["noise_amplification"]["noise_factors"]
noisy_values = result.metadata[0]["zne"]["noise_amplification"]["values"]
############################ PLOT ############################
plt.rcParams["figure.figsize"] = (5,3.5)
plt.grid(which='major',axis='both')
plt.plot([0, noise_factors[-1]], [exact, exact], "--", label=f"Exact", color="#000000")
plt.scatter(0, mitigated, label=f"Mitigated", marker="x", color="#785ef0")
if noise_factors[0] == 1:
plt.scatter(
noise_factors[0], noisy_values[0],
label=f"Unmitigated", marker="s", color="#dc267f",
)
plt.plot(
noise_factors, noisy_values,
label=f"Amplified", marker="o", color="#dc267f",
)
plt.title("Zero noise extrapolation")
plt.xlabel("Noise Factor ($n$)")
plt.ylabel(f"Expectation Value ($\langle ZZ \\rangle$)")
plt.legend()
plt.show()
import qiskit.tools.jupyter # pylint: disable=unused-import,wrong-import-order
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Kraus 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 import Kraus
from .channel_test_case import ChannelTestCase
class TestKraus(ChannelTestCase):
"""Tests for Kraus channel representation."""
def test_init(self):
"""Test initialization"""
# Initialize from unitary
chan = Kraus(self.UI)
assert_allclose(chan.data, [self.UI])
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Kraus
chan = Kraus(self.depol_kraus(0.5))
assert_allclose(chan.data, self.depol_kraus(0.5))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Non-CPTP
kraus_l, kraus_r = [self.UI, self.UX], [self.UY, self.UZ]
chan = Kraus((kraus_l, kraus_r))
assert_allclose(chan.data, (kraus_l, kraus_r))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize with redundant second op
chan = Kraus((kraus_l, kraus_l))
assert_allclose(chan.data, kraus_l)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from rectangular
kraus = [np.zeros((4, 2))]
chan = Kraus(kraus)
assert_allclose(chan.data, kraus)
self.assertEqual(chan.dim, (2, 4))
self.assertIsNone(chan.num_qubits)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Kraus, kraus, input_dims=4, output_dims=4)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Kraus(circuit)
target = Kraus(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, Kraus, circuit)
def test_equal(self):
"""Test __eq__ method"""
kraus = [self.rand_matrix(2, 2) for _ in range(2)]
self.assertEqual(Kraus(kraus), Kraus(kraus))
def test_copy(self):
"""Test copy method"""
mat = np.eye(2)
with self.subTest("Deep copy"):
orig = Kraus(mat)
cpy = orig.copy()
cpy._data[0][0][0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Kraus(mat)
clone = copy.copy(orig)
clone._data[0][0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = Kraus(mat)
clone = copy.copy(orig)
clone._data[0][0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Kraus(self.depol_kraus(0.5)).is_cptp())
self.assertTrue(Kraus(self.UX).is_cptp())
# Non-CPTP should return false
self.assertFalse(Kraus(([self.UI], [self.UX])).is_cptp())
self.assertFalse(Kraus([self.UI, self.UX]).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Single Kraus list
targ = Kraus([np.conjugate(k) for k in kraus_l])
chan1 = Kraus(kraus_l)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
# Double Kraus list
targ = Kraus(([np.conjugate(k) for k in kraus_l], [np.conjugate(k) for k in kraus_r]))
chan1 = Kraus((kraus_l, kraus_r))
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
def test_transpose(self):
"""Test transpose method."""
kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Single Kraus list
targ = Kraus([np.transpose(k) for k in kraus_l])
chan1 = Kraus(kraus_l)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double Kraus list
targ = Kraus(([np.transpose(k) for k in kraus_l], [np.transpose(k) for k in kraus_r]))
chan1 = Kraus((kraus_l, kraus_r))
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_adjoint(self):
"""Test adjoint method."""
kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Single Kraus list
targ = Kraus([np.transpose(k).conj() for k in kraus_l])
chan1 = Kraus(kraus_l)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double Kraus list
targ = Kraus(
([np.transpose(k).conj() for k in kraus_l], [np.transpose(k).conj() for k in kraus_r])
)
chan1 = Kraus((kraus_l, kraus_r))
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Kraus(np.eye(2)).compose, Kraus(np.eye(4)))
self.assertRaises(QiskitError, Kraus(np.eye(2)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Kraus(self.UX)
chan2 = Kraus(self.UY)
chan = chan1.compose(chan2)
targ = rho & Kraus(self.UZ)
self.assertEqual(rho & chan, targ)
# 50% depolarizing channel
chan1 = Kraus(self.depol_kraus(0.5))
chan = chan1.compose(chan1)
targ = rho & Kraus(self.depol_kraus(0.75))
self.assertEqual(rho & chan, targ)
# Compose different dimensions
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4)
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = rho & chan1 & chan2
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho & chan, targ)
chan = chan1 & chan2
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho & chan, targ)
def test_dot(self):
"""Test dot method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Kraus(self.UX)
chan2 = Kraus(self.UY)
targ = rho.evolve(Kraus(self.UZ))
self.assertEqual(rho.evolve(chan1.dot(chan2)), targ)
self.assertEqual(rho.evolve(chan1 @ chan2), targ)
# 50% depolarizing channel
chan1 = Kraus(self.depol_kraus(0.5))
targ = rho & Kraus(self.depol_kraus(0.75))
self.assertEqual(rho.evolve(chan1.dot(chan1)), targ)
self.assertEqual(rho.evolve(chan1 @ chan1), targ)
# Compose different dimensions
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4)
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = rho & chan1 & chan2
self.assertEqual(rho.evolve(chan2.dot(chan1)), targ)
self.assertEqual(rho.evolve(chan2 @ chan1), targ)
def test_compose_front(self):
"""Test deprecated front compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Kraus(self.UX)
chan2 = Kraus(self.UY)
chan = chan1.compose(chan2, front=True)
targ = rho & Kraus(self.UZ)
self.assertEqual(rho & chan, targ)
# 50% depolarizing channel
chan1 = Kraus(self.depol_kraus(0.5))
chan = chan1.compose(chan1, front=True)
targ = rho & Kraus(self.depol_kraus(0.75))
self.assertEqual(rho & chan, targ)
# Compose different dimensions
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4)
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = rho & chan1 & chan2
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho & chan, 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 = Kraus(self.UI)
chan2 = Kraus(self.UX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init & 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 & chan, rho_targ)
# Completely depolarizing
chan_dep = Kraus(self.depol_kraus(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 & 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 = Kraus(self.UI)
chan2 = Kraus(self.UX)
# X \otimes I
chan = chan2.tensor(chan1)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init & 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 & chan, rho_targ)
# Completely depolarizing
chan_dep = Kraus(self.depol_kraus(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 & chan, rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
rho = DensityMatrix(np.diag([1, 0]))
p_id = 0.9
chan = Kraus(self.depol_kraus(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = chan.power(3)
targ3a = rho & chan & chan & chan
self.assertEqual(rho & chan3, targ3a)
targ3b = rho & Kraus(self.depol_kraus(1 - p_id3))
self.assertEqual(rho & chan3, targ3b)
def test_add(self):
"""Test add method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Random Single-Kraus maps
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = (rho & chan1) + (rho & chan2)
chan = chan1._add(chan2)
self.assertEqual(rho & chan, targ)
chan = chan1 + chan2
self.assertEqual(rho & chan, targ)
# Random Single-Kraus maps
chan = Kraus((kraus1, kraus2))
targ = 2 * (rho & chan)
chan = chan._add(chan)
self.assertEqual(rho & chan, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
kraus = self.rand_kraus(8, 8, 4)
kraus0 = self.rand_kraus(2, 2, 4)
op = Kraus(kraus)
op0 = Kraus(kraus0)
eye = Kraus(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_sub_qargs(self):
"""Test sub method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
kraus = self.rand_kraus(8, 8, 4)
kraus0 = self.rand_kraus(2, 2, 4)
op = Kraus(kraus)
op0 = Kraus(kraus0)
eye = Kraus(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_subtract(self):
"""Test subtract method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Random Single-Kraus maps
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = (rho & chan1) - (rho & chan2)
chan = chan1 - chan2
self.assertEqual(rho & chan, targ)
# Random Single-Kraus maps
chan = Kraus((kraus1, kraus2))
targ = 0 * (rho & chan)
chan = chan - chan
self.assertEqual(rho & chan, targ)
def test_multiply(self):
"""Test multiply method."""
# Random initial state and Kraus ops
rho = DensityMatrix(self.rand_rho(2))
val = 0.5
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Single Kraus set
chan1 = Kraus(kraus1)
targ = val * (rho & chan1)
chan = chan1._multiply(val)
self.assertEqual(rho & chan, targ)
chan = val * chan1
self.assertEqual(rho & chan, targ)
targ = (rho & chan1) * val
chan = chan1 * val
self.assertEqual(rho & chan, targ)
# Double Kraus set
chan2 = Kraus((kraus1, kraus2))
targ = val * (rho & chan2)
chan = chan2._multiply(val)
self.assertEqual(rho & chan, targ)
chan = val * chan2
self.assertEqual(rho & chan, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Kraus(self.depol_kraus(1))
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"""
rho = DensityMatrix(np.diag([1, 0]))
targ = DensityMatrix(np.diag([-0.5, -0.5]))
chan = -Kraus(self.depol_kraus(1))
self.assertEqual(rho & chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Unit-testing permutation_ai"""
import pytest
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_transpiler_service.ai.collection import CollectPermutations
from qiskit_transpiler_service.ai.synthesis import AIPermutationSynthesis
@pytest.fixture
def permutations_circuit(backend, cmap_backend):
coupling_map = cmap_backend[backend]
cmap = list(coupling_map.get_edges())
orig_qc = QuantumCircuit(27)
for i, j in cmap:
orig_qc.h(i)
orig_qc.cx(i, j)
for i, j in cmap:
orig_qc.swap(i, j)
for i, j in cmap:
orig_qc.h(i)
orig_qc.cx(i, j)
for i, j in cmap[:4]:
orig_qc.swap(i, j)
for i, j in cmap:
orig_qc.cx(i, j)
return orig_qc
def test_permutation_collector(permutations_circuit, backend, cmap_backend):
qiskit_lvl3_transpiler = generate_preset_pass_manager(
optimization_level=1, coupling_map=cmap_backend[backend]
)
permutations_circuit = qiskit_lvl3_transpiler.run(permutations_circuit)
pm = PassManager(
[
CollectPermutations(max_block_size=27),
]
)
perm_only_circ = pm.run(permutations_circuit)
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(perm_only_circ)
perm_nodes = dag.named_nodes("permutation", "Permutation")
assert len(perm_nodes) == 2
assert perm_nodes[0].op.num_qubits == 27
assert perm_nodes[1].op.num_qubits == 4
assert not dag.named_nodes("linear_function", "Linear_function")
assert not dag.named_nodes("clifford", "Clifford")
def test_permutation_pass(permutations_circuit, backend, cmap_backend, caplog):
qiskit_lvl3_transpiler = generate_preset_pass_manager(
optimization_level=1, coupling_map=cmap_backend[backend]
)
permutations_circuit = qiskit_lvl3_transpiler.run(permutations_circuit)
ai_optimize_lf = PassManager(
[
CollectPermutations(max_block_size=27),
AIPermutationSynthesis(backend_name=backend),
]
)
ai_optimized_circuit = ai_optimize_lf.run(permutations_circuit)
assert "Using the synthesized circuit" in caplog.text
assert isinstance(ai_optimized_circuit, QuantumCircuit)
def test_permutation_wrong_backend(caplog):
orig_qc = QuantumCircuit(3)
orig_qc.swap(0, 1)
orig_qc.swap(1, 2)
ai_optimize_lf = PassManager(
[
CollectPermutations(min_block_size=2, max_block_size=27),
AIPermutationSynthesis(backend_name="a_wrong_backend"),
]
)
ai_optimized_circuit = ai_optimize_lf.run(orig_qc)
assert "couldn't synthesize the circuit" in caplog.text
assert "Keeping the original circuit" in caplog.text
assert isinstance(ai_optimized_circuit, QuantumCircuit)
|
https://github.com/ctuning/ck-qiskit
|
ctuning
|
# 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 teleportation example.
Note: if you have only cloned the Qiskit repository but not
used `pip install`, the examples only work from the root directory.
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import BasicAer
from qiskit import execute
###############################################################
# Set the backend name and coupling map.
###############################################################
coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]]
backend = BasicAer.get_backend("qasm_simulator")
###############################################################
# Make a quantum program for quantum teleportation.
###############################################################
q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2, name="teleport")
# Prepare an initial state
qc.u(0.3, 0.2, 0.1, q[0])
# Prepare a Bell pair
qc.h(q[1])
qc.cx(q[1], q[2])
# Barrier following state preparation
qc.barrier(q)
# Measure in the Bell basis
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[0], c0[0])
qc.measure(q[1], c1[0])
# Apply a correction
qc.barrier(q)
qc.z(q[2]).c_if(c0, 1)
qc.x(q[2]).c_if(c1, 1)
qc.measure(q[2], c2[0])
###############################################################
# Execute.
# Experiment does not support feedback, so we use the simulator
###############################################################
# First version: not mapped
initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2}
job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout)
result = job.result()
print(result.get_counts(qc))
# Second version: mapped to 2x8 array coupling graph
job = execute(
qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout
)
result = job.result()
print(result.get_counts(qc))
# Both versions should give the same distribution
|
https://github.com/xijia-tao/comp3316-a4-code
|
xijia-tao
|
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/LSEG-API-Samples/Article.EikonAPI.Python.OptionPricingUsingQiskitAndEikonDataAPI
|
LSEG-API-Samples
|
import warnings
warnings.filterwarnings("ignore")
import qiskit.tools.jupyter
%qiskit_version_table
import eikon as ek
print("Eikon version: ", ek.__version__)
import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import seaborn as sns
import qiskit
from qiskit import Aer, QuantumCircuit
from qiskit_finance.data_providers._base_data_provider import BaseDataProvider
from qiskit.finance.applications.ising import portfolio
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.aqua.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import COBYLA
from qiskit import IBMQ
IBMQ.save_account('MY_API_TOKEN', overwrite=True)
eikon_key = open("eikon.txt","r")
ek.set_app_key(str(eikon_key.read()))
eikon_key.close()
class EikonDataProvider(BaseDataProvider):
"""
The abstract base class for Eikon data_provider.
"""
def __init__(self, stocks_list, start_date, end_date):
'''
stocks -> List of interested assets
start -> start date to fetch historical data
end ->
'''
super().__init__()
self._stocks = stocks_list
self._start = start_date
self._end = end_date
self._data = []
self.stock_data = pd.DataFrame()
def run(self):
self._data = []
stocks_notfound = []
stock_data = ek.get_timeseries(self._stocks,
start_date=self._start,
end_date=self._end,
interval='daily',
corax='adjusted')
for ticker in self._stocks:
stock_value = stock_data['CLOSE']
self.stock_data[ticker] = stock_data['CLOSE']
if stock_value.dropna().empty:
stocks_notfound.append(ticker)
self._data.append(stock_value)
# List of stocks
stock_list = ['FB.O']
# Start Date
start_date = datetime.datetime(2020,12,1)
# End Date
end_date = datetime.datetime(2021,12,1)
# Set number of equities to the number of stocks
num_assets = len(stock_list)
# Set the risk factor
risk_factor = 0.7
# Set budget
budget = 2
# Scaling of budget penalty term will be dependant on the number of assets
penalty = num_assets
data = EikonDataProvider(stocks_list = stock_list, start_date=start_date, end_date=end_date)
data.run()
# Top 5 rows of data
df = data.stock_data
df.head()
df.describe()
# Closing Price History
fig, ax = plt.subplots(figsize=(15, 8))
ax.plot(df)
plt.title('Close Price History')
plt.xlabel('Date',fontsize =20)
plt.ylabel('Price in USD',fontsize = 20)
ax.legend(df.columns.values)
plt.show()
df.tail()
strike_price = 315 # agreed upon strike price
T = 40 / 253 # 40 days to maturity
S = 310.6 # initial spot price
# vol = 0.4 # volatility of 40%
vol = df['FB.O'].pct_change().std()
r = 0.05 # annual interest rate of 4%
# resulting parameters for log-normal distribution
mu = ((r - 0.5 * vol**2) * T + np.log(S))
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2/2)
variance = (np.exp(sigma**2) - 1) * np.exp(2*mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3*stddev)
high = mean + 3*stddev
low
high
import numpy as np
from qiskit.algorithms import AmplitudeEstimation
from qiskit_finance.circuit.library import EuropeanCallPricingObjective # F
from qiskit.circuit.library import LogNormalDistribution, NormalDistribution
from qiskit_finance.applications import EuropeanCallPricing
from qiskit_finance.applications.estimation import EuropeanCallDelta
from qiskit import Aer
from qiskit.algorithms import IterativeAmplitudeEstimation
provider = IBMQ.load_account()
provider.backends()
backend = provider.get_backend("ibmq_lima")
sim = QuantumInstance(backend=backend, shots=1000)
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 2
distribution = LogNormalDistribution(num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high))
european_call_pricing = EuropeanCallPricing(num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
rescaling_factor=0.25, # approximation constant for payoff function
bounds=(low, high),
uncertainty_model=distribution)
problem = european_call_pricing.to_estimation_problem()
problem.state_preparation.draw('mpl', style='iqx')
plt.show()
epsilon = 0.01 # determines final accuracy
alpha = 0.05 # determines how certain we are of the result
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=sim)
result = ae.estimate(problem)
conf_int_result = np.array(result.confidence_interval_processed)
print("Esimated value: \t%.4f" % european_call_pricing.interpret(result))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int_result))
x = distribution.values
y = distribution.probabilities
plt.figure(figsize=(6,4))
plt.bar(x, y, width=2)
plt.xticks(x, size=12, rotation=45)
plt.yticks(size=12)
plt.xlabel('Spot Price at Maturity $S_T$ (\$)', size=15)
plt.ylabel('Probability ($\%$)', size=15)
plt.show()
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = distribution.values
y = np.maximum(0, x - strike_price)
plt.figure(figsize=(6,4))
plt.plot(x, y, "ro-")
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=12, rotation=45)
plt.yticks(size=12)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(distribution.probabilities, y)
exact_delta = sum(distribution.probabilities[x >= strike_price])
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
european_call_delta = EuropeanCallDelta(
num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
bounds=(low, high),
uncertainty_model=distribution,
)
european_call_delta._objective.decompose().draw('mpl', style='iqx')
plt.show()
european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits)
european_call_delta_circ.append(distribution, range(num_uncertainty_qubits))
european_call_delta_circ.append(
european_call_delta._objective, range(european_call_delta._objective.num_qubits)
)
european_call_delta_circ.draw('mpl', style='iqx')
plt.show()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_delta.to_estimation_problem()
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=sim)
result_delta = ae_delta.estimate(problem)
conf_int = np.array(result_delta.confidence_interval_processed)
print("Exact delta: \t%.4f" % exact_delta)
print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
|
https://github.com/hugoecarl/TSP-Problem-Study
|
hugoecarl
|
import math
import matplotlib.pyplot as plt
%matplotlib inline
class TSP:
def __init__(self):
self.flat_mat = flat_mat
self.n = 0
self.melhor_dist = 1e11
self.pontos = []
self.melhores_pontos = []
def busca_exaustiva(self, flat_mat, n, ite):
if ite == n:
dist = 0
for j in range(1, n):
dist += flat_mat[self.pontos[j-1] * n + self.pontos[j]]
dist += flat_mat[self.pontos[n-1] * n + self.pontos[0]]
if dist < self.melhor_dist:
self.melhor_dist = dist
self.melhores_pontos = self.pontos[:]
return
for i in range(n):
if self.pontos[i] == -1:
self.pontos[i] = ite
self.busca_exaustiva(flat_mat, n, ite + 1)
self.pontos[i] = -1
def dist_mat(self):
x = []
y = []
flat_mat = [] #matriz 1 dimensao contendo todas as distancias possiveis entre os pontos para facilitar cálculo.
while True:
try:
temp = input("Digite a coordenada x y: ").split()
x.append(float(temp[0]))
y.append(float(temp[1]))
except:
break
for i in range(len(x)):
for j in range(len(y)):
flat_mat.append(math.sqrt((x[i] - x[j])**2 + (y[i] - y[j])**2))
return flat_mat, x, y
def get_results(self):
self.flat_mat, x, _ = self.dist_mat()
self.n = len(x)
self.pontos = [-1]*self.n
self.pontos[0] = 0
self.busca_exaustiva(self.flat_mat, self.n, 1)
return self.melhor_dist, self.melhores_pontos
Tsp = TSP()
distancia, pontos = Tsp.get_results()
print("Melhor distancia encontrada: ", distancia)
print("Melhor caminho encontrado: ", pontos)
#plota gráfico
def connectpoints(x,y,p1,p2):
x1, x2 = x[p1], x[p2]
y1, y2 = y[p1], y[p2]
plt.plot([x1,x2],[y1,y2],'ro-')
for i in range(1, len(pontos)):
connectpoints(x,y,pontos[i-1],pontos[i])
connectpoints(x,y,pontos[len(x)-1],pontos[0])
plt.title("Percurso")
plt.show()
%%time
%%cmd
python TSP.py < in-1.txt
type out-1.txt
python TSP.py < in-2.txt
type out-2.txt
python TSP.py < in-3.txt
type out-3.txt
python TSP.py < in-4.txt
type out-4.txt
from qiskit import IBMQ
import numpy as np
#IBMQ.save_account('seu-tokenIBMQ-para-rodar-localmente')
IBMQ.load_account()
from qiskit import Aer
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.library import TwoLocal
from qiskit.optimization.applications.ising import max_cut, tsp
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import SPSA
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.problems import QuadraticProgram
import logging
from qiskit.aqua import set_qiskit_aqua_logging
#Preparando os dados segundo os imputs do usuario para serem resolvidos pelo qiskit max 4 pontos por limitação de qubits
coord = []
flat_mat, x, y = TSP().dist_mat()
dist_mat = np.array(flat_mat).reshape(len(x),len(x))
for i, j in zip(x, y):
coord.append([i,j])
ins = tsp.TspData('TSP_Q', dim=len(x), coord=np.array(coord), w=dist_mat)
qubitOp, offset = tsp.get_operator(ins)
print('Offset:', offset)
print('Ising Hamiltonian:')
print(qubitOp.print_details())
#Usando o numpyMinimumEigensolver como o solver do problema para resolver de forma quantica
ee = NumPyMinimumEigensolver(qubitOp)
result = ee.run()
print('energy:', result.eigenvalue.real)
print('tsp objective:', result.eigenvalue.real + offset)
x_Q = sample_most_likely(result.eigenstate)
print('feasible:', tsp.tsp_feasible(x_Q))
z = tsp.get_tsp_solution(x_Q)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
for i in range(1, len(z)):
connectpoints(x,y,z[i-1],z[i])
connectpoints(x,y,z[len(x)-1],z[0])
plt.title("Percurso")
plt.show()
#instanciando o simulador ou o computador real importante lembrar que nao ira funcionar para mais de 4 pontos pelo numero de qubits disponibilizados pela IBM que sao apenas 16 para o simulador qasm e 15 para a maquina quantica
provider = IBMQ.get_provider(hub = 'ibm-q')
device = provider.get_backend('ibmq_16_melbourne')
aqua_globals.random_seed = np.random.default_rng(123)
seed = 10598
backend = Aer.get_backend('qasm_simulator')
#descomentar essa linha caso queira rodar na maquina real
#backend = device
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
#rodando no simulador quantico
spsa = SPSA(maxiter=10)
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa, quantum_instance=quantum_instance)
result = vqe.run(quantum_instance)
print('energy:', result.eigenvalue.real)
print('time:', result.optimizer_time)
x = sample_most_likely(result.eigenstate)
print('feasible:', tsp.tsp_feasible(x_Q))
z = tsp.get_tsp_solution(x_Q)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
%run qlatvia.py
draw_qubit()
draw_quantum_state(3/5,4/5,"|v>")
%run qlatvia.py
draw_qubit()
draw_quantum_state(3/5,4/5,"|v>")
from matplotlib.pyplot import arrow, text, gca
# the projection on |0>-axis
arrow(0,0,3/5,0,color="blue",linewidth=1.5)
arrow(0,4/5,3/5,0,color="blue",linestyle='dotted')
text(0.1,-0.1,"cos(a)=3/5")
# the projection on |1>-axis
arrow(0,0,0,4/5,color="blue",linewidth=1.5)
arrow(3/5,0,0,4/5,color="blue",linestyle='dotted')
text(-0.1,0.55,"sin(a)=4/5",rotation="90")
# drawing the angle with |0>-axis
from matplotlib.patches import Arc
gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=53) )
text(0.08,0.05,'.',fontsize=30)
text(0.21,0.09,'a')
%run qlatvia.py
draw_qubit()
from math import acos, pi
#
# your solution is here
#
quantum_state = random_quantum_state()
# obtain the degree with x-axis
radian = acos(quantum_state[0])
# convert radians to degree
angle = 360 * radian/(2*pi)
print("angle: " + str(angle) + " degrees")
# verify by visualizing the quantum state
draw_quantum_state(quantum_state[0],quantum_state[1],"s0")
%run qlatvia.py
draw_qubit()
draw_quantum_state(3/5,4/5,"|v1>")
draw_quantum_state(3/5,-4/5,"|v2>")
from matplotlib.pyplot import arrow, text, gca
# the projection on |0>-axis
arrow(0,0,3/5,0,color="blue",linewidth=1.5)
arrow(0,0,3/5,0,color="blue",linewidth=1.5)
arrow(0,4/5,3/5,0,color="blue",linestyle='dotted')
arrow(0,-4/5,3/5,0,color="blue",linestyle='dotted')
text(0.36,0.05,"cos(a)=3/5")
text(0.36,-0.09,"cos($-$a)=3/5")
# the projection on |1>-axis
arrow(0,0,0,4/5,color="blue",linewidth=1.5)
arrow(0,0,0,-4/5,color="blue",linewidth=1.5)
arrow(3/5,0,0,4/5,color="blue",linestyle='dotted')
arrow(3/5,0,0,-4/5,color="blue",linestyle='dotted')
text(-0.1,0.55,"sin(a)=4/5",rotation="90")
text(-0.14,-0.2,"sin($-$a)=$-$4/5",rotation="270")
# drawing the angle with |0>-axis
from matplotlib.patches import Arc
gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=53) )
text(0.08,0.05,'.',fontsize=30)
text(0.21,0.09,'a')
gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=-53,theta2=0) )
text(0.08,-0.07,'.',fontsize=30)
text(0.19,-0.12,'$-$a')
# set the angle
from random import randrange
myangle = randrange(361)
################################################
from matplotlib.pyplot import figure,gca
from matplotlib.patches import Arc
from math import sin,cos,pi
# draw a figure
figure(figsize=(6,6), dpi=60)
%run qlatvia.py
draw_axes()
print("the selected angle is",myangle,"degrees")
ratio_of_arc = ((1000*myangle/360)//1)/1000
print("it is",ratio_of_arc,"of a full circle")
print("its length is",ratio_of_arc,"x 2\u03C0","=",ratio_of_arc*2*pi)
myangle_in_radian = 2*pi*(myangle/360)
print("its radian value is",myangle_in_radian)
gca().add_patch( Arc((0,0),0.2,0.2,angle=0,theta1=0,theta2=myangle,color="red") )
gca().add_patch( Arc((0,0),2,2,angle=0,theta1=0,theta2=myangle,color="blue") )
x = cos(myangle_in_radian)
y = sin(myangle_in_radian)
draw_quantum_state(x,y,"|v>")
%run qlatvia.py
draw_qubit()
from math import acos, pi
#
# your solution is here
#
# get the random quantum state
quantum_state = random_quantum_state()
x, y = quantum_state[0], quantum_state[1]
# obtain the degree with x-axis
radian = acos(x)
# convert radians to degree
angle = 360 * radian/(2*pi)
print("the selected angle is",angle,"degrees")
ratio_of_arc = ((1000*myangle/360)//1)/1000
print("it is",ratio_of_arc,"of a full circle")
print("its length is",ratio_of_arc,"x 2\u03C0","=",ratio_of_arc*2*pi)
angle_in_radian = 2*pi*(angle/360)
print("its radian value is",angle_in_radian)
gca().add_patch( Arc((0,0),0.2,0.2,angle=0,theta1=0,theta2=angle,color="red") )
gca().add_patch( Arc((0,0),2,2,angle=0,theta1=0,theta2=angle,color="blue") )
x = cos(angle_in_radian)
y = sin(angle_in_radian)
# draw the axes
draw_axes()
draw_quantum_state(x,y,"|u>")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.delay(20, d0)
pulse.shift_phase(3.14/2, d0)
pulse.set_phase(3.14, d0)
pulse.shift_frequency(1e7, d0)
pulse.set_frequency(5e9, d0)
with pulse.build() as temp_sched:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0)
pulse.call(temp_sched)
pulse.acquire(30, a0, pulse.MemorySlot(0))
drive_sched.draw()
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
from qiskit.circuit.library.standard_gates import RXGate, RZGate, CXGate, CZGate
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
def anzats_circ(thetas, phis, D1, D2):
qr = QuantumRegister(4, name="q")
cr = ClassicalRegister(4, name='c')
qc = QuantumCircuit(qr, cr)
for d in range(D1):
qc.append(RXGate(phis[0]), [qr[2]])
qc.append(RXGate(phis[1]), [qr[3]])
qc.append(RZGate(phis[2]), [qr[2]])
qc.append(RZGate(phis[3]), [qr[3]])
qc.append(CZGate(), [qr[2], qr[3]])
qc.barrier(qr)
for d in range(D2):
qc.append(RXGate(thetas[0]), [qr[0]])
qc.append(RXGate(thetas[1]), [qr[1]])
qc.append(RXGate(thetas[2]), [qr[2]])
qc.append(RXGate(thetas[3]), [qr[3]])
qc.append(RZGate(thetas[4]), [qr[0]])
qc.append(RZGate(thetas[5]), [qr[1]])
qc.append(RZGate(thetas[6]), [qr[2]])
qc.append(RZGate(thetas[7]), [qr[3]])
qc.append(CZGate(), [qr[0], qr[1]])
qc.append(CZGate(), [qr[1], qr[2]])
qc.append(CZGate(), [qr[2], qr[3]])
qc.barrier(qr)
qc.append(RXGate(thetas[0]), [qr[0]])
qc.append(RXGate(thetas[1]), [qr[1]])
qc.append(RXGate(thetas[2]), [qr[2]])
qc.append(RXGate(thetas[3]), [qr[3]])
qc.append(RZGate(thetas[4]), [qr[0]])
qc.append(RZGate(thetas[5]), [qr[1]])
qc.append(RZGate(thetas[6]), [qr[2]])
qc.append(RZGate(thetas[7]), [qr[3]])
return qc
#Define in this box the parameters for the anzats
import numpy as np
#you may define here the requsted parameters as you'd like
thetas = np.array([0,0,0,0,np.pi/2,np.pi/2,np.pi/2,np.pi/2])
phis = np.array([np.pi,np.pi,np.pi,np.pi])
#you may define here the requested number of iterations D1 and D2 as described in Fig.1 of Subspace-search variational quantum
#eigensolver for excited states.
D1 = 1
D2 = 1
#display the created circuit
qc = anzats_circ(thetas,phis,D1,D2)
qc.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
dag_drawer(dag)
|
https://github.com/qiskit-community/qgss-2024
|
qiskit-community
|
from qiskit.circuit import QuantumCircuit
from qiskit.primitives import Estimator, Sampler
from qiskit.quantum_info import SparsePauliOp
from qiskit.visualization import plot_histogram
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('dark_background') # optional
# create excited |1> state
qc_1 = QuantumCircuit(1)
qc_1.x(0)
qc_1.draw('mpl')
# create superposition |+> state
qc_plus = QuantumCircuit(1)
qc_plus.h(0)
qc_plus.draw('mpl')
qc_1.measure_all()
qc_plus.measure_all()
sampler = Sampler()
job_1 = sampler.run(qc_1)
job_plus = sampler.run(qc_plus)
job_1.result().quasi_dists
job_plus.result().quasi_dists
legend = ["Excited State", "Plus State"] # TODO: Excited State does not appear
plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend)
qc_1.remove_final_measurements()
qc_plus.remove_final_measurements()
# rotate into the X-basis
qc_1.h(0)
qc_plus.h(0)
qc_1.measure_all()
qc_plus.measure_all()
sampler = Sampler()
job_1 = sampler.run(qc_1)
job_plus = sampler.run(qc_plus)
plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend)
qc2_1 = QuantumCircuit(1)
qc2_1.x(0)
qc2_plus = QuantumCircuit(1)
qc2_plus.h(0)
obsvs = list(SparsePauliOp(['Z', 'X']))
estimator = Estimator()
job2_1 = estimator.run([qc2_1]*len(obsvs), observables=obsvs)
job2_plus = estimator.run([qc2_plus]*len(obsvs), observables=obsvs)
job2_1.result()
# TODO: make this into module that outputs a nice table
print(f' | <Z> | <X> ')
print(f'----|------------------')
print(f'|1> | {job2_1.result().values[0]} | {job2_1.result().values[1]}')
print(f'|+> | {job2_plus.result().values[0]} | {job2_plus.result().values[1]}')
obsv = # create operator for chsh witness
from qc_grader.challenges.qgss_2023 import grade_lab2_ex1
grade_lab2_ex1(obsv)
from qiskit.circuit import Parameter
theta = Parameter('θ')
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.ry(theta, 0)
qc.draw('mpl')
angles = # create a parameterization of angles that will violate the inequality
estimator = Estimator()
job = estimator.run([qc]*len(angles), observables=[obsv]*len(angles), parameter_values=angles)
exps = job.result().values
plt.plot(angles, exps, marker='x', ls='-', color='green')
plt.plot(angles, [2]*len(angles), ls='--', color='red', label='Classical Bound')
plt.plot(angles, [-2]*len(angles), ls='--', color='red')
plt.xlabel('angle (rad)')
plt.ylabel('CHSH Witness')
plt.legend(loc=4)
from qc_grader.challenges.qgss_2023 import grade_lab2_ex2
grade_lab2_ex2(obsv, angles)
from qiskit.circuit import ClassicalRegister, QuantumRegister
theta = Parameter('θ')
qr = QuantumRegister(1, 'q')
qc = QuantumCircuit(qr)
qc.ry(theta, 0)
qc.draw('mpl')
tele_qc = qc.copy()
bell = QuantumRegister(2, 'Bell')
alice = ClassicalRegister(2, 'Alice')
bob = ClassicalRegister(1, 'Bob')
tele_qc.add_register(bell, alice, bob)
tele_qc.draw('mpl')
# create Bell state with other two qubits
tele_qc.barrier()
tele_qc.h(1)
tele_qc.cx(1, 2)
tele_qc.barrier()
tele_qc.draw('mpl')
# alice operates on her qubits
tele_qc.cx(0, 1)
tele_qc.h(0)
tele_qc.barrier()
tele_qc.draw('mpl')
tele_qc.measure([qr[0], bell[0]], alice)
tele_qc.draw('mpl')
graded_qc = tele_qc.copy()
##############################
# add gates to graded_qc here
##############################
graded_qc.draw('mpl')
graded_qc.barrier()
graded_qc.measure(bell[1], bob)
graded_qc.draw('mpl')
from qc_grader.challenges.qgss_2023 import grade_lab2_ex3
grade_lab2_ex3(graded_qc, theta, 5*np.pi/7)
from qiskit_aer.primitives import Sampler
angle = 5*np.pi/7
sampler = Sampler()
qc.measure_all()
job_static = sampler.run(qc.bind_parameters({theta: angle}))
job_dynamic = sampler.run(graded_qc.bind_parameters({theta: angle}))
print(f"Original Dists: {job_static.result().quasi_dists[0].binary_probabilities()}")
print(f"Teleported Dists: {job_dynamic.result().quasi_dists[0].binary_probabilities()}")
from qiskit.result import marginal_counts
tele_counts = # marginalize counts
legend = ['Original State', 'Teleported State']
plot_histogram([job_static.result().quasi_dists[0].binary_probabilities(), tele_counts], legend=legend)
from qc_grader.challenges.qgss_2023 import grade_lab2_ex4
grade_lab2_ex4(tele_counts, job_dynamic.result())
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import pylab
from qiskit_chemistry import QiskitChemistry
# Input dictionary to configure Qiskit Chemistry for the chemistry problem.
qiskit_chemistry_dict = {
'driver': {'name': 'PSI4'},
'PSI4': '',
'algorithm': {'name': 'ExactEigensolver'},
}
# PSI4 config here is a multi-line string that we update using format()
# To do so all other curly brackets from PSI4 config must be doubled
psi4_cfg = """
molecule h2 {{
0 1
H 0.0 0.0 -{0}
H 0.0 0.0 {0}
}}
set {{
basis {1}
scf_type pk
}}
"""
basis_sets = ['sto-3g', '3-21g', '6-31g']
start = 0.5 # Start distance
by = 0.5 # How much to increase distance by
steps = 20 # Number of steps to increase by
energies = np.empty([len(basis_sets), steps+1])
distances = np.empty(steps+1)
print('Processing step __', end='')
for i in range(steps+1):
print('\b\b{:2d}'.format(i), end='', flush=True)
d = start + i*by/steps
for j in range(len(basis_sets)):
qiskit_chemistry_dict['PSI4'] = psi4_cfg.format(d/2, basis_sets[j])
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict)
energies[j][i] = result['energy']
distances[i] = d
print(' --- complete')
print('Distances: ', distances)
print('Energies:', energies)
for j in range(len(basis_sets)):
pylab.plot(distances, energies[j], label=basis_sets[j])
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('H2 Ground State Energy in different basis sets')
pylab.legend(loc='upper right')
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library.standard_gates import PhaseGate
from qiskit.circuit.library.basis_change import QFT
import math
from src.util.util import run_qc
q = QuantumRegister(3)
b = QuantumRegister(1)
c = ClassicalRegister(3)
qc = QuantumCircuit(q, b, c)
qc.x(q[0])
qc.draw(output='mpl')
def increment(circuit, register, apply_QFT=True):
q = register
num = len(q)
qc = circuit
if apply_QFT == True:
qc.barrier()
qc = qc.compose(QFT(num_qubits=num, approximation_degree=0, do_swaps=True, \
inverse=False, insert_barriers=True, name='qft'))
qc.barrier()
for i, qubit in enumerate(q):
qc.rz(math.pi/2**(num-1-i), qubit)
if apply_QFT == True:
qc.barrier()
qc = qc.compose(QFT(num_qubits=num, approximation_degree=0, do_swaps=True, \
inverse=True, insert_barriers=True, name='iqft'))
qc.barrier()
return qc
test = increment(qc, q)
test.draw(output='mpl')
def control_increment(circuit, qregister, cregister, apply_QFT=True):
q = qregister
c = cregister
numq = len(q)
numc = len(c)
qc = circuit
if apply_QFT == True:
qc.barrier()
qc = qc.compose(QFT(num_qubits=numq, approximation_degree=0, do_swaps=True, \
inverse=False, insert_barriers=True, name='qft'))
qc.barrier()
for i, qubit in enumerate(q):
ncp = PhaseGate(math.pi/2**(numq-i-1)).control(numc)
qc.append(ncp, [*c, qubit])
if apply_QFT == True:
qc.barrier()
qc = qc.compose(QFT(num_qubits=numq, approximation_degree=0, do_swaps=True, \
inverse=True, insert_barriers=True, name='iqft'))
qc.barrier()
return qc
test2 = control_increment(qc, q, b)
test2.draw(output='mpl')
## Test increment without control
test = increment(qc, q)
test.measure(q[:], c[:])
run_qc(qc)
test.draw(output='mpl')
# Test control increment
q = QuantumRegister(3)
b = QuantumRegister(1)
c = ClassicalRegister(3)
qc = QuantumCircuit(q, b, c)
qc.x(q[0])
qc = control_increment(qc, q, b)
# Flipping control qubit to 1
qc.x(b[0])
qc = control_increment(qc, q, b)
# Flipping control qubit to 1
qc.x(b[0])
qc = control_increment(qc, q, b)
# Should equal 010
qc.measure(q[:], c[:])
run_qc(qc)
qc.draw(output="mpl")
|
https://github.com/qiskit-community/qiskit-aqt-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, Alpine Quantum Technologies GmbH 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import uuid
from collections import Counter, defaultdict
from dataclasses import dataclass
from pathlib import Path
from types import TracebackType
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
NoReturn,
Optional,
Union,
)
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers import JobV1
from qiskit.providers.jobstatus import JobStatus
from qiskit.result.result import Result
from qiskit.utils.lazy_tester import contextlib
from tqdm import tqdm
from typing_extensions import Self, TypeAlias, assert_never
from qiskit_aqt_provider import api_models_generated, persistence
from qiskit_aqt_provider.api_models_direct import JobResultError
from qiskit_aqt_provider.aqt_options import AQTOptions
from qiskit_aqt_provider.circuit_to_aqt import circuits_to_aqt_job
if TYPE_CHECKING: # pragma: no cover
from qiskit_aqt_provider.aqt_resource import AQTDirectAccessResource, AQTResource
# Tags for the status of AQT API jobs
@dataclass
class JobFinished:
"""The job finished successfully."""
status: ClassVar = JobStatus.DONE
results: dict[int, list[list[int]]]
@dataclass
class JobFailed:
"""An error occurred during the job execution."""
status: ClassVar = JobStatus.ERROR
error: str
class JobQueued:
"""The job is queued."""
status: ClassVar = JobStatus.QUEUED
@dataclass
class JobOngoing:
"""The job is running."""
status: ClassVar = JobStatus.RUNNING
finished_count: int
class JobCancelled:
"""The job was cancelled."""
status = ClassVar = JobStatus.CANCELLED
JobStatusPayload: TypeAlias = Union[JobQueued, JobOngoing, JobFinished, JobFailed, JobCancelled]
@dataclass(frozen=True)
class Progress:
"""Progress information of a job."""
finished_count: int
"""Number of completed circuits."""
total_count: int
"""Total number of circuits in the job."""
@dataclass
class _MockProgressBar:
"""Minimal tqdm-compatible progress bar mock."""
total: int
"""Total number of items in the job."""
n: int = 0
"""Number of processed items."""
def update(self, n: int = 1) -> None:
"""Update the number of processed items by `n`."""
self.n += n
def __enter__(self) -> Self:
return self
def __exit__(
self,
exc_type: Optional[type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[TracebackType],
/,
) -> None: ...
class AQTJob(JobV1):
"""Handle for quantum circuits jobs running on AQT cloud backends.
Jobs contain one or more quantum circuits that are executed with a common
set of options (see :class:`AQTOptions <qiskit_aqt_provider.aqt_options.AQTOptions>`).
Job handles should be retrieved from calls
to :meth:`AQTResource.run <qiskit_aqt_provider.aqt_resource.AQTResource.run>`, which immediately
returns after submitting the job. The :meth:`result` method allows blocking until a job
completes:
>>> import qiskit
>>> from qiskit.providers import JobStatus
>>> from qiskit_aqt_provider import AQTProvider
>>>
>>> backend = AQTProvider("").get_backend("offline_simulator_no_noise")
>>>
>>> qc = qiskit.QuantumCircuit(1)
>>> _ = qc.rx(3.14, 0)
>>> _ = qc.measure_all()
>>> qc = qiskit.transpile(qc, backend)
>>>
>>> job = backend.run(qc, shots=100)
>>> result = job.result()
>>> job.status() is JobStatus.DONE
True
>>> result.success
True
>>> result.get_counts()
{'1': 100}
"""
_backend: "AQTResource"
def __init__(
self,
backend: "AQTResource",
circuits: list[QuantumCircuit],
options: AQTOptions,
) -> None:
"""Initialize an :class:`AQTJob` instance.
.. tip:: :class:`AQTJob` instances should not be created directly. Use
:meth:`AQTResource.run <qiskit_aqt_provider.aqt_resource.AQTResource.run>`
to submit circuits for execution and retrieve a job handle.
Args:
backend: backend to run the job on.
circuits: list of circuits to execute.
options: overridden resource options for this job.
"""
super().__init__(backend, "")
self.circuits = circuits
self.options = options
self.api_submit_payload = circuits_to_aqt_job(circuits, options.shots)
self.status_payload: JobStatusPayload = JobQueued()
@classmethod
def restore(
cls,
job_id: str,
*,
access_token: Optional[str] = None,
store_path: Optional[Path] = None,
remove_from_store: bool = True,
) -> Self:
"""Restore a job handle from local persistent storage.
.. warning:: The default local storage path depends on the `qiskit_aqt_provider`
package version. Job persisted with a different package version will therefore
**not** be found!
.. hint:: If the job's execution backend is an offline simulator, the
job is re-submitted to the simulation backend and the new job ID differs
from the one passed to this function.
Args:
job_id: identifier of the job to retrieve.
access_token: access token for the AQT cloud.
See :class:`AQTProvider <qiskit_aqt_provider.aqt_provider.AQTProvider>`.
store_path: local persistent storage directory.
By default, use a standard cache directory.
remove_from_store: if :data:`True`, remove the retrieved job's data from persistent
storage after a successful load.
Returns:
A job handle for the passed `job_id`.
Raises:
JobNotFoundError: the target job was not found in persistent storage.
"""
from qiskit_aqt_provider.aqt_provider import AQTProvider
from qiskit_aqt_provider.aqt_resource import AQTResource, OfflineSimulatorResource
store_path = persistence.get_store_path(store_path)
data = persistence.Job.restore(job_id, store_path)
# TODO: forward .env loading args?
provider = AQTProvider(access_token)
if data.resource.resource_type == "offline_simulator":
# FIXME: persist with_noise_model and restore it
resource = OfflineSimulatorResource(provider, data.resource, with_noise_model=False)
else:
resource = AQTResource(provider, data.resource)
obj = cls(backend=resource, circuits=data.circuits.circuits, options=data.options)
if data.resource.resource_type == "offline_simulator":
# re-submit the job because we can't restore the backend state
obj.submit()
else:
obj._job_id = job_id
if remove_from_store:
persistence.Job.remove_from_store(job_id, store_path)
return obj
def persist(self, *, store_path: Optional[Path] = None) -> Path:
"""Save this job to local persistent storage.
.. warning:: Only jobs that have been submitted for execution
can be persisted (a valid `job_id` is required).
Args:
store_path: local persistent storage directory.
By default, use a standard cache directory.
Returns:
The path to the job data in local persistent storage.
Raises:
RuntimeError: the job was never submitted for execution.
"""
if not self.job_id():
raise RuntimeError("Can only persist submitted jobs.")
store_path = persistence.get_store_path(store_path)
data = persistence.Job(
resource=self._backend.resource_id,
circuits=persistence.Circuits(self.circuits),
options=self.options,
)
return data.persist(self.job_id(), store_path)
def submit(self) -> None:
"""Submit this job for execution.
This operation is not blocking. Use :meth:`result()` to block until
the job completes.
Raises:
RuntimeError: this job was already submitted.
"""
if self.job_id():
raise RuntimeError(f"Job already submitted (ID: {self.job_id()})")
job_id = self._backend.submit(self)
self._job_id = str(job_id)
def status(self) -> JobStatus:
"""Query the job's status.
Returns:
Aggregated job status for all the circuits in this job.
"""
payload = self._backend.result(uuid.UUID(self.job_id()))
if isinstance(payload, api_models_generated.JobResponseRRQueued):
self.status_payload = JobQueued()
elif isinstance(payload, api_models_generated.JobResponseRROngoing):
self.status_payload = JobOngoing(finished_count=payload.response.finished_count)
elif isinstance(payload, api_models_generated.JobResponseRRFinished):
self.status_payload = JobFinished(
results={
int(circuit_index): [[sample.root for sample in shot] for shot in shots]
for circuit_index, shots in payload.response.result.items()
}
)
elif isinstance(payload, api_models_generated.JobResponseRRError):
self.status_payload = JobFailed(error=payload.response.message)
elif isinstance(payload, api_models_generated.JobResponseRRCancelled):
self.status_payload = JobCancelled()
else: # pragma: no cover
assert_never(payload)
return self.status_payload.status
def progress(self) -> Progress:
"""Progress information for this job."""
num_circuits = len(self.circuits)
if isinstance(self.status_payload, JobQueued):
return Progress(finished_count=0, total_count=num_circuits)
if isinstance(self.status_payload, JobOngoing):
return Progress(
finished_count=self.status_payload.finished_count, total_count=num_circuits
)
# if the circuit is finished, failed, or cancelled, it is completed
return Progress(finished_count=num_circuits, total_count=num_circuits)
@property
def error_message(self) -> Optional[str]:
"""Error message for this job (if any)."""
if isinstance(self.status_payload, JobFailed):
return self.status_payload.error
return None
def result(self) -> Result:
"""Block until all circuits have been evaluated and return the combined result.
Success or error is signalled by the `success` field in the returned Result instance.
Returns:
The combined result of all circuit evaluations.
"""
if self.options.with_progress_bar:
context: Union[tqdm[NoReturn], _MockProgressBar] = tqdm(total=len(self.circuits))
else:
context = _MockProgressBar(total=len(self.circuits))
with context as progress_bar:
def callback(
job_id: str, # noqa: ARG001
status: JobStatus, # noqa: ARG001
job: AQTJob,
) -> None:
progress = job.progress()
progress_bar.update(progress.finished_count - progress_bar.n)
# one of DONE, CANCELLED, ERROR
self.wait_for_final_state(
timeout=self.options.query_timeout_seconds,
wait=self.options.query_period_seconds,
callback=callback,
)
# make sure the progress bar completes
progress_bar.update(self.progress().finished_count - progress_bar.n)
results = []
if isinstance(self.status_payload, JobFinished):
for circuit_index, circuit in enumerate(self.circuits):
samples = self.status_payload.results[circuit_index]
results.append(
_partial_qiskit_result_dict(
samples, circuit, shots=self.options.shots, memory=self.options.memory
)
)
return Result.from_dict(
{
"backend_name": self._backend.name,
"backend_version": self._backend.version,
"qobj_id": id(self.circuits),
"job_id": self.job_id(),
"success": self.status_payload.status is JobStatus.DONE,
"results": results,
# Pass error message as metadata
"error": self.error_message,
}
)
class AQTDirectAccessJob(JobV1):
"""Handle for quantum circuits jobs running on direct-access AQT backends.
Use
:meth:`AQTDirectAccessResource.run
<qiskit_aqt_provider.aqt_resource.AQTDirectAccessResource.run>`
to get a handle and evaluate circuits on a direct-access backend.
"""
_backend: "AQTDirectAccessResource"
def __init__(
self,
backend: "AQTDirectAccessResource",
circuits: list[QuantumCircuit],
options: AQTOptions,
) -> None:
"""Initialize the :class:`AQTDirectAccessJob` instance.
Args:
backend: backend to run the job on.
circuits: list of circuits to execute.
options: overridden resource options for this job.
"""
super().__init__(backend, "")
self.circuits = circuits
self.options = options
self.api_submit_payload = circuits_to_aqt_job(circuits, options.shots)
self._job_id = uuid.uuid4()
self._status = JobStatus.INITIALIZING
def submit(self) -> None:
"""No-op on direct-access backends."""
def result(self) -> Result:
"""Iteratively submit all circuits and block until full completion.
If an error occurs, the remaining circuits are not executed and the whole
job is marked as failed.
Returns:
The combined result of all circuit evaluations.
"""
if self.options.with_progress_bar:
context: Union[tqdm[NoReturn], _MockProgressBar] = tqdm(total=len(self.circuits))
else:
context = _MockProgressBar(total=len(self.circuits))
result = {
"backend_name": self._backend.name,
"backend_version": self._backend.version,
"qobj_id": id(self.circuits),
"job_id": self.job_id(),
"success": True,
"results": [],
}
with context as progress_bar:
for circuit_index, circuit in enumerate(self.circuits):
api_circuit = self.api_submit_payload.payload.circuits[circuit_index]
job_id = self._backend.submit(api_circuit)
api_result = self._backend.result(
job_id, timeout=self.options.query_timeout_seconds
)
if isinstance(api_result.payload, JobResultError):
break
result["results"].append(
_partial_qiskit_result_dict(
api_result.payload.result,
circuit,
shots=self.options.shots,
memory=self.options.memory,
)
)
progress_bar.update(1)
else: # no circuits in the job, or all executed successfully
self._status = JobStatus.DONE
return Result.from_dict(result)
self._status = JobStatus.ERROR
result["success"] = False
return Result.from_dict(result)
def status(self) -> JobStatus:
"""Query the job's status.
Returns:
Aggregated job status for all the circuits in this job.
"""
return self._status
def _partial_qiskit_result_dict(
samples: list[list[int]], circuit: QuantumCircuit, *, shots: int, memory: bool
) -> dict[str, Any]:
"""Build the Qiskit result dict for a single circuit evaluation.
Args:
samples: measurement outcome of the circuit evaluation.
circuit: the evaluated circuit.
shots: number of repetitions of the circuit evaluation.
memory: whether to fill the classical memory dump field with the measurement results.
Returns:
Dict, suitable for Qiskit's `Result.from_dict` factory.
"""
meas_map = _build_memory_mapping(circuit)
data: dict[str, Any] = {"counts": _format_counts(samples, meas_map)}
if memory:
data["memory"] = ["".join(str(x) for x in reversed(states)) for states in samples]
return {
"shots": shots,
"success": True,
"status": JobStatus.DONE,
"data": data,
"header": {
"memory_slots": circuit.num_clbits,
"creg_sizes": [[reg.name, reg.size] for reg in circuit.cregs],
"qreg_sizes": [[reg.name, reg.size] for reg in circuit.qregs],
"name": circuit.name,
"metadata": circuit.metadata or {},
},
}
def _build_memory_mapping(circuit: QuantumCircuit) -> dict[int, set[int]]:
"""Scan the circuit for measurement instructions and collect qubit to classical bits mappings.
Qubits can be mapped to multiple classical bits, possibly in different classical registers.
The returned map only maps qubits referenced in a `measure` operation in the passed circuit.
Qubits not targeted by a `measure` operation will not appear in the returned result.
Parameters:
circuit: the `QuantumCircuit` to analyze.
Returns:
the translation map for all measurement operations in the circuit.
Examples:
>>> qc = QuantumCircuit(2)
>>> qc.measure_all()
>>> _build_memory_mapping(qc)
{0: {0}, 1: {1}}
>>> qc = QuantumCircuit(2, 2)
>>> _ = qc.measure([0, 1], [1, 0])
>>> _build_memory_mapping(qc)
{0: {1}, 1: {0}}
>>> qc = QuantumCircuit(3, 2)
>>> _ = qc.measure([0, 1], [0, 1])
>>> _build_memory_mapping(qc)
{0: {0}, 1: {1}}
>>> qc = QuantumCircuit(4, 6)
>>> _ = qc.measure([0, 1, 2, 3], [2, 3, 4, 5])
>>> _build_memory_mapping(qc)
{0: {2}, 1: {3}, 2: {4}, 3: {5}}
>>> qc = QuantumCircuit(3, 4)
>>> qc.measure_all(add_bits=False)
>>> _build_memory_mapping(qc)
{0: {0}, 1: {1}, 2: {2}}
>>> qc = QuantumCircuit(3, 3)
>>> _ = qc.x(0)
>>> _ = qc.measure([0], [2])
>>> _ = qc.y(1)
>>> _ = qc.measure([1], [1])
>>> _ = qc.x(2)
>>> _ = qc.measure([2], [0])
>>> _build_memory_mapping(qc)
{0: {2}, 1: {1}, 2: {0}}
5 qubits in two registers:
>>> from qiskit import QuantumRegister, ClassicalRegister
>>> qr0 = QuantumRegister(2)
>>> qr1 = QuantumRegister(3)
>>> cr = ClassicalRegister(2)
>>> qc = QuantumCircuit(qr0, qr1, cr)
>>> _ = qc.measure(qr0, cr)
>>> _build_memory_mapping(qc)
{0: {0}, 1: {1}}
Multiple mapping of a qubit:
>>> qc = QuantumCircuit(3, 3)
>>> _ = qc.measure([0, 1], [0, 1])
>>> _ = qc.measure([0], [2])
>>> _build_memory_mapping(qc)
{0: {0, 2}, 1: {1}}
"""
qu2cl: defaultdict[int, set[int]] = defaultdict(set)
for instruction in circuit.data:
if instruction.operation.name == "measure":
for qubit, clbit in zip(instruction.qubits, instruction.clbits):
qu2cl[circuit.find_bit(qubit).index].add(circuit.find_bit(clbit).index)
return dict(qu2cl)
def _shot_to_int(
fluorescence_states: list[int], qubit_to_bit: Optional[dict[int, set[int]]] = None
) -> int:
"""Format the detected fluorescence states from a single shot as an integer.
This follows the Qiskit ordering convention, where bit 0 in the classical register is mapped
to bit 0 in the returned integer. The first classical register in the original circuit
represents the least-significant bits in the integer representation.
An optional translation map from the quantum to the classical register can be applied.
If given, only the qubits registered in the translation map are present in the return value,
at the index given by the translation map.
Parameters:
fluorescence_states: detected fluorescence states for this shot
qubit_to_bit: optional translation map from quantum register to classical register positions
Returns:
integral representation of the shot result, with the translation map applied.
Examples:
Without a translation map, the natural mapping is used (n -> n):
>>> _shot_to_int([1])
1
>>> _shot_to_int([0, 0, 1])
4
>>> _shot_to_int([0, 1, 1])
6
Swap qubits 1 and 2 in the classical register:
>>> _shot_to_int([1, 0, 1], {0: {0}, 1: {2}, 2: {1}})
3
If the map is partial, only the mapped qubits are present in the output:
>>> _shot_to_int([1, 0, 1], {1: {2}, 2: {1}})
2
One can translate into a classical register larger than the
qubit register.
Warning: the classical register is always initialized to 0.
>>> _shot_to_int([1], {0: {1}})
2
>>> _shot_to_int([0, 1, 1], {0: {3}, 1: {4}, 2: {5}}) == (0b110 << 3)
True
or with a map larger than the qubit space:
>>> _shot_to_int([1], {0: {0}, 1: {1}})
1
Consider the typical example of two quantum registers (the second one contains
ancilla qubits) and one classical register:
>>> from qiskit import QuantumRegister, ClassicalRegister
>>> qr_meas = QuantumRegister(2)
>>> qr_ancilla = QuantumRegister(3)
>>> cr = ClassicalRegister(2)
>>> qc = QuantumCircuit(qr_meas, qr_ancilla, cr)
>>> _ = qc.measure(qr_meas, cr)
>>> tr_map = _build_memory_mapping(qc)
We assume that a single shot gave the result:
>>> ancillas = [1, 1, 0]
>>> meas = [1, 0]
Then the corresponding output is 0b01 (measurement qubits mapped straight
to the classical register of length 2):
>>> _shot_to_int(meas + ancillas, tr_map) == 0b01
True
One can overwrite qr_meas[1] with qr_ancilla[0]:
>>> _ = qc.measure(qr_ancilla[0], cr[1])
>>> tr_map = _build_memory_mapping(qc)
>>> _shot_to_int(meas + ancillas, tr_map) == 0b11
True
"""
tr_map = qubit_to_bit or {}
if tr_map:
# allocate a zero-initialized classical register
# TODO: support pre-initialized classical registers
clbits = max(max(d) for d in tr_map.values()) + 1
creg = [0] * clbits
for src_index, dest_indices in tr_map.items():
# the translation map could map more than just the measured qubits
with contextlib.suppress(IndexError):
for dest_index in dest_indices:
creg[dest_index] = fluorescence_states[src_index]
else:
creg = fluorescence_states.copy()
return int((np.left_shift(1, np.arange(len(creg))) * creg).sum())
def _format_counts(
samples: list[list[int]], qubit_to_bit: Optional[dict[int, set[int]]] = None
) -> dict[str, int]:
"""Format all shots results from a circuit evaluation.
The returned dictionary is compatible with Qiskit's `ExperimentResultData`
`counts` field.
Keys are hexadecimal string representations of the detected states, with the
optional `QuantumRegister` to `ClassicalRegister` applied. Values are the occurrences
of the keys.
Parameters:
samples: detected qubit fluorescence states for all shots
qubit_to_bit: optional quantum to classical register translation map
Returns:
collected counts, for `ExperimentResultData`.
Examples:
>>> _format_counts([[1, 0, 0], [0, 1, 0], [1, 0, 0]])
{'0x1': 2, '0x2': 1}
>>> _format_counts([[1, 0, 0], [0, 1, 0], [1, 0, 0]], {0: {2}, 1: {1}, 2: {0}})
{'0x4': 2, '0x2': 1}
"""
return dict(Counter(hex(_shot_to_int(shot, qubit_to_bit)) for shot in samples))
|
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.
"""Test for the converter dag dependency to dag circuit and
dag circuit to dag dependency."""
import unittest
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.converters.dag_to_dagdependency_v2 import _dag_to_dagdependency_v2
from qiskit.converters.dagdependency_to_dag import dagdependency_to_dag
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestCircuitToDagDependencyV2(QiskitTestCase):
"""Test DAGCircuit to DAGDependencyV2."""
def test_circuit_and_dag_dependency(self):
"""Check convert to dag dependency and back"""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit_in = QuantumCircuit(qr, cr)
circuit_in.h(qr[0])
circuit_in.h(qr[1])
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.x(qr[0]).c_if(cr, 0x3)
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.measure(qr[2], cr[2])
dag_in = circuit_to_dag(circuit_in)
dag_dependency = _dag_to_dagdependency_v2(dag_in)
dag_out = dagdependency_to_dag(dag_dependency)
self.assertEqual(dag_out, dag_in)
def test_metadata(self):
"""Test circuit metadata is preservered through conversion."""
meta_dict = {"experiment_id": "1234", "execution_number": 4}
qr = QuantumRegister(2)
circuit_in = QuantumCircuit(qr, metadata=meta_dict)
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.measure_all()
dag = circuit_to_dag(circuit_in)
self.assertEqual(dag.metadata, meta_dict)
dag_dependency = _dag_to_dagdependency_v2(dag)
self.assertEqual(dag_dependency.metadata, meta_dict)
dag_out = dagdependency_to_dag(dag_dependency)
self.assertEqual(dag_out.metadata, meta_dict)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.measure(0,0)
qc.x(0).c_if(0, 0)
qc.draw(output='mpl')
from qiskit import QuantumRegister, ClassicalRegister
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
qc = QuantumCircuit(q, c)
qc.h([0, 1, 2])
qc.barrier()
qc.measure(q, c)
qc.draw('mpl')
print(bin(3))
print(bin(7))
qc.x(2).c_if(c, 3) # for the 011 case
qc.x(2).c_if(c, 7) # for the 111 case
qc.draw(output='mpl')
nq = 2
m = 2
q = QuantumRegister(nq, 'q')
c = ClassicalRegister(m, 'c')
qc_S = QuantumCircuit(q,c)
qc_S.h(0)
qc_S.x(1)
qc_S.draw('mpl')
from math import pi
cu_circ = QuantumCircuit(2)
cu_circ.cp(pi/2, 0, 1)
cu_circ.draw('mpl')
for _ in range(2 ** (m - 1)):
qc_S.cp(pi/2, 0, 1)
qc_S.draw('mpl')
def x_measurement(qc, qubit, cbit):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'"""
qc.h(qubit)
qc.measure(qubit, cbit)
x_measurement(qc_S, q[0], c[0])
qc_S.draw('mpl')
qc_S.reset(0)
qc_S.h(0)
qc_S.draw('mpl')
qc_S.p(-pi/2, 0).c_if(c, 1)
qc_S.draw('mpl')
## 2^t c-U operations (with t=m-2)
for _ in range(2 ** (m - 2)):
qc_S.cp(pi/2, 0, 1)
x_measurement(qc_S, q[0], c[1])
qc_S.draw('mpl')
import matplotlib.pyplot as plt
from qiskit.tools.visualization import plot_histogram
from qiskit_aer.primitives import Sampler
sampler = Sampler()
job = sampler.run(qc_S)
result = job.result()
dist0 = result.quasi_dists[0]
key_new = [str(key/2**m) for key in list(dist0.keys())]
dist1 = dict(zip(key_new, dist0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(dist0, ax=ax[0])
plot_histogram(dist1, ax=ax[1])
plt.tight_layout()
nq = 3 # number of qubits
m = 3 # number of classical bits
q = QuantumRegister(nq,'q')
c = ClassicalRegister(m,'c')
qc = QuantumCircuit(q,c)
qc.h(0)
qc.x([1, 2])
qc.draw('mpl')
cu_circ = QuantumCircuit(nq)
cu_circ.mcp(pi/4, [0, 1], 2)
cu_circ.draw('mpl')
for _ in range(2 ** (m - 1)):
qc.mcp(pi/4, [0, 1], 2)
qc.draw('mpl')
x_measurement(qc, q[0], c[0])
qc.draw('mpl')
qc.reset(0)
qc.h(0)
qc.draw('mpl')
qc.p(-pi/2, 0).c_if(c, 1)
qc.draw('mpl')
for _ in range(2 ** (m - 2)):
qc.mcp(pi/4, [0, 1], 2)
x_measurement(qc, q[0], c[1])
qc.draw('mpl')
# initialization of qubit q0
qc.reset(0)
qc.h(0)
# phase correction
qc.p(-pi/4, 0).c_if(c, 1)
qc.p(-pi/2, 0).c_if(c, 2)
qc.p(-3*pi/2, 0).c_if(c, 3)
# c-U operations
for _ in range(2 ** (m - 3)):
qc.mcp(pi/4, [0, 1], 2)
# X measurement
qc.h(0)
qc.measure(0, 2)
qc.draw('mpl')
result = sampler.run(qc).result()
dist0 = result.quasi_dists[0]
key_new = [str(key/2**m) for key in list(dist0.keys())]
dist1 = dict(zip(key_new, dist0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(dist0, ax=ax[0])
plot_histogram(dist1, ax=ax[1])
plt.tight_layout()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
# import matplotlib.pyplot as plt
%matplotlib inline
print(qiskit.__version__)
circuit = QuantumCircuit(2,2)
circuit.h(0)
circuit.cx(0,1)
circuit.measure([0,1],[0,1])
# circuit.measure_all()
circuit.barrier()
# circuit.draw(output='mpl')
circuit.draw(output='mpl')
simulator = Aer.get_backend('aer_simulator')
result = execute(circuit, backend=simulator, shots=1024).result()
count = result.get_counts()
print(count)
from qiskit.tools.visualization import plot_histogram
plot_histogram(count)
from qiskit import IBMQ
IBMQ.save_account("b32678329f7f6dd426b8cf18f20bea23c2cd056b0bee2b4bcf49744b612e598f20f7170a8da4bfd99b009b6fa59d596edea7a6926fd388be158843d8ef******", overwrite=True)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider.backends()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
job = execute(circuit, backend=backend, shots=1024)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
count = result.get_counts()
print(count)
from qiskit.tools.visualization import plot_histogram
plot_histogram(count)
|
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/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
from qiskit import IBMQ
from qiskit import BasicAer as Aer
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle
import copy
from ipywidgets import widgets
from IPython.display import display, clear_output
try:
IBMQ.load_accounts()
except:
pass
class run_game():
# Implements a puzzle, which is defined by the given inputs.
def __init__(self,initialize, success_condition, allowed_gates, vi, qubit_names, eps=0.1, backend=Aer.get_backend('qasm_simulator'), shots=1024,mode='circle',verbose=False):
"""
initialize
List of gates applied to the initial 00 state to get the starting state of the puzzle.
Supported single qubit gates (applied to qubit '0' or '1') are 'x', 'y', 'z', 'h', 'ry(pi/4)'.
Supported two qubit gates are 'cz' and 'cx'. Specify only the target qubit.
success_condition
Values for pauli observables that must be obtained for the puzzle to declare success.
allowed_gates
For each qubit, specify which operations are allowed in this puzzle. 'both' should be used only for operations that don't need a qubit to be specified ('cz' and 'unbloch').
Gates are expressed as a dict with an int as value. If this is non-zero, it specifies the number of times the gate is must be used (no more or less) for the puzzle to be successfully solved. If the value is zero, the player can use the gate any number of times.
vi
Some visualization information as a three element list. These specify:
* which qubits are hidden (empty list if both shown).
* whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles).
* whether the correlation circles (the four in the middle) are shown.
qubit_names
The two qubits are always called '0' and '1' from the programming side. But for the player, we can display different names.
eps=0.1
How close the expectation values need to be to the targets for success to be declared.
backend=Aer.get_backend('qasm_simulator')
Backend to be used by Qiskit to calculate expectation values (defaults to local simulator).
shots=1024
Number of shots used to to calculate expectation values.
mode='circle'
Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line').
verbose=False
"""
def get_total_gate_list():
# Get a text block describing allowed gates.
total_gate_list = ""
for qubit in allowed_gates:
gate_list = ""
for gate in allowed_gates[qubit]:
if required_gates[qubit][gate] > 0 :
gate_list += ' ' + gate+" (use "+str(required_gates[qubit][gate])+" time"+"s"*(required_gates[qubit][gate]>1)+")"
elif allowed_gates[qubit][gate]==0:
gate_list += ' '+gate + ' '
if gate_list!="":
if qubit=="both" :
gate_list = "\nAllowed symmetric operations:" + gate_list
else :
gate_list = "\nAllowed operations for " + qubit_names[qubit] + ":\n" + " "*10 + gate_list
total_gate_list += gate_list +"\n"
return total_gate_list
def get_success(required_gates):
# Determine whether the success conditions are satisfied, both for expectation values, and the number of gates to be used.
success = True
grid.get_rho()
if verbose:
print(grid.rho)
for pauli in success_condition:
success = success and (abs(success_condition[pauli] - grid.rho[pauli])<eps)
for qubit in required_gates:
for gate in required_gates[qubit]:
success = success and (required_gates[qubit][gate]==0)
return success
def get_command(gate,qubit):
# For a given gate and qubit, return the string describing the corresoinding Qiskit string.
if qubit=='both':
qubit = '1'
qubit_name = qubit_names[qubit]
for name in qubit_names.values():
if name!=qubit_name:
other_name = name
# then make the command (both for the grid, and for printing to screen)
if gate in ['x','y','z','h']:
real_command = 'grid.qc.'+gate+'(grid.qr['+qubit+'])'
clean_command = 'qc.'+gate+'('+qubit_name+')'
elif gate in ['ry(pi/4)','ry(-pi/4)']:
real_command = 'grid.qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,grid.qr['+qubit+'])'
clean_command = 'qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,'+qubit_name+')'
elif gate in ['cz','cx','swap']:
real_command = 'grid.qc.'+gate+'(grid.qr['+'0'*(qubit=='1')+'1'*(qubit=='0')+'],grid.qr['+qubit+'])'
clean_command = 'qc.'+gate+'('+other_name+','+qubit_name+')'
return [real_command,clean_command]
clear_output()
bloch = [None]
# set up initial state and figure
grid = pauli_grid(backend=backend,shots=shots,mode=mode)
for gate in initialize:
eval( get_command(gate[0],gate[1])[0] )
required_gates = copy.deepcopy(allowed_gates)
# determine which qubits to show in figure
if allowed_gates['0']=={} : # if no gates are allowed for qubit 0, we know to only show qubit 1
shown_qubit = 1
elif allowed_gates['1']=={} : # and vice versa
shown_qubit = 0
else :
shown_qubit = 2
# show figure
grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list())
description = {'gate':['Choose gate'],'qubit':['Choose '+'qu'*vi[1]+'bit'],'action':['Make it happen!']}
all_allowed_gates_raw = []
for q in ['0','1','both']:
all_allowed_gates_raw += list(allowed_gates[q])
all_allowed_gates_raw = list(set(all_allowed_gates_raw))
all_allowed_gates = []
for g in ['bloch','unbloch']:
if g in all_allowed_gates_raw:
all_allowed_gates.append( g )
for g in ['x','y','z','h','cz','cx']:
if g in all_allowed_gates_raw:
all_allowed_gates.append( g )
for g in all_allowed_gates_raw:
if g not in all_allowed_gates:
all_allowed_gates.append( g )
gate = widgets.ToggleButtons(options=description['gate']+all_allowed_gates)
qubit = widgets.ToggleButtons(options=[''])
action = widgets.ToggleButtons(options=[''])
boxes = widgets.VBox([gate,qubit,action])
display(boxes)
if vi[1]:
print('\nYour quantum program so far\n')
self.program = []
def given_gate(a):
# Action to be taken when gate is chosen. This sets up the system to choose a qubit.
if gate.value:
if gate.value in allowed_gates['both']:
qubit.options = description['qubit'] + ["not required"]
qubit.value = "not required"
else:
allowed_qubits = []
for q in ['0','1']:
if (gate.value in allowed_gates[q]) or (gate.value in allowed_gates['both']):
allowed_qubits.append(q)
allowed_qubit_names = []
for q in allowed_qubits:
allowed_qubit_names += [qubit_names[q]]
qubit.options = description['qubit'] + allowed_qubit_names
def given_qubit(b):
# Action to be taken when qubit is chosen. This sets up the system to choose an action.
if qubit.value not in ['',description['qubit'][0],'Success!']:
action.options = description['action']+['Apply operation']
def given_action(c):
# Action to be taken when user confirms their choice of gate and qubit.
# This applied the command, updates the visualization and checks whether the puzzle is solved.
if action.value not in ['',description['action'][0]]:
# apply operation
if action.value=='Apply operation':
if qubit.value not in ['',description['qubit'][0],'Success!']:
# translate bit gates to qubit gates
if gate.value=='NOT':
q_gate = 'x'
elif gate.value=='CNOT':
q_gate = 'cx'
else:
q_gate = gate.value
if qubit.value=="not required":
q = qubit_names['1']
else:
q = qubit.value
q01 = '0'*(qubit.value==qubit_names['0']) + '1'*(qubit.value==qubit_names['1']) + 'both'*(qubit.value=="not required")
if q_gate in ['bloch','unbloch']:
if q_gate=='bloch':
bloch[0] = q01
else:
bloch[0] = None
else:
command = get_command(q_gate,q01)
eval(command[0])
if vi[1]:
print(command[1])
self.program.append( command[1] )
if required_gates[q01][gate.value]>0:
required_gates[q01][gate.value] -= 1
grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list())
success = get_success(required_gates)
if success:
gate.options = ['Success!']
qubit.options = ['Success!']
action.options = ['Success!']
plt.close(grid.fig)
else:
gate.value = description['gate'][0]
qubit.options = ['']
action.options = ['']
gate.observe(given_gate)
qubit.observe(given_qubit)
action.observe(given_action)
class pauli_grid():
# Allows a quantum circuit to be created, modified and implemented, and visualizes the output in the style of 'Hello Quantum'.
def __init__(self,backend=Aer.get_backend('qasm_simulator'),shots=1024,mode='circle'):
"""
backend=Aer.get_backend('qasm_simulator')
Backend to be used by Qiskit to calculate expectation values (defaults to local simulator).
shots=1024
Number of shots used to to calculate expectation values.
mode='circle'
Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line').
"""
self.backend = backend
self.shots = shots
self.box = {'ZI':(-1, 2),'XI':(-2, 3),'IZ':( 1, 2),'IX':( 2, 3),'ZZ':( 0, 3),'ZX':( 1, 4),'XZ':(-1, 4),'XX':( 0, 5)}
self.rho = {}
for pauli in self.box:
self.rho[pauli] = 0.0
for pauli in ['ZI','IZ','ZZ']:
self.rho[pauli] = 1.0
self.qr = QuantumRegister(2)
self.cr = ClassicalRegister(2)
self.qc = QuantumCircuit(self.qr, self.cr)
self.mode = mode
# colors are background, qubit circles and correlation circles, respectively
if self.mode=='line':
self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)]
else:
self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)]
self.fig = plt.figure(figsize=(5,5),facecolor=self.colors[0])
self.ax = self.fig.add_subplot(111)
plt.axis('off')
self.bottom = self.ax.text(-3,1,"",size=9,va='top',color='w')
self.lines = {}
for pauli in self.box:
w = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(1.0,1.0,1.0), lw=0 )
b = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(0.0,0.0,0.0), lw=0 )
c = {}
c['w'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(0,0,0), zorder=10) )
c['b'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(1,1,1), zorder=10) )
self.lines[pauli] = {'w':w,'b':b,'c':c}
def get_rho(self):
# Runs the circuit specified by self.qc and determines the expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'.
bases = ['ZZ','ZX','XZ','XX']
results = {}
for basis in bases:
temp_qc = copy.deepcopy(self.qc)
for j in range(2):
if basis[j]=='X':
temp_qc.h(self.qr[j])
temp_qc.barrier(self.qr)
temp_qc.measure(self.qr,self.cr)
job = execute(temp_qc, backend=self.backend, shots=self.shots)
results[basis] = job.result().get_counts()
for string in results[basis]:
results[basis][string] = results[basis][string]/self.shots
prob = {}
# prob of expectation value -1 for single qubit observables
for j in range(2):
for p in ['X','Z']:
pauli = {}
for pp in 'IXZ':
pauli[pp] = (j==1)*pp + p + (j==0)*pp
prob[pauli['I']] = 0
for basis in [pauli['X'],pauli['Z']]:
for string in results[basis]:
if string[(j+1)%2]=='1':
prob[pauli['I']] += results[basis][string]/2
# prob of expectation value -1 for two qubit observables
for basis in ['ZZ','ZX','XZ','XX']:
prob[basis] = 0
for string in results[basis]:
if string[0]!=string[1]:
prob[basis] += results[basis][string]
for pauli in prob:
self.rho[pauli] = 1-2*prob[pauli]
def update_grid(self,rho=None,labels=False,bloch=None,hidden=[],qubit=True,corr=True,message=""):
"""
rho = None
Dictionary of expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. If supplied, this will be visualized instead of the results of running self.qc.
labels = None
Dictionary of strings for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ' that are printed in the corresponding boxes.
bloch = None
If a qubit name is supplied, and if mode='line', Bloch circles are displayed for this qubit
hidden = []
Which qubits have their circles hidden (empty list if both shown).
qubit = True
Whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles).
corr = True
Whether the correlation circles (the four in the middle) are shown.
message
A string of text that is displayed below the grid.
"""
def see_if_unhidden(pauli):
# For a given Pauli, see whether its circle should be shown.
unhidden = True
# first: does it act non-trivially on a qubit in `hidden`
for j in hidden:
unhidden = unhidden and (pauli[j]=='I')
# second: does it contain something other than 'I' or 'Z' when only bits are shown
if qubit==False:
for j in range(2):
unhidden = unhidden and (pauli[j] in ['I','Z'])
# third: is it a correlation pauli when these are not allowed
if corr==False:
unhidden = unhidden and ((pauli[0]=='I') or (pauli[1]=='I'))
return unhidden
def add_line(line,pauli_pos,pauli):
"""
For mode='line', add in the line.
line = the type of line to be drawn (X, Z or the other one)
pauli = the box where the line is to be drawn
expect = the expectation value that determines its length
"""
unhidden = see_if_unhidden(pauli)
coord = None
p = (1-self.rho[pauli])/2 # prob of 1 output
# in the following, white lines goes from a to b, and black from b to c
if unhidden:
if line=='Z':
a = ( self.box[pauli_pos][0], self.box[pauli_pos][1]+l/2 )
c = ( self.box[pauli_pos][0], self.box[pauli_pos][1]-l/2 )
b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] )
lw = 8
coord = (b[1] - (a[1]+c[1])/2)*1.2 + (a[1]+c[1])/2
elif line=='X':
a = ( self.box[pauli_pos][0]+l/2, self.box[pauli_pos][1] )
c = ( self.box[pauli_pos][0]-l/2, self.box[pauli_pos][1] )
b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] )
lw = 9
coord = (b[0] - (a[0]+c[0])/2)*1.1 + (a[0]+c[0])/2
else:
a = ( self.box[pauli_pos][0]+l/(2*np.sqrt(2)), self.box[pauli_pos][1]+l/(2*np.sqrt(2)) )
c = ( self.box[pauli_pos][0]-l/(2*np.sqrt(2)), self.box[pauli_pos][1]-l/(2*np.sqrt(2)) )
b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] )
lw = 9
self.lines[pauli]['w'].pop(0).remove()
self.lines[pauli]['b'].pop(0).remove()
self.lines[pauli]['w'] = plt.plot( [a[0],b[0]], [a[1],b[1]], color=(1.0,1.0,1.0), lw=lw )
self.lines[pauli]['b'] = plt.plot( [b[0],c[0]], [b[1],c[1]], color=(0.0,0.0,0.0), lw=lw )
return coord
l = 0.9 # line length
r = 0.6 # circle radius
L = 0.98*np.sqrt(2) # box height and width
if rho==None:
self.get_rho()
# draw boxes
for pauli in self.box:
if 'I' in pauli:
color = self.colors[1]
else:
color = self.colors[2]
self.ax.add_patch( Rectangle( (self.box[pauli][0],self.box[pauli][1]-1), L, L, angle=45, color=color) )
# draw circles
for pauli in self.box:
unhidden = see_if_unhidden(pauli)
if unhidden:
if self.mode=='line':
self.ax.add_patch( Circle(self.box[pauli], r, color=(0.5,0.5,0.5)) )
else:
prob = (1-self.rho[pauli])/2
self.ax.add_patch( Circle(self.box[pauli], r, color=(prob,prob,prob)) )
# update bars if required
if self.mode=='line':
if bloch in ['0','1']:
for other in 'IXZ':
px = other*(bloch=='1') + 'X' + other*(bloch=='0')
pz = other*(bloch=='1') + 'Z' + other*(bloch=='0')
z_coord = add_line('Z',pz,pz)
x_coord = add_line('X',pz,px)
for j in self.lines[pz]['c']:
self.lines[pz]['c'][j].center = (x_coord,z_coord)
self.lines[pz]['c'][j].radius = (j=='w')*0.05 + (j=='b')*0.04
px = 'I'*(bloch=='0') + 'X' + 'I'*(bloch=='1')
pz = 'I'*(bloch=='0') + 'Z' + 'I'*(bloch=='1')
add_line('Z',pz,pz)
add_line('X',px,px)
else:
for pauli in self.box:
for j in self.lines[pauli]['c']:
self.lines[pauli]['c'][j].radius = 0.0
if pauli in ['ZI','IZ','ZZ']:
add_line('Z',pauli,pauli)
if pauli in ['XI','IX','XX']:
add_line('X',pauli,pauli)
if pauli in ['XZ','ZX']:
add_line('ZX',pauli,pauli)
self.bottom.set_text(message)
if labels:
for pauli in box:
plt.text(self.box[pauli][0]-0.05,self.box[pauli][1]-0.85, pauli)
self.ax.set_xlim([-3,3])
self.ax.set_ylim([0,6])
self.fig.canvas.draw()
|
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/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/jcylim/QiskitProject
|
jcylim
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError
from qiskit import available_backends, execute, register, get_backend
from qiskit.tools.visualization import circuit_drawer
from qiskit.tools.qi.qi import state_fidelity
# Useful additional packages
import matplotlib.pyplot as plt
#matplotlib inline
import numpy as np
from math import pi
q = QuantumRegister(3)
qc = QuantumCircuit(q)
'''
#Controlled Pauli Gates
# 1. Controlled-X (or, controlled-NOT) gate
qc.cx(q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 2. Controlled Y gate
qc.cy(q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 3. Controlled Z (or, controlled phase) gate
qc.cz(q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 4. Controlled Hadamard gate
qc.ch(q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
#Controlled rotation gates
# 5. Controlled rotation around Z-axis
qc.crz(pi/2,q[0],q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 6. Controlled phase rotation
qc.cu1(pi/2,q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 7. Controlled u3 rotation
qc.cu3(pi/2, pi/2, pi/2, q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 8. Swap rotation
qc.swap(q[0], q[1])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# 9. Toffoli gate
qc.ccx(q[0], q[1], q[2])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
'''
# 10. Controlled swap gate (Fredkin Gate)
qc.cswap(q[0], q[1], q[2])
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
print(np.round(job.result().get_data(qc)['unitary'], 3))
|
https://github.com/zapata-engineering/orquestra-qiskit
|
zapata-engineering
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/bopardikarsoham/The-Quantum-Teleportation-Algorithm
|
bopardikarsoham
|
from qiskit import *
circuit = QuantumCircuit(3,3)
%matplotlib inline
circuit.draw(output='mpl')
circuit.x(0)
circuit.barrier()
circuit.draw(output='mpl')
circuit.h(1)
circuit.cx(1,2)
circuit.draw(output='mpl')
circuit.cx(0,1)
circuit.h(0)
circuit.draw(output='mpl')
circuit.barrier()
circuit.measure([0,1], [0,1])
circuit.draw(output='mpl')
circuit.barrier()
circuit.cx(1,2)
circuit.cz(0,2)
circuit.draw(output='mpl')
circuit.measure(2,2)
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend = simulator, shots = 1024).result()
counts = result.get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/rainmaker29/QuantumComputing-qiskit
|
rainmaker29
|
import qiskit as q
%matplotlib inline
# Creating a quantum circuit with 3 qbits
circuit = q.QuantumCircuit(2,2)
#Adding a NOT gate to 0th qbit which flips the input
circuit.x(0)
#Adding a 'Controlled NOT' gate between 0th,1st qbits
#CNOT Gate operation : The second bit is flipped if the first bit is 1
circuit.cx(0,1)
#Mapping the value of qbit to classical bits (collapse)
circuit.measure([0,1],[0,1])
circuit.draw()
circuit.draw(output="mpl")
from qiskit import IBMQ
IBMQ.save_account("e870e2997e01a21385263381f81495beff826d71a12d646658a7a15ffc5400dbbefa30e9ce0d2e65b872b30170038db21cdf8482e422510d62ef16297ad5c8a2")
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider("ibm-q")
# In QC practice,a simulator or a quantum computer is referred to as 'backend'
for backend in provider.backends():
try:
qubit_count = len(backend.properties().qubits)
except :
qubit_count = "simulated"
print(backend.name(),"has",backend.status().pending_jobs," queued and ",qubit_count,"qubits")
from qiskit.tools.monitor import job_monitor
backend = provider.get_backend("ibmqx2") #Since it has0 queued
job = q.execute(circuit,backend=backend,shots=500)
job_monitor(job)
# Now our circuit has been successfully run on IBM Cloud's IBMQX2 machine
from qiskit.visualization import plot_histogram
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts],legend=['Device'])
circuit = q.QuantumCircuit(2,2)
# Hadamard gate to the first qbit
circuit.h(0)
# The same good old CNOT gate
circuit.cx(0,1)
circuit.measure([0,1],[0,1])
circuit.draw(output="mpl")
# Let's execute this circuit
# This cell isn't much needed yet we'll use it as a revision cell
for backend in provider.backends():
try:
qubit_count = len(backend.properties().qubits)
except:
qubit_count = "simulated"
print(backend.name(),"has ",backend.status().pending_jobs,"queued and",qubit_count,"qubits")
# let's choose ibmqx2
backend = provider.get_backend("ibmqx2")
job = q.execute(circuit,backend = backend,shots=500)
job_monitor(job) # Gives the status of our job
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts],legend=['Device '])
from qiskit import Aer
for backend in Aer.backends():
print(backend)
#Let's use qasm_simulator
sim_backend = Aer.get_backend('qasm_simulator')
job = q.execute(circuit,backend=sim_backend,shots=500)
job_monitor(job)
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts],legend=['Device'])
import qiskit as q
from qiskit.tools.visualization import plot_bloch_multivector
%matplotlib inline
statevec_simulator = q.Aer.get_backend("statevector_simulator")
qasm_sim = q.Aer.get_backend('qasm_simulator')
def do_job(circuit):
job = q.execute(circuit,backend=statevec_simulator)
result = job.result()
statevec = result.get_statevector()
n_qubits = circuit.n_qubits
circuit.measure([i for i in range(n_qubits)],[i for i in range(n_qubits)])
qasm_job = q.execute(circuit,backend=qasm_sim,shots=1024).result()
counts = qasm_job.get_counts()
return statevec,counts
circuit = q.QuantumCircuit(2,2)
statevec,counts=do_job(circuit)
plot_bloch_multivector(statevec)
# Let's see how superposition looks like in bloch sphere
circuit = q.QuantumCircuit(2,2)
circuit.h(0)
statevec,counts = do_job(circuit)
plot_bloch_multivector(statevec)
# The qubit 0 is under superposition . So, it lies between 1 and 0 states in the space
#Let's entangle the qubits
circuit = q.QuantumCircuit(2,2)
circuit.h(0)
circuit.cx(0,1)
statevec,counts = do_job(circuit)
plot_bloch_multivector(statevec)
from qiskit.visualization import plot_histogram
plot_histogram([counts],legend=['Device'])
#Let's take 3 qubits and control the last qubit by the first two qubits
circuit = q.QuantumCircuit(3,3)
circuit.h(0)
circuit.h(1)
circuit.cx(0,2)
circuit.cx(1,2)
circuit.draw(output="mpl")
statevec,counts = do_job(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts],legend=['Device'])
circuit = q.QuantumCircuit(3,3)
circuit.h(0)
circuit.h(1)
circuit.ccx(0,1,2)
circuit.draw(output="mpl")
statevec,counts = do_job(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts],legend=['Device'])
circuit = q.QuantumCircuit(3,1)
circuit.h(0)
circuit.h(1)
circuit.ccx(0,1,2)
circuit.measure([2],[0])
result = q.execute(circuit,backend=qasm_sim,shots=1024).result()
counts = result.get_counts()
plot_histogram([counts],legend=['Device'])
import math
circuit = q.QuantumCircuit(3,1)
circuit.h(0)
circuit.h(1)
circuit.ccx(0,1,2)
circuit.rx(math.pi/2,2)
circuit.draw(output="mpl")
circuit.measure([2],[0])
result = q.execute(circuit,backend=qasm_sim,shots=1024).result()
counts = result.get_counts()
plot_histogram([counts],legend=['output'])
#Rotate X by 45 deg
circuit = q.QuantumCircuit(3,3)
circuit.h(0)
circuit.h(1)
circuit.ccx(0,1,2)
circuit.rx(math.pi/4,2)
statevec,counts = do_job(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts],legend=['output'])
circuit = q.QuantumCircuit(3,3)
circuit.h(0)
circuit.h(1)
circuit.ccx(0,1,2)
circuit.rx(math.pi/4, 2)
circuit.rz(math.pi, 2)
circuit.ry(math.pi, 2)
statevec, counts = do_job(circuit)
plot_bloch_multivector(statevec)
circuit = q.QuantumCircuit(3,3)
circuit.h(0)
circuit.h(1)
circuit.x(2)
circuit.crz(math.pi,1,2)
circuit.draw(output="mpl")
statevec,counts = do_job(circuit)
plot_bloch_multivector(statevec)
|
https://github.com/usamisaori/qLipschitz
|
usamisaori
|
from sklearn.datasets import load_iris
import pennylane as qml
import numpy as np
from pennylane.optimize import AdamOptimizer
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
X, Y = load_iris(return_X_y=True)
X_train_0 = X[0:30]
X_train_1 = X[50:80]
X_train = np.vstack((X_train_0, X_train_1))
Y_train_0 = Y[0:30]
Y_train_1 = Y[50:80]
Y_train = np.vstack((Y_train_0, Y_train_1)).flatten()
X, Y = load_iris(return_X_y=True)
X_test_0 = X[30:50]
X_test_1 = X[80:100]
X_test = np.vstack((X_test_0, X_test_1))
Y_test_0 = Y[30:50]
Y_test_1 = Y[80:100]
Y_test = np.vstack((Y_test_0, Y_test_1)).flatten()
X_train = (X_train - X_train.min(axis=0)) / (X_train.max(axis=0) - X_train.min(axis=0))
X_test = (X_test - X_test.min(axis=0)) / (X_test.max(axis=0) - X_test.min(axis=0))
qubits_num = 4
layers_num = 2
dev = qml.device("default.qubit", wires=qubits_num)
class VQC:
def __init__(self):
# 3 => U3(theta, phi, lambda)
self.params = (0.1 * np.random.randn(layers_num, qubits_num, 3))
self.bestparams = self.params
self.bestcost = 10
self.opt = AdamOptimizer(0.125)
self.weights = []
self.costs = []
self.accuracies = []
def fit(self, X_train, Y_train, epoch=300):
batch_size = 20
for turn in range(epoch):
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X_train), (batch_size,))
X_train_batch = X_train[batch_index]
Y_train_batch = Y_train[batch_index]
self.params = self.opt.step(lambda v: cost(v, X_train_batch, Y_train_batch), self.params)
cost_now = cost(self.params, X_train, Y_train)
acc_now = accuracy(self.params, X_train, Y_train)
if cost_now < self.bestcost:
self.bestcost = cost_now
self.bestparams = self.params
self.weights.append(self.params)
self.costs.append(cost_now)
self.accuracies.append(acc_now)
print(
"Turn: {:5d} | Cost: {:0.7f} | Accuracy: {:0.2f}% ".format(
turn, cost_now, acc_now * 100
))
def score(self, X_test, Y_test):
predictions = [ predict(self.bestparams, data) for data in X_test ]
acc = accuracy(self.bestparams, X_test, Y_test)
print("FINAL ACCURACY: {:0.2f}%".format(acc * 100))
@qml.qnode(dev)
def circuit(params, data):
angles = [ i * np.pi for i in data ]
for i in range(qubits_num):
qml.RX(angles[i], wires=i)
qml.Rot( *params[0, i], wires=i )
qml.CZ(wires=[1, 0])
qml.CZ(wires=[1, 2])
qml.CZ(wires=[2, 3])
qml.CZ(wires=[0, 3])
for i in range(qubits_num):
qml.Rot( *params[1, i], wires=i )
# PauliZ measure => 1 -> |0> while -1 -> |1>
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2)), qml.expval(qml.PauliZ(3))
def cost(weights, datas, labels):
loss = 0
for i, data in enumerate(datas):
# like [-1, 1, 1]
measured = circuit(weights, data)
p = measured[0]
if labels[i] == 0:
loss += (1 - p) ** 2
else:
loss += (-1 - p) ** 2
return loss / len(datas)
import qiskit
import numpy as np
from qiskit import QuantumCircuit
from qiskit import Aer, execute
unitary_backend = Aer.get_backend('unitary_simulator')
qasm_backend = Aer.get_backend('qasm_simulator')
def predict(params, data):
qcircuit = QuantumCircuit(4, 4)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
qcircuit.u3(*params[0][i], qubits[i])
qcircuit.cz(qubits[0], qubits[1])
qcircuit.cz(qubits[1], qubits[2])
qcircuit.cz(qubits[2], qubits[3])
qcircuit.cz(qubits[0], qubits[3])
for i in range(qubits_num):
qcircuit.u3(*params[1][i], qubits[i])
# the measurement
qcircuit.measure([0, 1, 2, 3], [0, 1, 2, 3])
# job execution
shots = 1000
job_sim = execute(qcircuit, qasm_backend, shots=shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(qcircuit)
p1 = (counts.get('1000', 0) + counts.get('1001', 0) + counts.get('1010', 0) + counts.get('1011',0) + \
counts.get('1100', 0) + counts.get('1101', 0) + counts.get('1110', 0) + counts.get('1111', 0)) / shots
if p1 > 0.5:
return 1
else:
return 0
def accuracy(weights, datas, labels):
predictions = [ predict(weights, data) for data in datas ]
acc = 0
for i, p in enumerate(predictions):
if p == labels[i]:
acc += 1
return acc / len(predictions)
vqc = VQC()
vqc.fit(X_train, Y_train, epoch=10)
vqc.score(X_test, Y_test)
vqc.bestparams
def createCircuit(params, data):
qcircuit = QuantumCircuit(4, 4)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
qcircuit.u3(*params[0][i], qubits[i])
qcircuit.cz(qubits[0], qubits[1])
qcircuit.cz(qubits[1], qubits[2])
qcircuit.cz(qubits[2], qubits[3])
qcircuit.cz(qubits[0], qubits[3])
for i in range(qubits_num):
qcircuit.u3(*params[1][i], qubits[i])
return qcircuit
qcircuit = createCircuit(vqc.bestparams, X_train[0])
qcircuit.draw(output='mpl')
|
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
|
bayesian-randomized-benchmarking
|
#Import general libraries (needed for functions)
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
#Import Qiskit classes
import qiskit
import qiskit_experiments as qe
rb = qe.randomized_benchmarking
from scipy.optimize import curve_fit
# import the bayesian packages
import pymc3 as pm
import arviz as az
import bayesian_fitter as bf
# initialize the Bayesian extension
%config InlineBackend.figure_format = 'retina'
# Initialize random number generator
RANDOM_SEED = 8927
np.random.seed(RANDOM_SEED)
az.style.use("arviz-darkgrid")
# choice of "simulation, "real", "retrieve"
option = "simulation"
# Determine the backend
if option == "simulation":
from qiskit.test.mock import FakeAthens
backend = FakeAthens()
hardware = 'ibmq_athens' # hardware reference
else:
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
device = provider.get_backend('ibmq_athens')
backend = device
hardware = device.name() # hardware used
# RB design
q_list = [0]
lengths = [1, 50, 100, 200, 300, 400, 500, 600, 800, 1000]
num_samples = 5
seed = 1010
num_qubits = len(q_list)
scale = (2 ** num_qubits - 1) / (2 ** num_qubits)
shots = 1024
if option != "retrieve":
exp = rb.RBExperiment(q_list, lengths, num_samples=num_samples, seed=seed)
eda= exp.run(backend)
# obtain EPC from alpha (used by plot_posterior)
def alpha_to_EPC(alpha):
return scale*(1-alpha)
# one or two qubits for retrieve and for the plots
list_bitstring = ['0', '00']
# obtain the current count values
Y_list = []
if option == "simulation":
for i_sample in range(num_samples*len(lengths)):
Y_list.append(eda.data[i_sample]['counts']\
[eda.data[i_sample]['metadata']['ylabel']])
else: # specify job (fresh job or run some time ago)
job = backend.retrieve_job('6097aed0a4885edfb19508fa') # athens 01'
for rbseed, result in enumerate(job.result().get_counts()):
total_counts = 0
for key,val in result.items():
if key in list_bitstring:
total_counts += val
Y_list.append(total_counts)
Y = np.array(Y_list).reshape(num_samples, len(lengths))
#get LSF EPC and priors
if option != "retrieve":
popt = eda._analysis_results[0]['popt']
pcov = eda._analysis_results[0]['pcov']
else: # manual entry (here for job ''6097aed0a4885edfb19508fa')
popt = [0.7207075, 0.95899375, 0.2545933 ]
pcov = [[ 2.53455272e-04, -9.10001034e-06, -1.29839515e-05],
[-9.10001034e-06, 9.55193998e-06, -7.07822420e-06],
[-1.29839515e-05, -7.07822420e-06, 2.07452483e-05]]
alpha_ref=popt[1]
mu_AB= [popt[0],popt[2]]
alpha_ref_err = np.sqrt(pcov[1][1])
EPC = scale*(1-alpha_ref)
EPC_err = scale*alpha_ref_err
cov_AB= [0.0001, 0.0001]
alpha_lower=0.8
alpha_upper=0.999
sigma_theta = .004
pooled_model = bf.get_bayesian_model(model_type="pooled",
Y=Y,shots=1024,m_gates=lengths,
alpha_ref = alpha_ref,
mu_AB=mu_AB,cov_AB=cov_AB)
pm.model_to_graphviz(pooled_model)
with pooled_model:
trace_p= pm.sample(draws = 2000, tune= 10000, target_accept=0.97,
return_inferencedata=True)
az.plot_trace(trace_p)
with pooled_model:
azp_summary = az.summary(trace_p, hdi_prob=.94, round_to=6, kind="all")
azp_summary
epc_p =scale*(1 - azp_summary['mean']['alpha'])
epc_p_err = scale* (azp_summary['sd']['alpha'])
with pooled_model:
ax = az.plot_posterior(trace_p, var_names=['alpha'], round_to=4, point_estimate=None,
transform = alpha_to_EPC, textsize = 10.0, color='b')
ax.set_title("RB_process: standard "+str(q_list)+", backend: "+backend.name(),
fontsize=12)
Bayes_legend ="Bayesian Pooled Model:\n EPC {0:1.3e} ± {1:1.3e}".format(epc_p, epc_p_err)
ax.axvline(x=EPC,color='r',ls=":")
Fitter_legend ="Frequentist model:\n EPC {0:1.3e} ± {1:1.3e}".format(EPC, EPC_err)
ax.legend((Bayes_legend, "$Highest\; density\; interval$ HDI",
Fitter_legend),fontsize=10 )
hierarchical_model = bf.get_bayesian_model(model_type="hierarchical",
Y=Y,shots=1024,m_gates=lengths,
alpha_ref = alpha_ref,
mu_AB=mu_AB,cov_AB=cov_AB)
pm.model_to_graphviz(hierarchical_model)
with hierarchical_model:
trace_h= pm.sample(draws = 2000, tune= 10000, target_accept=0.99,
return_inferencedata=True)
az.plot_trace(trace_h)
with hierarchical_model:
azh_summary = az.summary(trace_h, hdi_prob=.94, round_to=6,
kind="all", var_names=["~GSP"])
azh_summary
epc_h =scale*(1 - azh_summary['mean']['alpha'])
epc_h_err = scale* (azh_summary['sd']['alpha'])
with hierarchical_model:
ax = az.plot_posterior(trace_h, var_names=['alpha'], round_to=4, point_estimate=None,
transform = alpha_to_EPC, textsize = 10.0, color='b')
ax.set_title("RB_process: standard "+str(q_list)+", backend: "+backend.name(),
fontsize=12)
Bayes_legend ="Bayesian Hierarchical Model:\n EPC {0:1.3e} ± {1:1.3e}".format(epc_h, epc_h_err)
ax.axvline(x=EPC,color='r',ls=":")
Fitter_legend ="Frequentist model:\n EPC {0:1.3e} ± {1:1.3e}".format(EPC, EPC_err)
ax.legend((Bayes_legend, "$Highest\; density\; interval$ HDI",
Fitter_legend),fontsize=10 )
# compare LSF and SMC
print("Model: Frequentist Bayesian")
print(" LSF pooled hierarchical")
print("EPC {0:.5f} {1:.5f} {2:.5f}"
.format(EPC, epc_p, epc_h))
print("ERROR ± {0:.5f} ± {1:.5f} ± {2:.5f}"
.format(EPC_err, epc_p_err, epc_h_err))
import matplotlib.pyplot as plt # seems we need to reimport for replot WIP
#fig, plt = plt.subplots(1, 1, sharex=True, figsize=(10, 6))
fig, plt = plt.subplots(1, 1, sharex=True, figsize=(10, 6))
plt.set_ylabel("Ground State Population")
plt.set_xlabel("Number of Cliffords")
for i_seed in range(num_samples):
plt.scatter(lengths, Y[i_seed,:]/1024, label = "data",
marker="+",color="purple")
plt.plot(np.array(lengths)-0.5,azp_summary['mean']['AB[0]']\
*azp_summary['mean']['alpha']**lengths+\
azp_summary['mean']['AB[1]']-0.002,'o-',color="c")
plt.plot(np.array(lengths)+0.5,azh_summary['mean']['AB[0]']\
*azh_summary['mean']['alpha']**\
lengths+azh_summary['mean']['AB[1]']+0.002,'o-',color="orange")
plt.legend(("Pooled Model",
"Hierarchical Model"))
plt.set_title("RB_process: standard "+str(q_list)+\
", device: "+hardware+', backend: '+backend.name(),
fontsize=14);
# Leave-one-out Cross-validation (LOO) comparison
df_comp_loo = az.compare({"hierarchical": trace_h, "pooled": trace_p})
df_comp_loo
az.plot_compare(df_comp_loo, insample_dev=False);
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/OscarCharlieST/QISKIT_lab
|
OscarCharlieST
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer
from qiskit.tools.visualization import circuit_drawer
from qiskit import Aer
import matplotlib.pyplot as plt
import math
import numpy as np
import time
import pandas as pd
from tqdm import tqdm
#Function that returns the expectation value of a measurement
def get_expectation(circuit,backend,logshots):
job = execute(circuit, backend,shots=2**logshots)
counts = job.result().get_counts(circuit)
runtime = job.result().time_taken
keys = list(counts.keys())
if set(keys) == set(['0','1']):
return (counts['0']-counts['1'])/(counts['0']+counts['1']) , runtime
elif keys == ['0']:
return 1.0, runtime
elif keys == ['1']:
return -1.0, runtime
#Given an angle phi determines the state in our defined set of states
def initial_state(phi):
state = math.cos(phi)*np.array([1,0]) + 1j*math.sin(phi)* np.array([0,1])
return state
#Given data as a csv file and shots, returns histogram comparing the results with the true value of the expectation
#value and the mean of each method
def exp_value_histogram(data, state, shots,backend, mean=0.0, save = False):
#data = pd.read_csv(f'{backend}_state_1.csv')
M1 = data['Method 1']
M2 = data['Method 2']
n_simulations = len(M1)
fig1, ax1 = plt.subplots(figsize=(8,5))
bins=np.histogram(np.hstack((M1,M2)), bins=40)[1]
ax1.hist(M1, bins, color='b', alpha=0.5, label=f'method 1')
ax1.hist(M2, bins, color='r', alpha=0.5, label=f'method 2')
ax1.axvline(mean, linestyle='-', c='g', label='True value')
ax1.axvline(np.mean(M1), linestyle='-', c='b', label='Method 1 mean')
ax1.axvline(np.mean(M2), linestyle='-', c='r', label='Method 2 mean')
ax1.set_xlabel(r'Estimate of $\langle M\rangle$')
ax1.set_ylabel('Frequency')
ax1.set_title(f'Results of {n_simulations} simulations of {2**shots} shots for {state} on {backend}')
ax1.legend()
if save == True:
fig1.savefig(f'figures/{state}_{backend}.png')
def time_benchmarking(M1,M2,t1,t2,shots,exp_value):
fig, axs = plt.subplots(1,2,figsize=(16,5))
axs[0].plot(shots,t1, label='method 1')
axs[0].plot(shots,t2, label='method 2')
axs[0].set_xlabel('Number of shots')
axs[0].set_ylabel('Time taken')
axs[0].legend()
axs[1].scatter(shots,M1, label='method 1')
axs[1].scatter(shots,M2, label='method 2')
axs[1].axhline(exp_value, label='expected value', c=(.7,.7,.7))
axs[1].set_xlabel('Number of shots (log_2 scale)')
axs[1].set_ylabel('Expectation value of M')
axs[1].set_ylim([min(M1+M2)-0.05,max(M1+M2)+0.05])
axs[1].legend()
# Method 1 - apply HU^dagger(theta) and measure Z
#Build the cirquit
def method_1_circuit(theta, phi):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circuit = QuantumCircuit(qr, cr)
circuit.initialize(initial_state(phi), qr[0])
circuit.p(-theta, qr[0])
circuit.h(qr[0])
circuit.measure(qr[0],cr[0])
return circuit
circuit_drawer(method_1_circuit(theta=math.pi/8, phi=math.pi/4))
# Method 2
# M(theta) = cos(theta)X + sin(theta)Y
# alpha = cos(theta) ; beta = sin(theta)
#Build the cirquits
#Measure X expectation value circuit
def method_2_X_circuit(theta,phi):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circuit = QuantumCircuit(qr, cr)
circuit.initialize(initial_state(phi), qr[0])
circuit.h(qr[0])
circuit.measure(qr[0],cr[0])
circuit_drawer(circuit)
return circuit
circuit_drawer(method_2_X_circuit(theta=math.pi/4, phi=0))
def method1(theta,phi,backend,shots):
circuit = method_1_circuit(theta, phi)
return get_expectation(circuit,backend,shots)
#Measure Y expectation value circuit
def method_2_Y_circuit(theta,phi):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circuit = QuantumCircuit(qr, cr)
circuit.initialize(initial_state(phi), qr[0])
circuit.p(-math.pi/2,qr[0])
circuit.h(qr[0])
circuit.measure(qr[0],cr[0])
circuit_drawer(circuit)
return circuit
circuit_drawer(method_2_Y_circuit(theta=math.pi/4, phi=0))
def method2(theta,phi,backend,shots):
'''
Output: expectation value, job status of circuit X, job status of circuit Y
'''
circuit_X = method_2_X_circuit(theta, phi)
expectation_X, runtime_X = get_expectation(circuit_X,backend,shots)
circuit_Y = method_2_Y_circuit(theta,phi)
expectation_Y, runtime_Y = get_expectation(circuit_Y,backend,shots)
expectation_M = math.cos(theta)*expectation_X + math.sin(theta)*expectation_Y
return expectation_M, runtime_X + runtime_Y
#Establish number of simulations, shots and backend simulator
n_simulations = 500
shots = 10 #log scale
backend = Aer.get_backend('qasm_simulator')
#State 1
theta_1=math.pi/4
phi_1=0
method_1_state_1 = []
runtime_method_1_state_1 = []
for n in tqdm(range(n_simulations)):
exp_value,runtime = method1(theta_1,phi_1,backend,shots)
method_1_state_1.append(exp_value)
runtime_method_1_state_1.append(runtime)
m1_dict = {'Method 1':method_1_state_1, 'Method 1 runtime':runtime_method_1_state_1}
pd.DataFrame(m1_dict).to_csv(f'{backend}_state_1.csv')
method_2_state_1 = []
runtime_method_2_state_1 = []
for n in tqdm(range(n_simulations)):
exp_value,runtime = method2(theta_1,phi_1,backend,shots)
method_2_state_1.append(exp_value)
runtime_method_2_state_1.append(runtime)
m1_dict.update({'Method 2':method_2_state_1, 'Method 2 runtime':runtime_method_2_state_1})
pd.DataFrame(m1_dict).to_csv(f'{backend}_state_1.csv')
#State 2
theta_2=math.pi/8
phi_2=math.pi/4
method_1_state_2 = []
runtime_method_1_state_2 = []
for n in tqdm(range(n_simulations)):
exp_value, runtime = method1(theta_2,phi_2,backend,shots)
method_1_state_2.append(exp_value)
runtime_method_1_state_2.append(runtime)
m2_dict = {'Method 1':method_1_state_2,'Method runtime':runtime_method_1_state_2}
pd.DataFrame(m2_dict).to_csv(f'{backend}_state_2.csv')
method_2_state_2 = []
runtime_method_2_state_2 = []
for n in tqdm(range(n_simulations)):
exp_value, runtime = method2(theta_2,phi_2,backend,shots)
method_2_state_2.append(exp_value)
runtime_method_2_state_2.append(runtime)
m2_dict.update({'Method 2':method_2_state_2,'Method 2 runtime':runtime_method_2_state_2})
pd.DataFrame(m2_dict).to_csv(f'{backend}_state_2.csv')
state_1_data = pd.read_csv(f'{backend}_state_1.csv')
state_1 = r'$\theta=\pi/4, \phi=0$'
exp_value_histogram(state_1_data, 'state_1', shots,backend, save = True)
state_2_data = pd.read_csv(f'{backend}_state_2.csv')
state_2 = r'$\theta=\pi/8, \phi=\pi/4$'
exp_value_histogram(state_2_data, 'state_2', shots,backend, mean=0.3827, save = True)
shots = np.arange(1000, 100000, 1000)
shots_log = list(map(lambda x: math.log(x,2), shots))
method_1_state_1 = []
runtime_method_1_state_1 = []
for s in tqdm(shots_log):
exp_value,runtime = method1(theta_1,phi_1,backend,s)
method_1_state_1.append(exp_value)
runtime_method_1_state_1.append(runtime)
method_2_state_1 = []
runtime_method_2_state_1 = []
for s in tqdm(shots_log):
exp_value,runtime = method2(theta_1,phi_1,backend,s)
method_2_state_1.append(exp_value)
runtime_method_2_state_1.append(runtime)
time_benchmarking(method_1_state_1, method_2_state_1,runtime_method_1_state_1,runtime_method_2_state_1,shots,0)
tps_1 = np.mean(np.array(runtime_method_1_state_1)/np.array(shots))
tps_2 = np.mean(np.array(runtime_method_2_state_1)/np.array(shots))
print('Ratio of time taken (method 2:method 1) = ', round(tps_2/tps_1, 3))
shots_std = np.linspace(500,2000,15)
shots_log = list(map(lambda x: math.log(x,2), shots_std))
n_simulations = 50
std1 = []
rt1 = []
for s in tqdm(shots_log):
method_1_state_1 = []
runtime_method_1_state_1 = []
for i in range(n_simulations):
exp_value,runtime = method1(theta_1,phi_1,backend,s)
method_1_state_1.append(exp_value)
runtime_method_1_state_1.append(runtime)
std1.append(np.std(method_1_state_1))
rt1.append(np.mean(runtime_method_1_state_1))
std2 = []
rt2 = []
for s in tqdm(shots_log):
method_2_state_1 = []
runtime_method_2_state_1 = []
for i in range(n_simulations):
exp_value,runtime = method2(theta_1,phi_1,backend,s)
method_2_state_1.append(exp_value)
runtime_method_2_state_1.append(runtime)
std2.append(np.std(method_2_state_1))
rt2.append(np.mean(runtime_method_2_state_1))
fig, axs = plt.subplots(1,2,figsize=(16,5))
axs[0].plot(shots_std,rt1, label='method 1', c='r')
axs[0].plot(shots_std,rt2, label='method 2', c='b')
axs[0].set_xlabel('Number of shots')
axs[0].set_ylabel('Mean time taken')
axs[0].legend()
rt_s = np.sqrt(1/np.array(shots_std))
axs[1].scatter(rt_s, std1, label='method 1', c='r')
axs[1].plot(rt_s, rt_s*np.polyfit(rt_s, std1,1)[0]+ np.polyfit(rt_s, std1,1)[1],
c='r', alpha=.5, label='m='+str(round(np.polyfit(rt_s, std1,1)[0],3)))
axs[1].scatter(rt_s, std2, label='method 2', c='b')
axs[1].plot(rt_s, rt_s*np.polyfit(rt_s, std2,1)[0]+ np.polyfit(rt_s, std2,1)[1],
c='b', alpha=.5, label='m='+str(round(np.polyfit(rt_s, std2,1)[0],3)))
axs[1].set_xlabel(r'shots$^{-1/2}$')
axs[1].set_ylabel(r'$\Delta\langle M\rangle$')
axs[1].legend()
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
mykey = 'd0db27e06149ec7280499124f8a6a11cf87d70d35c06147d3f70a8f9c0ae5a136f33ae887c14b0b44c10c1dc64e3249cc89aa7104fc3e01c940a3e1f1dead7fc'
IBMQ.save_account(mykey)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
small_devices = provider.backends(filters=lambda x: x.configuration().n_qubits == 5
and not x.configuration().simulator)
backend=least_busy(small_devices)
print(backend)
n_simulations = 20
shots = 10 #log scale
#State 1
theta_1=math.pi/4
phi_1=0
method_1_state_1 = []
runtime_method_1_state_1 = []
for n in tqdm(range(n_simulations)):
exp_value,runtime = method1(theta_1,phi_1,backend,shots)
method_1_state_1.append(exp_value)
runtime_method_1_state_1.append(runtime)
m1_dict = {'Method 1':method_1_state_1, 'Method 1 runtime':runtime_method_1_state_1}
pd.DataFrame(m1_dict).to_csv(f'{backend}_state_1.csv')
method_2_state_1 = []
runtime_method_2_state_1 = []
for n in tqdm(range(n_simulations)):
exp_value,runtime = method2(theta_1,phi_1,backend,shots)
method_2_state_1.append(exp_value)
runtime_method_2_state_1.append(runtime)
m1_dict.update({'Method 2':method_2_state_1, 'Method 2 runtime':runtime_method_2_state_1})
pd.DataFrame(m1_dict).to_csv(f'{backend}_state_1.csv')
#State 2
theta_2=math.pi/8
phi_2=math.pi/4
method_1_state_2 = []
runtime_method_1_state_2 = []
for n in tqdm(range(n_simulations)):
exp_value, runtime = method1(theta_2,phi_2,backend,shots)
method_1_state_2.append(exp_value)
runtime_method_1_state_2.append(runtime)
m2_dict = {'Method 1':method_2_state_1,'Method 1 runtime':runtime_method_1_state_2}
pd.DataFrame(m2_dict).to_csv(f'{backend}_state_2.csv')
method_2_state_2 = []
runtime_method_2_state_2 = []
for n in tqdm(range(n_simulations)):
exp_value, runtime = method2(theta_2,phi_2,backend,shots)
method_2_state_2.append(method2(exp_value))
runtime_method_2_state_2.append(runtime)
m2_dict.update({'Method 2':method_2_state_2,'Method 2 runtime':runtime_method_2_state_2})
pd.DataFrame(m2_dict).to_csv(f'{backend}_state_2.csv')
n_simulations = 20
shots = 10 #log scale
backend = 'ibmq_belem'
state_1_data = pd.read_csv(f'{backend}_state_1.csv')
state_1 = r'$\theta=\pi/4, \phi=0$'
exp_value_histogram(state_1_data, 'state_1', shots,backend, save = True)
state_2_data = pd.read_csv(f'{backend}_state_2.csv')
state_2 = r'$\theta=\pi/8, \phi=\pi/4$'
exp_value_histogram(state_2_data, 'state_2', shots,backend, mean=0.3827, save = True)
#State 1
runtime_method_1_state_1_mean = np.mean(state_1_data['Method 1 runtime'])
print(f'The mean runtime for method 1 for state 1 is: {runtime_method_1_state_1_mean} s')
runtime_method_2_state_1_mean = np.mean(state_1_data['Method 2 runtime'])
print(f'The mean runtime for method 2 for state 1 is: {runtime_method_2_state_1_mean} s')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
from qiskit import *
import numpy as np
%matplotlib inline
from matplotlib import style
style.use('bmh')
style.use('dark_background')
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
display(oracle_qc.draw('mpl'))
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('constant', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw('mpl')
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
results = execute(dj_circuit, backend=backend, shots=1024).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_ourense')
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3)
job_monitor(job)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Import requisite modules
import math
import datetime
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Import Qiskit packages
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit_aer.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
# The data providers of stock-market data
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_finance.applications.optimization import PortfolioDiversification
# Generate a pairwise time-series similarity matrix
seed = 123
stocks = ["TICKER1", "TICKER2"]
n = len(stocks)
data = RandomDataProvider(
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=seed,
)
data.run()
rho = data.get_similarity_matrix()
q = 1 # q less or equal than n
class ClassicalOptimizer:
def __init__(self, rho, n, q):
self.rho = rho
self.n = n # number of inner variables
self.q = q # number of required selection
def compute_allowed_combinations(self):
f = math.factorial
return int(f(self.n) / f(self.q) / f(self.n - self.q))
def cplex_solution(self):
# refactoring
rho = self.rho
n = self.n
q = self.q
my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)]
my_ub = [1 for x in range(0, n**2 + n)]
my_lb = [0 for x in range(0, n**2 + n)]
my_ctype = "".join(["I" for x in range(0, n**2 + n)])
my_rhs = (
[q]
+ [1 for x in range(0, n)]
+ [0 for x in range(0, n)]
+ [0.1 for x in range(0, n**2)]
)
my_sense = (
"".join(["E" for x in range(0, 1 + n)])
+ "".join(["E" for x in range(0, n)])
+ "".join(["L" for x in range(0, n**2)])
)
try:
my_prob = cplex.Cplex()
self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs)
my_prob.solve()
except CplexError as exc:
print(exc)
return
x = my_prob.solution.get_values()
x = np.array(x)
cost = my_prob.solution.get_objective_value()
return x, cost
def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs):
n = self.n
prob.objective.set_sense(prob.objective.sense.minimize)
prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype)
prob.set_log_stream(None)
prob.set_error_stream(None)
prob.set_warning_stream(None)
prob.set_results_stream(None)
rows = []
col = [x for x in range(n**2, n**2 + n)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [x for x in range(0 + n * ii, n + n * ii)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [ii * n + ii, n**2 + ii]
coef = [1, -1]
rows.append([col, coef])
for ii in range(0, n):
for jj in range(0, n):
col = [ii * n + jj, n**2 + jj]
coef = [1, -1]
rows.append([col, coef])
prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs)
# Instantiate the classical optimizer class
classical_optimizer = ClassicalOptimizer(rho, n, q)
# Compute the number of feasible solutions:
print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations()))
# Compute the total number of possible combinations (feasible + unfeasible)
print("Total number of combinations= " + str(2 ** (n * (n + 1))))
# Visualize the solution
def visualize_solution(xc, yc, x, C, n, K, title_str):
plt.figure()
plt.scatter(xc, yc, s=200)
for i in range(len(xc)):
plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r")
plt.grid()
for ii in range(n**2, n**2 + n):
if x[ii] > 0:
plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20)
for ii in range(0, n**2):
if x[ii] > 0:
iy = ii // n
ix = ii % n
plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2")
plt.title(title_str + " cost = " + str(int(C * 100) / 100.0))
plt.show()
from qiskit.utils import algorithm_globals
class QuantumOptimizer:
def __init__(self, rho, n, q):
self.rho = rho
self.n = n
self.q = q
self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q)
self.qp = self.pdf.to_quadratic_program()
# Obtains the least eigenvalue of the Hamiltonian classically
def exact_solution(self):
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(self.qp)
return self.decode_result(result)
def vqe_solution(self):
algorithm_globals.random_seed = 100
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(self.qp)
return self.decode_result(result)
def qaoa_solution(self):
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(self.qp)
return self.decode_result(result)
def decode_result(self, result, offset=0):
quantum_solution = 1 - (result.x)
ground_level = self.qp.objective.evaluate(result.x)
return quantum_solution, ground_level
# Instantiate the quantum optimizer class with parameters:
quantum_optimizer = QuantumOptimizer(rho, n, q)
# Check if the binary representation is correct. This requires CPLEX
try:
import cplex
# warnings.filterwarnings('ignore')
quantum_solution, quantum_cost = quantum_optimizer.exact_solution()
print(quantum_solution, quantum_cost)
classical_solution, classical_cost = classical_optimizer.cplex_solution()
print(classical_solution, classical_cost)
if np.abs(quantum_cost - classical_cost) < 0.01:
print("Binary formulation is correct")
else:
print("Error in the formulation of the Hamiltonian")
except Exception as ex:
print(ex)
ground_state, ground_level = quantum_optimizer.exact_solution()
print(ground_state)
classical_cost = 1.000779571614484 # obtained from the CPLEX solution
try:
if np.abs(ground_level - classical_cost) < 0.01:
print("Ising Hamiltonian in Z basis is correct")
else:
print("Error in the Ising Hamiltonian formulation")
except Exception as ex:
print(ex)
vqe_state, vqe_level = quantum_optimizer.vqe_solution()
print(vqe_state, vqe_level)
try:
if np.linalg.norm(ground_state - vqe_state) < 0.01:
print("SamplingVQE produces the same solution as the exact eigensolver.")
else:
print(
"SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected."
)
except Exception as ex:
print(ex)
xc, yc = data.get_coordinates()
visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical")
visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import *
from qiskit.circuit import Gate
my_gate = Gate(name='my_gate', num_qubits=2, params=[])
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.append(my_gate, [qr[0], qr[1]])
circ.append(my_gate, [qr[1], qr[2]])
circ.draw()
# Build a sub-circuit
sub_q = QuantumRegister(2)
sub_circ = QuantumCircuit(sub_q, name='sub_circ')
sub_circ.h(sub_q[0])
sub_circ.crz(1, sub_q[0], sub_q[1])
sub_circ.barrier()
sub_circ.id(sub_q[1])
sub_circ.u(1, 2, -2, sub_q[0])
# Convert to a gate and stick it into an arbitrary place in the bigger circuit
sub_inst = sub_circ.to_instruction()
qr = QuantumRegister(3, 'q')
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.cx(qr[1], qr[2])
circ.append(sub_inst, [qr[1], qr[2]])
circ.draw()
decomposed_circ = circ.decompose() # Does not modify original circuit
decomposed_circ.draw()
from qiskit.circuit import Parameter
theta = Parameter('θ')
n = 5
qc = QuantumCircuit(5, 1)
qc.h(0)
for i in range(n-1):
qc.cx(i, i+1)
qc.barrier()
qc.rz(theta, range(5))
qc.barrier()
for i in reversed(range(n-1)):
qc.cx(i, i+1)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
print(qc.parameters)
import numpy as np
theta_range = np.linspace(0, 2 * np.pi, 128)
circuits = [qc.bind_parameters({theta: theta_val})
for theta_val in theta_range]
circuits[-1].draw()
backend = BasicAer.get_backend('qasm_simulator')
job = backend.run(transpile(circuits, backend))
counts = job.result().get_counts()
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
ax.plot(theta_range, list(map(lambda c: c.get('0', 0), counts)), '.-', label='0')
ax.plot(theta_range, list(map(lambda c: c.get('1', 0), counts)), '.-', label='1')
ax.set_xticks([i * np.pi / 2 for i in range(5)])
ax.set_xticklabels(['0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'], fontsize=14)
ax.set_xlabel('θ', fontsize=14)
ax.set_ylabel('Counts', fontsize=14)
ax.legend(fontsize=14)
import time
from itertools import combinations
from qiskit.compiler import assemble
from qiskit.test.mock import FakeVigo
start = time.time()
qcs = []
theta_range = np.linspace(0, 2*np.pi, 32)
for n in theta_range:
qc = QuantumCircuit(5)
for k in range(8):
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qc.rz(n, range(5))
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qcs.append(qc)
compiled_circuits = transpile(qcs, backend=FakeVigo())
qobj = assemble(compiled_circuits, backend=FakeVigo())
end = time.time()
print('Time compiling over set of bound circuits: ', end-start)
start = time.time()
qc = QuantumCircuit(5)
theta = Parameter('theta')
for k in range(8):
for i,j in combinations(range(5), 2):
qc.cx(i,j)
qc.rz(theta, range(5))
for i,j in combinations(range(5), 2):
qc.cx(i,j)
transpiled_qc = transpile(qc, backend=FakeVigo())
qobj = assemble([transpiled_qc.bind_parameters({theta: n})
for n in theta_range], backend=FakeVigo())
end = time.time()
print('Time compiling over parameterized circuit, then binding: ', end-start)
phi = Parameter('phi')
sub_circ1 = QuantumCircuit(2, name='sc_1')
sub_circ1.rz(phi, 0)
sub_circ1.rx(phi, 1)
sub_circ2 = QuantumCircuit(2, name='sc_2')
sub_circ2.rx(phi, 0)
sub_circ2.rz(phi, 1)
qc = QuantumCircuit(4)
qr = qc.qregs[0]
qc.append(sub_circ1.to_instruction(), [qr[0], qr[1]])
qc.append(sub_circ2.to_instruction(), [qr[0], qr[1]])
qc.append(sub_circ2.to_instruction(), [qr[2], qr[3]])
print(qc.draw())
# The following raises an error: "QiskitError: 'Name conflict on adding parameter: phi'"
# phi2 = Parameter('phi')
# qc.u3(0.1, phi2, 0.3, 0)
p = Parameter('p')
qc = QuantumCircuit(3, name='oracle')
qc.rz(p, 0)
qc.cx(0, 1)
qc.rz(p, 1)
qc.cx(1, 2)
qc.rz(p, 2)
theta = Parameter('theta')
phi = Parameter('phi')
gamma = Parameter('gamma')
qr = QuantumRegister(9)
larger_qc = QuantumCircuit(qr)
larger_qc.append(qc.to_instruction({p: theta}), qr[0:3])
larger_qc.append(qc.to_instruction({p: phi}), qr[3:6])
larger_qc.append(qc.to_instruction({p: gamma}), qr[6:9])
print(larger_qc.draw())
print(larger_qc.decompose().draw())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
The purpose of this notebook is to show how to use Qiskit's `Parameter` object to create and manipulated PQCs.
import sys
sys.path.append('../../Pyfiles')
import qiskit
qiskit.__qiskit_version__
from qiskit import QuantumCircuit, Aer
from qiskit.circuit import Parameter
import numpy as np
from sklearn.utils import shuffle
import matplotlib.pyplot as plt
%matplotlib inline
from optimizer import *
dataID = '2a'
dataPath = r'../../dataset/data{0}.txt'.format(dataID)
dataLabel = r'../../dataset/data{0}label.txt'.format(dataID)
dataCoords = np.loadtxt(dataPath)
dataLabels = np.loadtxt(dataLabel)
# Make a data structure which is easier to work with
# for shuffling.
# Also, notice we change the data labels from {0, 1} to {-1, +1}
data = list(zip(dataCoords, 2*dataLabels-1))
shuffled_data = np.array(shuffle(data), dtype='object')
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 0)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 0)])[1::2], ls='', marker='o')
ax.plot(np.ravel(dataCoords[np.where(dataLabels == 1)])[::2],
np.ravel(dataCoords[np.where(dataLabels == 1)])[1::2], ls='', marker='o')
shuffled_data
x0 = Parameter('x0')
x1 = Parameter('x1')
t0 = Parameter('t0')
t1 = Parameter('t1')
t2 = Parameter('t2')
t3 = Parameter('t3')
qc = QuantumCircuit(2)
qc.rx(x0, 0)
qc.rx(x1, 1)
qc.ry(np.pi/4, range(qc.width()))
qc.rz(np.pi/4, range(qc.width()))
qc.rx(t0, 0)
qc.rz(t1, 0)
qc.rx(t2, 1)
qc.rz(t3, 1)
qc.draw()
def calc_probs_from_results(counts, converter_dict):
r'''Given a Qiskit `counts` object (i.e., a dictionary containing
bitstrings and outcome probabilities), make an assignment to the
probabilities of a +/- 1 label.'''
probsPlus = 0
probsMinus = 0
for k in converter_dict.keys():
if converter_dict[k] == 1:
probsPlus += counts[k]
else:
probsMinus += counts[k]
return probsPlus, probsMinus
def label_assignment(probsPlus, probsMinus):
r'''Given the probabilities of +/- 1, declare the
label which should be assigned'''
if probsPlus > probsMinus:
label = 1
elif probsMinus > probsPlus:
label = -1
else:
# An edge case: if the probs are equal, just return a random label
label= 2*np.random.binomial(1, .5) -1
return label
def prediction_loss(label, prediction):
return np.abs(label - prediction)
def loss(params, paramNames, dataCircuits, converter_dict):
r'''Function which computes the loss.
Inputs:
params: The particular parameter values
paramNames: The name of the parameters
dataCircuits: List of partially-parameterized circuits
converter_dict: A dictionary representing how to map from bitstrings to labels
Outputs:
The loss
'''
# Bind the variables for the classifier part of the circuit
fully_bound_qcs = [d.bind_parameters(dict(zip(paramNames, params)))for d in dataCircuits]
# Run all the circuits
job = be.run(fully_bound_qcs)
# Get the counts
counts = job.result().get_counts()
# Now, calculate the probabilities of the +/- 1 outcome
probsList = [calc_probs_from_results(C, converter_dict) for C in list(counts)]
# Do the label assignment
predictions_list = [label_assignment(P[0], P[1]) for P in probsList]
# Calculate the loss on each data point
prediction_loss_list = [prediction_loss(data[j][1], predictions_list[j]) for j in range(len(predictions_list))]
# Sum it up and return
return np.sum(prediction_loss_list)
# Converter dictionary for 2-qubit circuit.
two_q_converter_dict = {'00': 1, '01': -1, '10': -1, '11': 1}
# We'll use the statevector simulator, to get the
# exact outcome probabilities.
be = Aer.get_backend('statevector_simulator')
#load the SPSA optimizer from the optimizer.py file
from optimizer import *
c = 1
a = c/5
currentParams = np.random.uniform(-np.pi, np.pi, size=4)
lossList = []
cList = []
aList = []
paramsList = []
for j in range(10):
print(j)
cj = c/(j+1)**(1/3)
aj = a/(j+1)
aList.append(aj)
cList.append(cj)
np.random.seed(j)
data_ixs = np.random.choice(len(shuffled_data), size=750)
data_set = shuffled_data[data_ixs]
# Generate a list of circuits whose parameters are partially bound,
# based on the data set.
dataCircuits = [qc.bind_parameters({x0:X[0][0], x1:X[0][1]}) for X in data_set]
# Use a lambda function to make a call to the loss function
# where the only thing which changes is the parameter values
# for the classification part of the circuit.
L = lambda x: loss(x, [t0, t1, t2, t3], dataCircuits, two_q_converter_dict)
lossList.append(L(currentParams))
# Update the parameters
currentParams = SPSA_update(L, currentParams, aj, cj)
paramsList.append(currentParams)
lossList.append(L(currentParams))
fig = plt.figure(figsize=(15, 10))
ax = fig.add_subplot(2, 2, 1)
ax.plot(lossList)
ax = fig.add_subplot(2, 2, 2)
ax.plot(aList, label='a')
ax.plot(cList, label='c')
ax.legend(loc=0)
ax.set_yscale('log')
ax = fig.add_subplot(2, 2, 4)
for j in range(len(paramsList[0])):
ax.plot([p[j] for p in paramsList], label='t{0}'.format(j))
ax.legend(loc=0)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import *
from qiskit.visualization import plot_histogram
# quantum circuit to make a Bell state
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
meas = QuantumCircuit(2, 2)
meas.measure([0,1], [0,1])
# execute the quantum circuit
backend = BasicAer.get_backend('qasm_simulator') # the device to run on
circ = bell.compose(meas)
result = backend.run(transpile(circ, backend), shots=1000).result()
counts = result.get_counts(circ)
print(counts)
plot_histogram(counts)
# Execute 2-qubit Bell state again
second_result = backend.run(transpile(circ, backend), shots=1000).result()
second_counts = second_result.get_counts(circ)
# Plot results with legend
legend = ['First execution', 'Second execution']
plot_histogram([counts, second_counts], legend=legend)
plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12),
color=['orange', 'black'], bar_labels=False)
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton
from qiskit.visualization import plot_state_qsphere
# execute the quantum circuit
backend = BasicAer.get_backend('statevector_simulator') # the device to run on
result = backend.run(transpile(bell, backend)).result()
psi = result.get_statevector(bell)
plot_state_city(psi)
plot_state_hinton(psi)
plot_state_qsphere(psi)
plot_state_paulivec(psi)
plot_bloch_multivector(psi)
plot_state_city(psi, title="My City", color=['black', 'orange'])
plot_state_hinton(psi, title="My Hinton")
plot_state_paulivec(psi, title="My Paulivec", color=['purple', 'orange', 'green'])
plot_bloch_multivector(psi, title="My Bloch Spheres")
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,1,0])
plot_bloch_vector([0,1,0], title='My Bloch Sphere')
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
# Checking the version of PYTHON; we only support > 3.5
import sys
if sys.version_info < (3,5):
raise Exception('Please use Python version 3.5 or greater.')
#Importing qiskit and math lib
from qiskit import QuantumProgram
import math
#import Qconfig
pi = math.pi
theta_list = [0.01, 0.02, 0.03, 0.04, 0.05, 1.31, 1.32, 1.33, 1.34, 1.35]
Q_program = QuantumProgram()
#Q_program.set_api(Qconfig.APItoken, Qconfig.config['url'])
def k_means():
# create Quantum Register called "qr" with 5 qubits
qr = Q_program.create_quantum_register("qr", 5)
# create Classical Register called "cr" with 5 bits
cr = Q_program.create_classical_register("cr", 5)
# Creating Quantum Circuit called "qc" involving your Quantum Register "qr"
# and your Classical Register "cr"
qc = Q_program.create_circuit("k_means", [qr], [cr])
#Define a loop to compute the distance between each pair of points
for i in range(9):
for j in range(1,10-i):
# Set the parament theta about different point
theta_1 = theta_list[i]
theta_2 = theta_list[i+j]
#Achieve the quantum circuit via qiskit
qc.h(qr[2])
qc.h(qr[1])
qc.h(qr[4])
qc.u3(theta_1, pi, pi, qr[1])
qc.u3(theta_2, pi, pi, qr[4])
qc.cswap(qr[2], qr[1], qr[4])
qc.h(qr[2])
qc.measure(qr[2], cr[2])
qc.reset(qr)
result = Q_program.execute("k_means", backend = 'local_qasm_simulator')
print(result)
print('theta_1:' + str(theta_1))
print('theta_2:' + str(theta_2))
print( result.get_data("k_means"))
#result = Q_program.execute(["reset"], backend='ibmqx4', shots=1024, timeout=600)
if __name__ == "__main__":
k_means()
%run "../version.ipynb"
|
https://github.com/nickk124/quantumsearch
|
nickk124
|
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
# provider = IBMQ.load_account()
from qiskit import *
from qiskit.providers.ibmq import least_busy
# imports
import qiskit
import math
# imports
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
%config InlineBackend.figure_format = 'svg' # Makes the images look nice
# import qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.visualization import plot_histogram, plot_state_city
# gates/operators
from qiskit.quantum_info.operators import Operator
from qiskit.extensions import UnitaryGate
qiskit.__qiskit_version__
# CONVERSION TOOLS
def int_to_binary(i, length): # returns binary string of int with some length
raw_str = "{0:b}".format(i)
return raw_str.zfill(length)
def get_binary_basis_vec(d, n): # returns vec e_d from equation 2, string form
# d is direction, n is number of dimensions/qubits
e_d = ''.zfill(n - 1 - d) + '1' + ''.zfill(d)
return e_d
def bitwise_xor(a, b):
# get bitwise addition/xor of two strings, length preserved
y = int(a, 2)^int(b,2)
return bin(y)[2:].zfill(len(a))
# VISUALIZATION TOOLS
def draw_circuit(self):
return self.circuit.draw('mpl')
def plot_states_hist(self): # plots by actually measuring the circuit
self.circuit.measure_all()
backend = Aer.get_backend('qasm_simulator')
shots = 1024 # number of times circuit is run, for sampling
results = execute(self.circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
return plot_histogram(answer)
def plot_states_3D(self): # plots current states in 3D
backend = Aer.get_backend('statevector_simulator') # the device to run on
results = execute(self.circuit, backend).result()
answer = result.get_statevector(self.circuit)
return plot_state_city(answer)
# CIRCUIT TOOLS
def get_n_qubits_coin(self):
# number of qubits needed for the coin/
# number of bits needed to specify direction in n-cube
return int(math.ceil(np.log2(self.n)))
def initialize_circuit(self): # initializes quantum computer
# need to initialize an equal superposition over all states
self.n_qubits_coin = get_n_qubits_coin(self) # qubits needed for coin
self.n_qubits_total = self.n + self.n_qubits_coin
coin_register = QuantumRegister(self.n_qubits_coin, 'coin')
cube_register = QuantumRegister(self.n, 'node')
circuit = QuantumCircuit(coin_register, cube_register)
for qubit in range(self.n_qubits_total):
circuit.h(qubit) # perform hadamard on each qubit
self.circuit_initialized = True
return circuit
def make_gates_n_2(self): # add one set of U' gates for n = 2 case
circ = self.circuit
# circ.h(0) // davis
# circ.ccx(0, 1, 2)
# circ.cx(0, 1)
# circ.x(0)
# circ.x(1)
# circ.ccx(0, 1, 2)
# circ.x(1)
# circ.cx(0, 1)
circ.ccx(0, 2, 1)
circ.ccx(1, 2, 0)
circ.x(0)
circ.ccx(0, 1, 2)
circ.x(0)
circ.x(2)
circ.ccx(1, 2, 0)
circ.ccx(0, 2, 1)
circ.x(1)
circ.ccx(1, 2, 0)
circ.x(1)
circ.x(2)
circ.ccx(1, 2, 0)
circ.x(0)
circ.ccx(0, 1, 2)
circ.x(0)
circ.x(2)
circ.ccx(1, 2, 0)
circ.x(2)
circ.ccx(0, 2, 1)
circ.ccx(1, 2, 0)
circ.x(0)
circ.ccx(0, 1, 2)
circ.x(0)
circ.x(1)
circ.ccx(1, 2, 0)
circ.x(1)
circ.ccx(0, 2, 1)
circ.ccx(1, 2, 0)
return
def perform_evolution_gates(self, tF): # use explicit gates, n-dependent
supported_qubit_counts = [2] # supported values for n
if self.n in supported_qubit_counts:
for it in range(tF):
make_gates_n_2(self)
else:
print("Error: n = {} qubits not currently supported\nfor explicit gate implementation.".format(self.n))
return
def perform_evolution_operators(self, tF): # use the qiskit Operator API
Uprime = get_perturbed_evolution_operator(self)
Uprime = UnitaryGate(Uprime,label="U'")
for it in range(tF):
self.circuit.unitary(Uprime, [i for i in range(self.n_qubits_total)], label="Uprime")
return
def perform_evolution(self, num_iters=None, use_operators=False): # perform step 2 of algorithm
if not self.circuit_initialized:
print("Error: initialize circuit first!")
return
if num_iters is None:
tF = math.ceil(np.pi * np.sqrt(self.N) / 2) # number of times to apply evolution op
else:
tF = num_iters
if use_operators:
perform_evolution_operators(self, tF)
else:
perform_evolution_gates(self, tF)
return self.draw_circuit()
# OPERATORS/GATES
def get_sC_matrix(self): # gets |s^C><s^C| matrix
sC_matrix = np.ones((self.n, self.n)) / n
return sC_matrix
def get_sC_operator(self):
sC_matrix = get_sC_matrix(self)
return Operator(sC_matrix)
def get_shift_matrix(self): # get matrix form of S operator
S = np.zeros((self.dim_U, self.dim_U))
# following equation 2 of the paper
for d in range(self.n): # sum over each cartesian direction
for x in range(self.N): # loop over each position on hypercube
d_str = int_to_binary(d, self.n_qubits_coin)
x_str = int_to_binary(x, self.n)
e_d_str = get_binary_basis_vec(d, self.n)
# print(d_str,x_str,e_d_str)
# binary string that shows row:
row_str = d_str + bitwise_xor(x_str, e_d_str)
# same, for col:
col_str = d_str + x_str
row_index = int(row_str, 2)
col_index = int(col_str, 2)
# print(row_index, col_index)
S[row_index][col_index] = 1
print(S)
return S
def get_shift_operator(self): # S operator, from the paper
# get matrix from of the operator
S_matrix = get_shift_matrix(self)
return Operator(S_matrix)
def get_c_matrices(self): #C matrix
grovers = np.full((self.n, self.n), 2/self.n)
np.fill_diagonal(grovers, 2/self.n-1)
coin_operator = np.kron(grovers, np.eye(self.N))
return grovers, coin_operator
def get_coin_matrix(self):
C_0, C = get_c_matrices(self)
tens1 = -np.eye(self.n)- C_0
tens2 = np.zeros((self.N,self.N)) # |000…00><000…00| term
tens2[1][1] = 1
right_term = np.kron(tens1, tens2)
return C+right_term
def get_perturbed_coin_operator(self): # C' operator, from the paper
coin_matrix = get_coin_matrix(self)
return Operator(coin_matrix)
def get_perturbed_evolution_matrix(self): # U' matrix in the paper
Cprime = get_coin_matrix(self)
S = get_shift_matrix(self)
return np.matmul(Cprime,S)
def get_perturbed_evolution_operator(self): # U' operator in the paper
S = get_shift_operator(self)
Cprime = get_perturbed_coin_operator(self)
#print(Cprime.data.shape)
#self.circuit.append(S)
Uprime = S.compose(Cprime, front=True)
return Uprime
class QRW:
# INITIALIZATION HELPERS
def __init__(self, num_qubits_cube):
self.n = num_qubits_cube # total number of qubits in cube; n-cube will have N = 2^n nodes
self.N = int(2**n)
self.dim_U = self.n * int(2**n) # no. of rows/cols for U/S/C
self.circuit = self.initialize_circuit()
# CIRCUIT TOOLS
initialize_circuit = initialize_circuit
perform_evolution = perform_evolution
# VISUALIZATION TOOLS
draw_circuit = draw_circuit
plot_states_hist = plot_states_hist
plot_states_3D = plot_states_3D
n = 2
qrw = QRW(n) # initialize computer
#qrw_instance.plot_states_hist()
qrw.perform_evolution()
qrw.draw_circuit()
#qrw.plot_states_hist()
qrw.plot_states_hist()
Uprime = get_perturbed_evolution_operator(qrw)
print(Uprime.data.shape)
circuit = QuantumCircuit(3)
from qiskit.extensions import UnitaryGate
uprime = get_perturbed_evolution_operator(qrw)
uprime = UnitaryGate(uprime,label="U'")
circuit.unitary(uprime, [0, 1, 2])
circuit.draw('mpl')
fig, axes = plt.subplots(1,3,figsize=(10,10))
S = get_shift_matrix(qrw)
sC = get_sC_matrix(qrw)
axes[0].imshow(S)
cprime = get_coin_matrix(qrw)
axes[1].imshow(np.real(cprime.data))
Uprime = get_perturbed_evolution_operator(qrw)
print(np.array(Uprime.data))
axes[2].imshow(np.real(Uprime.data))
plt.show()
from qiskit.extensions import UnitaryGate
uprime = get_perturbed_evolution_operator(qrw)
uprime = UnitaryGate(uprime,label="U'")
qrw.unitary(uprime, [0,1,2])
draw_circuit(qrw)
def is_unitary(m):
return np.allclose(np.eye(m.shape[0]), m.H * m)
uprime = get_perturbed_evolution_matrix(qrw)
is_unitary(np.matrix(uprime))
shift = get_shift_matrix(qrw)
is_unitary(np.matrix(shift))
import quantum_decomp as qd
Uprime.data
print(qd.matrix_to_qsharp(Uprime.data))
# gates = qd.matrix_to_gates(Uprime.data)
# print('\n'.join(map(str, gates)))
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# 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.
"""
Exception for errors raised by Qiskit Aer simulators backends.
"""
from qiskit import QiskitError
class AerError(QiskitError):
"""Base class for errors raised by simulators."""
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/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister
from qiskit.compiler import transpile, assemble
from qiskit.quantum_info import Operator, DensityMatrix
import qiskit.quantum_info as qi
from qiskit.tools.monitor import job_monitor
import random as rand
import scipy.linalg as la
import numpy as np
#Function to convert an integer to a binary bit string using "little Endian" encoding
# where the most significant bit is the first bit
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters: x (int), n (int, number of digits)"""
binry = format(x, 'b').zfill(n)
sup = list( reversed( binry[0:int(len(binry)/2)] ) )
sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) )
return format(x, 'b').zfill(n)
#return ''.join(sup)+''.join(sdn)
#================== qc_evolve ==========================
'''
Function to compute the time evolution operator and append the needed gates to
a given circuit.
Inputs:
-qc (qiskit circuit)
Circuit object to append time evolution gates
-numsite (int)
Number of sites in the one-dimensional chain
-time (float)
Current time of the evolution to build the operator
-hop (float, list)
Hopping parameter of the chain. Can be either float
for constant hopping or array describing the hopping
across each site. Length should be numsite-1
-U (float, list)
Repulsion parameter of the chain. Can be either float
for constant repulsion or array to describe different
repulsions for each site
-trotter_steps (int)
Number of trotter steps used to approximate the time evolution
operator
Outputs:
-None: qc is modified and returned
'''
def qc_evolve(qc, numsite, time, dt, hop, U, trotter_steps):
#Compute angles for the onsite and hopping gates
# based on the model parameters t, U, and dt
#theta = hop*time/(2*trotter_steps)
#phi = U*time/(trotter_steps)
numq = 2*numsite
# if np.isscalar(U):
# U = np.full(numsite, U)
# if np.isscalar(hop):
# hop = np.full(numsite, hop)
z_onsite = []
x_hop = []
y_hop = []
#MODIFIED TO TRY SMALLER TIME STEPS
num_steps = int(time/dt)
theta = hop*dt/(2*trotter_steps)
phi = U*dt/(trotter_steps)
z_onsite.append(Operator([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, np.exp(1j*phi)]]))
x_hop.append(Operator([[np.cos(theta), 0, 0, 1j*np.sin(theta)],
[0, np.cos(theta), 1j*np.sin(theta), 0],
[0, 1j*np.sin(theta), np.cos(theta), 0],
[1j*np.sin(theta), 0, 0, np.cos(theta)]]))
y_hop.append(Operator([[np.cos(theta), 0, 0, -1j*np.sin(theta)],
[0, np.cos(theta), 1j*np.sin(theta), 0],
[0, 1j*np.sin(theta), np.cos(theta), 0],
[-1j*np.sin(theta), 0, 0, np.cos(theta)]]))
#for step in range(num_steps):
for trot in range(trotter_steps):
#Onsite terms
for i in range(0, numsite):
qc.unitary(z_onsite[0], [i, i+numsite], label="Z_Onsite")
qc.barrier()
#Hopping terms
for i in range(0,numsite-1):
#Spin-up chain
qc.unitary(y_hop[0], [i,i+1], label="YHop")
qc.unitary(x_hop[0], [i,i+1], label="Xhop")
#Spin-down chain
qc.unitary(y_hop[0], [i+numsite, i+1+numsite], label="Xhop")
qc.unitary(x_hop[0], [i+numsite, i+1+numsite], label="Xhop")
qc.barrier()
#=============================================================
'''
for i in range(0, numsite):
phi = U[i]*time/(trotter_steps)
z_onsite.append( Operator([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, np.exp(1j*phi)]]) )
if i < numsite-1:
theta = hop[i]*time/(2*trotter_steps)
x_hop.append( Operator([[np.cos(theta), 0, 0, 1j*np.sin(theta)],
[0, np.cos(theta), 1j*np.sin(theta), 0],
[0, 1j*np.sin(theta), np.cos(theta), 0],
[1j*np.sin(theta), 0, 0, np.cos(theta)]]) )
y_hop.append( Operator([[np.cos(theta), 0, 0, -1j*np.sin(theta)],
[0, np.cos(theta), 1j*np.sin(theta), 0],
[0, 1j*np.sin(theta), np.cos(theta), 0],
[-1j*np.sin(theta), 0, 0, np.cos(theta)]]))
#Loop over each time step needed and apply onsite and hopping gates
for trot in range(trotter_steps):
#Onsite Terms
for i in range(0, numsite):
qc.unitary(z_onsite[i], [i,i+numsite], label="Z_Onsite")
#Add barrier to separate onsite from hopping terms
qc.barrier()
#Hopping terms
for i in range(0,numsite-1):
#Spin-up chain
qc.unitary(y_hop[i], [i,i+1], label="YHop")
qc.unitary(x_hop[i], [i,i+1], label="Xhop")
#Spin-down chain
qc.unitary(y_hop[i], [i+numsite, i+1+numsite], label="Xhop")
qc.unitary(x_hop[i], [i+numsite, i+1+numsite], label="Xhop")
#Add barrier after finishing the time step
qc.barrier()
'''
# circuit_operator = qi.Operator(qc)
# return circuit_operator.data
#================== sys_evolve ==========================
'''
Function to evolve the 1d-chain in time given a set of system parameters and using
the qiskit qasm_simulator (will later on add in functionality to set the backend)
Inputs:
-nsites (int)
Number of sites in the chain
-excitations (list)
List to create initial state of the system. The encoding here is
the first half of the qubits are the spin-up electrons for each site
and the second half for the spin-down electrons
-total_time (float)
Total time to evolve the system (units of inverse energy, 1/hop)
-dt (float)
Time step to evolve the system with
-hop (float, list)
Hopping parameter of the chain. Can be either float
for constant hopping or array describing the hopping
across each site. Length should be numsite-1
-U (float, list)
Repulsion parameter of the chain. Can be either float
for constant repulsion or array to describe different
repulsions for each site
-trotter_steps (int)
Number of trotter steps used to approximate the time evolution
operator
Outputs:
-data (2d array of length [2*nsites, time_steps])
Output data of the quantum simulation. Record the normalized counts
for each qubit at each time step
'''
def sys_evolve(nsites, excitations, total_time, dt, hop, U, trotter_steps):
#Check for correct data types of input
if not isinstance(nsites, int):
raise TypeError("Number of sites should be int")
if np.isscalar(excitations):
raise TypeError("Initial state should be list or numpy array")
if not np.isscalar(total_time):
raise TypeError("Evolution time should be scalar")
if not np.isscalar(dt):
raise TypeError("Time step should be scalar")
if not isinstance(trotter_steps, int):
raise TypeError("Number of trotter slices should be int")
numq = 2*nsites
num_steps = int(total_time/dt)
print('Num Steps: ',num_steps)
print('Total Time: ', total_time)
data = np.zeros((2**numq, num_steps))
for t_step in range(0, num_steps):
#Create circuit with t_step number of steps
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#=========USE THIS REGION TO SET YOUR INITIAL STATE==============
#Loop over each excitation
for flip in excitations:
qcirc.x(flip)
# qcirc.z(flip)
#===============================================================
qcirc.barrier()
#Append circuit with Trotter steps needed
qc_evolve(qcirc, nsites, t_step*dt, dt, hop, U, trotter_steps)
#Measure the circuit
for i in range(numq):
qcirc.measure(i, i)
#Choose provider and backend
#provider = IBMQ.get_provider()
#backend = Aer.get_backend('statevector_simulator')
backend = Aer.get_backend('qasm_simulator')
#backend = provider.get_backend('ibmq_qasm_simulator')
#backend = provider.get_backend('ibmqx4')
#backend = provider.get_backend('ibmqx2')
#backend = provider.get_backend('ibmq_16_melbourne')
shots = 8192
max_credits = 10 #Max number of credits to spend on execution
job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job_exp)
result = job_exp.result()
counts = result.get_counts(qcirc)
print(result.get_counts(qcirc))
print("Job: ",t_step+1, " of ", num_steps," complete.")
#Store results in data array and normalize them
for i in range(2**numq):
if counts.get(get_bin(i,numq)) is None:
dat = 0
else:
dat = counts.get(get_bin(i,numq))
data[i,t_step] = dat/shots
return data
#================== sys_evolve_eng ==========================
'''
Function to evolve the 1d-chain in time given a set of system parameters and using
the qiskit qasm_simulator and compute the total energy along the way
Inputs:
-nsites (int)
Number of sites in the chain
-excitations (list)
List to create initial state of the system. The encoding here is
the first half of the qubits are the spin-up electrons for each site
and the second half for the spin-down electrons
-total_time (float)
Total time to evolve the system (units of inverse energy, 1/hop)
-dt (float)
Time step to evolve the system with
-hop (float, list)
Hopping parameter of the chain. Can be either float
for constant hopping or array describing the hopping
across each site. Length should be numsite-1
-U (float, list)
Repulsion parameter of the chain. Can be either float
for constant repulsion or array to describe different
repulsions for each site
-trotter_steps (int)
Number of trotter steps used to approximate the time evolution
operator
Outputs:
-data (2d array of length [2*nsites, time_steps]):
Output data of the quantum simulation. Record the normalized counts
for each qubit at each time step
-energies (array of length [time_steps])
Output data of the total energy of the system at each time step
'''
def sys_evolve_eng(nsites, excitations, total_time, dt, hop, U, trotter_steps):
#Check for correct data types of input
if not isinstance(nsites, int):
raise TypeError("Number of sites should be int")
if np.isscalar(excitations):
raise TypeError("Initial state should be list or numpy array")
if not np.isscalar(total_time):
raise TypeError("Evolution time should be scalar")
if not np.isscalar(dt):
raise TypeError("Time step should be scalar")
if not isinstance(trotter_steps, int):
raise TypeError("Number of trotter slices should be int")
numq = 2*nsites
num_steps = int(total_time/dt)
print('Num Steps: ',num_steps)
print('Total Time: ', total_time)
data = np.zeros((2**numq, num_steps))
energies = np.zeros(num_steps)
for t_step in range(0, num_steps):
#Create circuit with t_step number of steps
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#=========SET YOUR INITIAL STATE==============
#Loop over each excitation
for flip in excitations:
qcirc.x(flip)
# qcirc.h(flip)
# qcirc.t(flip)
#===============================================================
qcirc.barrier()
#Append circuit with Trotter steps needed
qc_evolve(qcirc, nsites, t_step*dt, dt, hop, U, trotter_steps)
#Measure the circuit
for i in range(numq):
qcirc.measure(i, i)
#Choose provider and backend
#provider = IBMQ.get_provider()
#backend = Aer.get_backend('statevector_simulator')
backend = Aer.get_backend('qasm_simulator')
#backend = provider.get_backend('ibmq_qasm_simulator')
#backend = provider.get_backend('ibmqx4')
#backend = provider.get_backend('ibmqx2')
#backend = provider.get_backend('ibmq_16_melbourne')
shots = 8192
max_credits = 10 #Max number of credits to spend on execution
job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits)
#job_monitor(job_exp)
result = job_exp.result()
counts = result.get_counts(qcirc)
#print(result.get_counts(qcirc))
print("Job: ",t_step+1, " of ", num_steps," computing energy...")
#Store results in data array and normalize them
for i in range(2**numq):
if counts.get(get_bin(i,numq)) is None:
dat = 0
else:
dat = counts.get(get_bin(i,numq))
data[i,t_step] = dat/shots
#=======================================================
#Compute energy of system
#Compute repulsion energies
repulsion_energy = measure_repulsion(U, nsites, counts, shots)
#Compute hopping energies
#Get list of hopping pairs
even_pairs = []
for i in range(0,nsites-1,2):
#up_pair = [i, i+1]
#dwn_pair = [i+nsites, i+nsites+1]
even_pairs.append([i, i+1])
even_pairs.append([i+nsites, i+nsites+1])
odd_pairs = []
for i in range(1,nsites-1,2):
odd_pairs.append([i, i+1])
odd_pairs.append([i+nsites, i+nsites+1])
#Start with even hoppings, initialize circuit and find hopping pairs
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#Loop over each excitation
for flip in excitations:
qcirc.x(flip)
qcirc.barrier()
#Append circuit with Trotter steps needed
qc_evolve(qcirc, nsites, t_step*dt, dt, hop, U, trotter_steps)
even_hopping = measure_hopping(hop, even_pairs, qcirc, numq)
#===============================================================
#Now do the same for the odd hoppings
#Start with even hoppings, initialize circuit and find hopping pairs
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#Loop over each excitation
for flip in excitations:
qcirc.x(flip)
qcirc.barrier()
#Append circuit with Trotter steps needed
qc_evolve(qcirc, nsites, t_step*dt, dt, hop, U, trotter_steps)
odd_hopping = measure_hopping(hop, odd_pairs, qcirc, numq)
total_energy = repulsion_energy + even_hopping + odd_hopping
energies[t_step] = total_energy
print("Total Energy is: ", total_energy)
print("Job: ",t_step+1, " of ", num_steps," complete")
return data, energies
#================== measure_repulsion =========================
'''
Measure the energy due to the repulsive U term in H
Inputs:
-U (float): Repulsion energy of system
-num_sites (int): Number of sites in chain
-results (qiskit counts object): Results from qiskit circuit run
-shots (int): Number of shots from circuit run
Outputs:
-repulsion (float): Measures U*|a|^2|11> for each pair of modes
'''
def measure_repulsion(U, num_sites, results, shots):
repulsion = 0.
for state in results:
#Adding in debug print statement
#print(state)
for i in range( int( len(state)/2 ) ):
if state[i]=='1':
if state[i+num_sites]=='1':
print("Measured State: ",state)
repulsion += U*results.get(state)/shots
return repulsion
#================== measure_hopping =========================
'''
Measure the hopping energy at a given time step for a given set of
even/odd pairs. Apply the diagonalizing circuit to each pair and measure
the hopping as -t*( |a|^2*|01> - |b|^2*|10> )
Inputs:
-hopping (float): Hopping energy
-pairs (2d list): List of pairs of qubits to apply diagonalizing circuit
-circuit (qiskit circuit): Circuit to append diagonalizing gates to
-num_qubits (int): Number of qubits
Outputs:
-hop_eng (floats): Hopping energy at a given time step
'''
def measure_hopping(hopping, pairs, circuit, num_qubits):
#Add diagonalizing circuit
for pair in pairs:
circuit.cnot(pair[0],pair[1])
circuit.ch(pair[1],pair[0])
circuit.cnot(pair[0],pair[1])
circuit.measure_all()
#Run circuit
backend = Aer.get_backend('qasm_simulator')
shots = 8192
max_credits = 10 #Max number of credits to spend on execution
hop_exp = execute(circuit, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(hop_exp)
result = hop_exp.result()
counts = result.get_counts(circuit)
#Compute energy
for pair in pairs:
hop_eng = 0.
for state in counts:
if state[num_qubits-1-pair[0]]=='1':
prob_01 = counts.get(state)/shots
for comp_state in counts:
if comp_state[num_qubits-1-pair[1]]=='1':
hop_eng += -hopping*(prob_01 - counts.get(comp_state)/shots)
return hop_eng
'''The procedure here is, for each fermionic mode, add the probability of every state containing
that mode (at a given time step), and renormalize the data based on the total occupation of each mode.
Afterwards, plot the data as a function of time step for each mode.'''
#================== process_run ==========================
'''
Function to process the data output from sys_evolve or sys_evolve_eng. Will map each of the possible basis states to
each fermionic mode in order to plot the occupation probability as a function of time.
Inputs:
-num_sites (int)
Number of sites in the chain
-time_steps (int)
Number of time steps in the evolution
-dt (float)
Time step size (units of inverse energy)
-results (output of sys_evolve)
List obtained from the sys_evolve function
Outputs:
-proc_data (2d array of size [2*num_sites, time_steps])
Processes the data by mapping the outputs of each qubit
into occupation of each fermionic mode of the system.
Does this by adding and renormalizing each possible state
into a given fermionic mode.
'''
def process_run(num_sites, time_steps, dt, results):
proc_data = np.zeros((2*num_sites, time_steps))
timesq = np.arange(0.,time_steps*dt, dt)
#Sum over time steps
for t in range(time_steps):
#Sum over all possible states of computer
for i in range(2**(2*num_sites)):
#Grab binary string in "little Endian" encoding by reversing get_bin()
num = ''.join( list( reversed(get_bin(i,2*num_sites)) ) )
#For each state, check which mode(s) it contains and add them
for mode in range(len(num)):
if num[mode]=='1':
proc_data[mode,t] += results[i,t]
#Renormalize these sums so that the total occupation of the modes is 1
norm = 0.0
for mode in range(len(num)):
norm += proc_data[mode,t]
proc_data[:,t] = proc_data[:,t] / norm
'''
At this point, proc_data is a 2d array containing the occupation
of each mode, for every time step
'''
return proc_data
#================== sys_evolve ==========================
'''
Function to evolve the 1d-chain in time given a set of system parameters and using
the qiskit qasm_simulator (will later on add in functionality to set the backend)
Inputs:
-nsites (int)
Number of sites in the chain
-excitations (list)
List to create initial state of the system. The encoding here is
the first half of the qubits are the spin-up electrons for each site
and the second half for the spin-down electrons
-total_time (float)
Total time to evolve the system (units of inverse energy, 1/hop)
-dt (float)
Time step to evolve the system with
-hop (float, list)
Hopping parameter of the chain. Can be either float
for constant hopping or array describing the hopping
across each site. Length should be numsite-1
-U (float, list)
Repulsion parameter of the chain. Can be either float
for constant repulsion or array to describe different
repulsions for each site
-trotter_steps (int)
Number of trotter steps used to approximate the time evolution
operator
Outputs:
-data (2d array of length [2*nsites, time_steps])
Output data of the quantum simulation. Record the normalized counts
for each qubit at each time step
'''
def sys_evolve_den(nsites, excitations, total_time, dt, hop, U, trotter_steps):
#Check for correct data types of input
if not isinstance(nsites, int):
raise TypeError("Number of sites should be int")
if np.isscalar(excitations):
raise TypeError("Initial state should be list or numpy array")
if not np.isscalar(total_time):
raise TypeError("Evolution time should be scalar")
if not np.isscalar(dt):
raise TypeError("Time step should be scalar")
if not isinstance(trotter_steps, int):
raise TypeError("Number of trotter slices should be int")
numq = 2*nsites
num_steps = int(total_time/dt)
print('Num Steps: ',num_steps)
print('Total Time: ', total_time)
data = []
for t_step in range(0, num_steps):
#Create circuit with t_step number of steps
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#=========USE THIS REGION TO SET YOUR INITIAL STATE==============
#Loop over each excitation
for flip in excitations:
qcirc.x(flip)
#qcirc.h(flip)
# qcirc.z(flip)
#===============================================================
qcirc.barrier()
#Append circuit with Trotter steps needed
qc_evolve(qcirc, nsites, t_step*dt, dt, hop, U, trotter_steps)
den_mtrx_obj = DensityMatrix.from_instruction(qcirc)
den_mtrx = den_mtrx_obj.to_operator().data
state_vector = qi.Statevector.from_instruction(qcirc)
#data.append(state_vector.data)
data.append(den_mtrx)
#Measure the circuit
for i in range(numq):
qcirc.measure(i, i)
'''
#Choose provider and backend
provider = IBMQ.get_provider()
#backend = Aer.get_backend('statevector_simulator')
backend = Aer.get_backend('qasm_simulator')
#backend = provider.get_backend('ibmq_qasm_simulator')
#backend = provider.get_backend('ibmqx4')
#backend = provider.get_backend('ibmqx2')
#backend = provider.get_backend('ibmq_16_melbourne')
shots = 8192
max_credits = 10 #Max number of credits to spend on execution
job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job_exp)
result = job_exp.result()
counts = result.get_counts(qcirc)
print(result.get_counts(qcirc))
print("Job: ",t_step+1, " of ", num_steps," complete.")
'''
return data
|
https://github.com/Qiskit/feedback
|
Qiskit
|
import sys
#add local qiskit-terra/test/python path here to import transpiler._dummy_passes
#test_path='<enter path here>'
sys.path.append(test_path)
from transpiler import test_pass_scheduler
from qiskit import QuantumCircuit,QuantumRegister
from qiskit.transpiler import PassManager
from qiskit.transpiler.runningpassmanager import ConditionalController,DoWhileController
from transpiler._dummy_passes import (
PassA_TP_NR_NP,
PassB_TP_RA_PA,
PassC_TP_RA_PA,
PassD_TP_NR_NP,
PassE_AP_NR_NP,
PassF_reduce_dag_property,
PassI_Bad_AP,
PassJ_Bad_NoReturn,
PassK_check_fixed_point_property,
PassM_AP_NR_NP,
)
from transpiler.test_pass_scheduler import SchedulerTestCase
def show_run(passmanager,circuit):
myScheduler=SchedulerTestCase()
with myScheduler.assertLogs("LocalLogger", level="INFO") as cm:
out = passmanager.run(circuit)
return [record.message for record in cm.records]
#Creating a nested ConditionalController
#Defining PassManager and circuit
passmanager=PassManager()
circuit = QuantumCircuit(QuantumRegister(1))
#Runs PassA_TP_NR_NP if property_set["property"] is True
#Passes like PassA_TP_NR_NP are just test passes used in the test suite
nested_conditional=[ConditionalController(
[PassA_TP_NR_NP()],
condition=lambda property_set: property_set["property"])]
passmanager.append([PassE_AP_NR_NP(True)] +
nested_conditional)
show_run(passmanager,circuit)
#Nesting a ConditionalController inside of a loop
#Defining PassManager and circuit
passmanager=PassManager()
circuit = QuantumCircuit(QuantumRegister(1))
#Runs PassA_TP_NR_NP if property_set["property"] is True
nested_conditional=[ConditionalController(
[PassA_TP_NR_NP()],
condition=lambda property_set: property_set["property"])]
passmanager.append([PassK_check_fixed_point_property(), PassE_AP_NR_NP(True)]
+ nested_conditional
+ [PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"])
show_run(passmanager,circuit)
#Nesting ConditionalControllers more than one level
passmanager=PassManager()
circuit = QuantumCircuit(QuantumRegister(1))
nested_level3=ConditionalController([PassC_TP_RA_PA()], condition=lambda property_set: property_set["property"])
nested_level2=ConditionalController([PassF_reduce_dag_property(),nested_level3],condition=lambda property_set: property_set["property"])
nested_level1=[ConditionalController([PassA_TP_NR_NP(),nested_level2], condition=lambda property_set: property_set["property"])]
passmanager.append([PassE_AP_NR_NP(True)]
+ nested_level1)
show_run(passmanager,circuit)
#Multiple nested ConditionalControllers on the same level
passmanager=PassManager()
circuit = QuantumCircuit(QuantumRegister(1))
nested_conditional1=[ConditionalController([PassB_TP_RA_PA()], condition=lambda property_set: property_set["property"])]
nested_conditional2=[ConditionalController([PassC_TP_RA_PA()], condition=lambda property_set: property_set["property"])]
nested_conditional3=[ConditionalController([PassD_TP_NR_NP()], condition=lambda property_set: property_set["property"])]
passmanager.append([PassE_AP_NR_NP(True)]
+ nested_conditional1
+ [PassE_AP_NR_NP(False)]
+ nested_conditional2
+ [PassE_AP_NR_NP(True)]
+ nested_conditional3)
show_run(passmanager,circuit)
#Nested DoWhileController
passmanager=PassManager()
circuit = QuantumCircuit(QuantumRegister(1))
nested_do_while = [DoWhileController([PassK_check_fixed_point_property(),PassF_reduce_dag_property()],
do_while=lambda property_set: not property_set["property_fixed_point"])]
passmanager.append([PassD_TP_NR_NP()]
+ nested_do_while
+ [PassD_TP_NR_NP()])
show_run(passmanager,circuit)
from qiskit.circuit.library import QuantumVolume
from qiskit import *
from qiskit.test.mock import FakeBelem
qcomp = FakeBelem()
qv_circuit=QuantumVolume(3)
qv_circuit.draw()
from IPython.display import display
from qiskit.converters import dag_to_circuit
from qiskit.transpiler import TransformationPass
from qiskit.converters import dag_to_circuit
def my_callback(pass_,dag, time, property_set, count):
circuit = dag_to_circuit(dag)
print(pass_.name())
#display(circuit.draw(output='mpl'))
circuit = dag_to_circuit(dag)
transpile(qv_circuit,backend=qcomp, optimization_level=3,callback=my_callback,translation_method='synthesis').draw(output='mpl')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.