repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from enum import Flag, auto
import os
from typing import Dict, List, Union
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.circuit import Qubit, Clbit
from qiskit.circuit.instruction import Instruction
class Capability(Flag):
NONE = 0
CONDITIONAL_BRANCHING_ON_RESULT = auto()
QUBIT_USE_AFTER_MEASUREMENT = auto()
ALL = CONDITIONAL_BRANCHING_ON_RESULT | QUBIT_USE_AFTER_MEASUREMENT
class CapabilityError(Exception):
"""Base class for profile validation exceptions"""
def _get_bit_labels(
self,
circuit: QuantumCircuit,
) -> Dict[Union[Qubit, Clbit], str]:
register_names: Dict[str, Union[QuantumRegister, ClassicalRegister]] = {}
for registers in (circuit.qregs, circuit.cregs):
for register in registers:
register_names[register.name] = register
bit_labels: Dict[Union[Qubit, Clbit], str] = {
bit: "%s[%d]" % (name, idx)
for name, register in register_names.items()
for (idx, bit) in enumerate(register)
}
return bit_labels
def _get_instruction_string(
self,
bit_labels: Dict[Union[Qubit, Clbit], str],
instruction: Instruction,
qargs: List[Qubit],
cargs: List[Clbit],
):
gate_params = ",".join(["param(%s)" % bit_labels[c] for c in cargs])
qubit_params = ",".join(["%s" % bit_labels[q] for q in qargs])
instruction_name = instruction.name
if instruction.condition is not None:
# condition should be a
# - tuple (ClassicalRegister, int)
# - tuple (Clbit, bool)
# - tuple (Clbit, int)
if isinstance(instruction.condition[0], Clbit):
bit: Clbit = instruction.condition[0]
value: Union[int, bool] = instruction.condition[1]
instruction_name = "if(%s[%d] == %s) %s" % (
bit._register.name,
bit._index,
value,
instruction_name,
)
else:
register: ClassicalRegister = instruction.condition[0]
value: int = instruction.condition[1]
instruction_name = "if(%s == %d) %s" % (
register._name,
value,
instruction_name,
)
if gate_params:
return f"{instruction_name}({gate_params}) {qubit_params}"
else:
return f"{instruction_name} {qubit_params}"
class ConditionalBranchingOnResultError(CapabilityError):
def __init__(
self,
circuit: QuantumCircuit,
instruction: Instruction,
qargs: List[Qubit],
cargs: List[Clbit],
profile: str,
):
bit_labels: Dict[Union[Qubit, Clbit], str] = self._get_bit_labels(circuit)
instruction_string = self._get_instruction_string(
bit_labels, instruction, qargs, cargs
)
self.instruction_string = instruction_string
self.msg_suffix = "Support for branching based on measurement requires Capability.CONDITIONAL_BRANCHING_ON_RESULT"
self.msg = f"Attempted to branch on register value.{os.linesep}Instruction: {instruction_string}{os.linesep}{self.msg_suffix}"
CapabilityError.__init__(self, self.msg)
self.instruction = instruction
self.qargs = qargs
self.cargs = cargs
self.profile = profile
class QubitUseAfterMeasurementError(CapabilityError):
def __init__(
self,
circuit: QuantumCircuit,
instruction: Instruction,
qargs: List[Qubit],
cargs: List[Clbit],
profile: str,
):
bit_labels: Dict[Union[Qubit, Clbit], str] = self._get_bit_labels(circuit)
instruction_string = self._get_instruction_string(
bit_labels, instruction, qargs, cargs
)
self.instruction_string = instruction_string
self.msg_suffix = (
"Support for qubit reuse requires Capability.QUBIT_USE_AFTER_MEASUREMENT"
)
self.msg = f"Qubit was used after being measured.{os.linesep}Instruction: {instruction_string}{os.linesep}{self.msg_suffix}"
CapabilityError.__init__(self, self.msg)
self.instruction = instruction
self.qargs = qargs
self.cargs = cargs
self.profile = profile
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from typing import List, Optional, Union
from pyqir import Module, Context
from qiskit import ClassicalRegister, QuantumRegister
from qiskit.circuit.bit import Bit
from qiskit.circuit.quantumcircuit import QuantumCircuit, Instruction
from abc import ABCMeta, abstractmethod
class _QuantumCircuitElement(metaclass=ABCMeta):
@classmethod
def from_element_list(cls, elements):
return [cls(elem) for elem in elements]
@abstractmethod
def accept(self, visitor):
pass
class _Register(_QuantumCircuitElement):
def __init__(self, register: Union[QuantumRegister, ClassicalRegister]):
self._register: Union[QuantumRegister, ClassicalRegister] = register
def accept(self, visitor):
visitor.visit_register(self._register)
class _Instruction(_QuantumCircuitElement):
def __init__(self, instruction: Instruction, qargs: List[Bit], cargs: List[Bit]):
self._instruction: Instruction = instruction
self._qargs = qargs
self._cargs = cargs
def accept(self, visitor):
visitor.visit_instruction(self._instruction, self._qargs, self._cargs)
class QiskitModule:
def __init__(
self,
circuit: QuantumCircuit,
name: str,
module: Module,
num_qubits: int,
num_clbits: int,
reg_sizes: List[int],
elements: List[_QuantumCircuitElement],
):
self._circuit = circuit
self._name = name
self._module = module
self._elements = elements
self._num_qubits = num_qubits
self._num_clbits = num_clbits
self.reg_sizes = reg_sizes
@property
def circuit(self) -> QuantumCircuit:
return self._circuit
@property
def name(self) -> str:
return self._name
@property
def module(self) -> Module:
return self._module
@property
def num_qubits(self) -> int:
return self._num_qubits
@property
def num_clbits(self) -> int:
return self._num_clbits
@classmethod
def from_quantum_circuit(
cls, circuit: QuantumCircuit, module: Optional[Module] = None
) -> "QiskitModule":
"""Create a new QiskitModule from a qiskit.QuantumCircuit object."""
elements: List[_QuantumCircuitElement] = []
reg_sizes = [len(creg) for creg in circuit.cregs]
# Registers
elements.extend(_Register.from_element_list(circuit.qregs))
elements.extend(_Register.from_element_list(circuit.cregs))
# Instructions
for instruction, qargs, cargs in circuit._data:
elements.append(_Instruction(instruction, qargs, cargs))
if module is None:
module = Module(Context(), circuit.name)
return cls(
circuit=circuit,
name=circuit.name,
module=module,
num_qubits=circuit.num_qubits,
num_clbits=circuit.num_clbits,
reg_sizes=reg_sizes,
elements=elements,
)
def accept(self, visitor):
visitor.visit_qiskit_module(self)
for element in self._elements:
element.accept(visitor)
visitor.record_output(self)
visitor.finalize()
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from io import UnsupportedOperation
import logging
from abc import ABCMeta, abstractmethod
from qiskit import ClassicalRegister, QuantumRegister
from qiskit.circuit import Qubit, Clbit
from qiskit.circuit.instruction import Instruction
from qiskit.circuit.bit import Bit
import pyqir.qis as qis
import pyqir.rt as rt
import pyqir
from pyqir import (
BasicBlock,
Builder,
Constant,
Function,
FunctionType,
IntType,
Linkage,
Module,
PointerType,
const,
entry_point,
qubit_id,
)
from typing import List, Union
from qiskit_qir.capability import (
Capability,
ConditionalBranchingOnResultError,
QubitUseAfterMeasurementError,
)
from qiskit_qir.elements import QiskitModule
_log = logging.getLogger(name=__name__)
# This list cannot change as existing clients hardcoded to it
# when it wasn't designed to be externally used.
# To work around this we are using an additional list to replace
# this list which contains the instructions that we can process.
# This following three variables can be removed in a future
# release after dependency version restrictions have been applied.
SUPPORTED_INSTRUCTIONS = [
"barrier",
"delay",
"measure",
"m",
"cx",
"cz",
"h",
"reset",
"rx",
"ry",
"rz",
"s",
"sdg",
"t",
"tdg",
"x",
"y",
"z",
"id",
]
_QUANTUM_INSTRUCTIONS = [
"barrier",
"ccx",
"cx",
"cz",
"h",
"id",
"m",
"measure",
"reset",
"rx",
"ry",
"rz",
"s",
"sdg",
"swap",
"t",
"tdg",
"x",
"y",
"z",
]
_NOOP_INSTRUCTIONS = ["delay"]
_SUPPORTED_INSTRUCTIONS = _QUANTUM_INSTRUCTIONS + _NOOP_INSTRUCTIONS
class QuantumCircuitElementVisitor(metaclass=ABCMeta):
@abstractmethod
def visit_register(self, register):
raise NotImplementedError
@abstractmethod
def visit_instruction(self, instruction):
raise NotImplementedError
class BasicQisVisitor(QuantumCircuitElementVisitor):
def __init__(self, profile: str = "AdaptiveExecution", **kwargs):
self._module = None
self._qiskitModule: QiskitModule | None = None
self._builder = None
self._entry_point = None
self._qubit_labels = {}
self._clbit_labels = {}
self._profile = profile
self._capabilities = self._map_profile_to_capabilities(profile)
self._measured_qubits = {}
self._emit_barrier_calls = kwargs.get("emit_barrier_calls", False)
self._record_output = kwargs.get("record_output", True)
def visit_qiskit_module(self, module: QiskitModule):
_log.debug(
f"Visiting Qiskit module '{module.name}' ({module.num_qubits}, {module.num_clbits})"
)
self._module = module.module
self._qiskitModule = module
context = self._module.context
entry = entry_point(
self._module, module.name, module.num_qubits, module.num_clbits
)
self._entry_point = entry.name
self._builder = Builder(context)
self._builder.insert_at_end(BasicBlock(context, "entry", entry))
i8p = PointerType(IntType(context, 8))
nullptr = Constant.null(i8p)
rt.initialize(self._builder, nullptr)
@property
def entry_point(self) -> str:
return self._entry_point
def finalize(self):
self._builder.ret(None)
def record_output(self, module: QiskitModule):
if self._record_output == False:
return
i8p = PointerType(IntType(self._module.context, 8))
# qiskit inverts the ordering of the results within each register
# but keeps the overall register ordering
# here we logically loop from n-1 to 0, decrementing in order to
# invert the register output. The second parameter is an exclusive
# range so we need to go to -1 instead of 0
logical_id_base = 0
for size in module.reg_sizes:
rt.array_record_output(
self._builder,
const(IntType(self._module.context, 64), size),
Constant.null(i8p),
)
for index in range(size - 1, -1, -1):
result_ref = pyqir.result(self._module.context, logical_id_base + index)
rt.result_record_output(self._builder, result_ref, Constant.null(i8p))
logical_id_base += size
def visit_register(self, register):
_log.debug(f"Visiting register '{register.name}'")
if isinstance(register, QuantumRegister):
self._qubit_labels.update(
{bit: n + len(self._qubit_labels) for n, bit in enumerate(register)}
)
_log.debug(
f"Added labels for qubits {[bit for n, bit in enumerate(register)]}"
)
elif isinstance(register, ClassicalRegister):
self._clbit_labels.update(
{bit: n + len(self._clbit_labels) for n, bit in enumerate(register)}
)
else:
raise ValueError(f"Register of type {type(register)} not supported.")
def process_composite_instruction(
self, instruction: Instruction, qargs: List[Qubit], cargs: List[Clbit]
):
subcircuit = instruction.definition
_log.debug(
f"Processing composite instruction {instruction.name} with qubits {qargs}"
)
if len(qargs) != subcircuit.num_qubits:
raise ValueError(
f"Composite instruction {instruction.name} called with the wrong number of qubits; \
{subcircuit.num_qubits} expected, {len(qargs)} provided"
)
if len(cargs) != subcircuit.num_clbits:
raise ValueError(
f"Composite instruction {instruction.name} called with the wrong number of classical bits; \
{subcircuit.num_clbits} expected, {len(cargs)} provided"
)
for inst, i_qargs, i_cargs in subcircuit.data:
mapped_qbits = [qargs[subcircuit.qubits.index(i)] for i in i_qargs]
mapped_clbits = [cargs[subcircuit.clbits.index(i)] for i in i_cargs]
_log.debug(
f"Processing sub-instruction {inst.name} with mapped qubits {mapped_qbits}"
)
self.visit_instruction(inst, mapped_qbits, mapped_clbits)
def visit_instruction(
self,
instruction: Instruction,
qargs: List[Bit],
cargs: List[Bit],
skip_condition=False,
):
qlabels = [self._qubit_labels.get(bit) for bit in qargs]
clabels = [self._clbit_labels.get(bit) for bit in cargs]
qubits = [pyqir.qubit(self._module.context, n) for n in qlabels]
results = [pyqir.result(self._module.context, n) for n in clabels]
if (
instruction.condition is not None
) and not self._capabilities & Capability.CONDITIONAL_BRANCHING_ON_RESULT:
raise ConditionalBranchingOnResultError(
self._qiskitModule.circuit, instruction, qargs, cargs, self._profile
)
labels = ", ".join([str(l) for l in qlabels + clabels])
if instruction.condition is None or skip_condition:
_log.debug(f"Visiting instruction '{instruction.name}' ({labels})")
if instruction.condition is not None and skip_condition is False:
_log.debug(
f"Visiting condition for instruction '{instruction.name}' ({labels})"
)
if isinstance(instruction.condition[0], Clbit):
bit_label = self._clbit_labels.get(instruction.condition[0])
conditions = [pyqir.result(self._module.context, bit_label)]
else:
conditions = [
pyqir.result(self._module.context, self._clbit_labels.get(bit))
for bit in instruction.condition[0]
]
# Convert value into a bitstring of the same length as classical register
# condition should be a
# - tuple (ClassicalRegister, int)
# - tuple (Clbit, bool)
# - tuple (Clbit, int)
if isinstance(instruction.condition[0], Clbit):
bit: Clbit = instruction.condition[0]
value: Union[int, bool] = instruction.condition[1]
if value:
values = "1"
else:
values = "0"
else:
register: ClassicalRegister = instruction.condition[0]
value: int = instruction.condition[1]
values = format(value, f"0{register.size}b")
# Add branches recursively for each bit in the bitstring
def __visit():
self.visit_instruction(instruction, qargs, cargs, skip_condition=True)
def _branch(conditions_values):
try:
cond, val = next(conditions_values)
def __branch():
qis.if_result(
self._builder,
cond,
one=_branch(conditions_values) if val == "1" else None,
zero=_branch(conditions_values) if val == "0" else None,
)
except StopIteration:
return __visit
else:
return __branch
if len(conditions) < len(values):
raise ValueError(
f"Value {value} is larger than register width {len(conditions)}."
)
# qiskit has the most significant bit on the right, so we
# must reverse the bit array for comparisons.
_branch(zip(conditions, values[::-1]))()
elif (
"measure" == instruction.name
or "m" == instruction.name
or "mz" == instruction.name
):
for qubit, result in zip(qubits, results):
self._measured_qubits[qubit_id(qubit)] = True
qis.mz(self._builder, qubit, result)
else:
if not self._capabilities & Capability.QUBIT_USE_AFTER_MEASUREMENT:
# If we have a supported instruction, apply the capability
# check. If we have a composite instruction then it will call
# back into this function with a supported name and we'll
# verify at that time
if instruction.name in _SUPPORTED_INSTRUCTIONS:
if any(map(self._measured_qubits.get, map(qubit_id, qubits))):
raise QubitUseAfterMeasurementError(
self._qiskitModule.circuit,
instruction,
qargs,
cargs,
self._profile,
)
if "barrier" == instruction.name:
if self._emit_barrier_calls:
qis.barrier(self._builder)
elif "delay" == instruction.name:
pass
elif "swap" == instruction.name:
qis.swap(self._builder, *qubits)
elif "ccx" == instruction.name:
qis.ccx(self._builder, *qubits)
elif "cx" == instruction.name:
qis.cx(self._builder, *qubits)
elif "cz" == instruction.name:
qis.cz(self._builder, *qubits)
elif "h" == instruction.name:
qis.h(self._builder, *qubits)
elif "reset" == instruction.name:
qis.reset(self._builder, qubits[0])
elif "rx" == instruction.name:
qis.rx(self._builder, *instruction.params, *qubits)
elif "ry" == instruction.name:
qis.ry(self._builder, *instruction.params, *qubits)
elif "rz" == instruction.name:
qis.rz(self._builder, *instruction.params, *qubits)
elif "s" == instruction.name:
qis.s(self._builder, *qubits)
elif "sdg" == instruction.name:
qis.s_adj(self._builder, *qubits)
elif "t" == instruction.name:
qis.t(self._builder, *qubits)
elif "tdg" == instruction.name:
qis.t_adj(self._builder, *qubits)
elif "x" == instruction.name:
qis.x(self._builder, *qubits)
elif "y" == instruction.name:
qis.y(self._builder, *qubits)
elif "z" == instruction.name:
qis.z(self._builder, *qubits)
elif "id" == instruction.name:
# See: https://github.com/qir-alliance/pyqir/issues/74
qubit = pyqir.qubit(self._module.context, qubit_id(*qubits))
qis.x(self._builder, qubit)
qis.x(self._builder, qubit)
elif instruction.definition:
_log.debug(
f"About to process composite instruction {instruction.name} with qubits {qargs}"
)
self.process_composite_instruction(instruction, qargs, cargs)
else:
raise ValueError(
f"Gate {instruction.name} is not supported. \
Please transpile using the list of supported gates: {_SUPPORTED_INSTRUCTIONS}."
)
def ir(self) -> str:
return str(self._module)
def bitcode(self) -> bytes:
return self._module.bitcode()
def _map_profile_to_capabilities(self, profile: str):
value = profile.strip().lower()
if "BasicExecution".lower() == value:
return Capability.NONE
elif "AdaptiveExecution".lower() == value:
return Capability.ALL
else:
raise UnsupportedOperation(
f"The supplied profile is not supported: {profile}."
)
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from qiskit_qir.translate import to_qir_module
from qiskit import QuantumCircuit, ClassicalRegister
from qiskit.circuit import Parameter
import numpy as np
from pyqir import Context, Module, is_entry_point
from typing import List
import test_utils
import pytest
def get_parameterized_circuit(num_qubits: int, num_params: int) -> List[QuantumCircuit]:
theta_range = np.linspace(0, 2 * np.pi, num_params)
theta = Parameter("θ")
circuit = QuantumCircuit(num_qubits, 1)
circuit.h(0)
for i in range(num_qubits - 1):
circuit.cx(i, i + 1)
circuit.barrier()
circuit.rz(theta, range(num_qubits))
circuit.barrier()
for i in reversed(range(num_qubits - 1)):
circuit.cx(i, i + 1)
circuit.h(0)
circuit.measure(0, 0)
circuits = [
circuit.assign_parameters({theta: theta_val}, inplace=False)
for theta_val in theta_range
]
return circuits
@pytest.mark.parametrize("num_params", [1, 2, 3])
def test_binding_generates_corresponding_entry_points(num_params: int) -> None:
circuits = get_parameterized_circuit(2, num_params)
bitcode = to_qir_module(circuits)[0].bitcode
mod = Module.from_bitcode(Context(), bitcode)
funcs = list(filter(is_entry_point, mod.functions))
assert len(funcs) == num_params
def test_batch_entry_points_use_circuit_names() -> None:
qc1 = QuantumCircuit(1, name="first")
qc2 = QuantumCircuit(1, name="second")
module, entry_points = to_qir_module(list([qc1, qc2]))
mod = Module.from_bitcode(Context(), module.bitcode)
functions = list(filter(is_entry_point, mod.functions))
assert len(functions) == 2
for function in functions:
assert function.name in ["first", "second"]
assert entry_points == list([x.name for x in functions])
def test_batch_entry_points_make_unique_names_on_duplicates() -> None:
name = "first"
qc1 = QuantumCircuit(1, name=name)
qc2 = QuantumCircuit(1, name=name)
module, entry_points = to_qir_module(list([qc1, qc2]))
mod = Module.from_bitcode(Context(), module.bitcode)
functions = list(filter(is_entry_point, mod.functions))
assert len(functions) == 2
for function in functions:
assert function.name.startswith(name)
assert functions[0].name != functions[1].name
assert entry_points == list([x.name for x in functions])
def test_batch_entry_points_have_appropriate_attributes() -> None:
qc1 = QuantumCircuit(1, 2, name="first")
qc2 = QuantumCircuit(1, name="second")
qc3 = QuantumCircuit(name="second")
qc4 = QuantumCircuit(name="second")
cr = ClassicalRegister(2, "creg")
qc4.add_register(cr)
bitcode = to_qir_module(list([qc1, qc2, qc3, qc4]))[0].bitcode
mod = Module.from_bitcode(Context(), bitcode)
functions = list(filter(is_entry_point, mod.functions))
assert len(functions) == 4
test_utils.check_attributes_on_entrypoint(functions[0], 1, 2)
test_utils.check_attributes_on_entrypoint(functions[1], 1)
test_utils.check_attributes_on_entrypoint(functions[2])
test_utils.check_attributes_on_entrypoint(functions[3], expected_results=2)
def test_passing_list_with_non_quantum_circuits_raises_value_error() -> None:
qc = QuantumCircuit(1)
with pytest.raises(ValueError):
_ = to_qir_module(list([qc, 2]))
with pytest.raises(ValueError):
_ = to_qir_module(list([2, qc]))
with pytest.raises(ValueError):
_ = to_qir_module(list([2]))
with pytest.raises(ValueError):
_ = to_qir_module(list([qc, 2, qc]))
def test_passing_non_quantum_circuits_raises_value_error() -> None:
with pytest.raises(ValueError):
_ = to_qir_module(2)
def test_passing_empty_list_of_quantum_circuits_raises_value_error() -> None:
with pytest.raises(ValueError):
_ = to_qir_module(list([]))
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from typing import List
import pytest
from qiskit_qir.elements import QiskitModule
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit_qir.capability import (
Capability,
ConditionalBranchingOnResultError,
QubitUseAfterMeasurementError,
)
from qiskit_qir.visitor import BasicQisVisitor
# test circuits
def teleport() -> QuantumCircuit:
qq = QuantumRegister(3, name="qq")
cr = ClassicalRegister(2, name="cr")
circuit = QuantumCircuit(qq, cr, name="Teleport")
circuit.h(1)
circuit.cx(1, 2)
circuit.cx(0, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.measure(1, 1)
circuit.x(2).c_if(cr, int("10", 2))
circuit.z(2).c_if(cr, int("01", 2))
return circuit
def use_after_measure():
qq = QuantumRegister(2, name="qq")
cr = ClassicalRegister(2, name="cr")
circuit = QuantumCircuit(qq, cr)
circuit.h(1)
circuit.measure(1, 1)
circuit.h(1)
return circuit
def use_another_after_measure():
circuit = QuantumCircuit(3, 2)
circuit.h(0)
circuit.measure(0, 0)
circuit.h(1)
circuit.cx(1, 2)
circuit.measure(1, 1)
return circuit
def use_another_after_measure_and_condition():
qq = QuantumRegister(3, name="qq")
cr = ClassicalRegister(2, name="cr")
circuit = QuantumCircuit(qq, cr)
circuit.h(0)
circuit.measure(0, 0)
circuit.h(1)
circuit.cx(1, 2)
circuit.measure(1, 1)
circuit.x(2).c_if(cr, int("10", 2))
return circuit
def use_conditional_branch_on_single_register_true_value():
circuit = QuantumCircuit(name="Conditional")
qr = QuantumRegister(2, "qreg")
cr = ClassicalRegister(3, "creg")
circuit.add_register(qr)
circuit.add_register(cr)
circuit.x(0)
circuit.measure(0, 0)
circuit.x(1).c_if(cr[2], 1)
circuit.measure(0, 1)
return circuit
def use_conditional_branch_on_single_register_false_value():
circuit = QuantumCircuit(name="Conditional")
qr = QuantumRegister(2, "qreg")
cr = ClassicalRegister(3, "creg")
circuit.add_register(qr)
circuit.add_register(cr)
circuit.x(0)
circuit.measure(0, 0)
circuit.x(1).c_if(cr[2], 0)
circuit.measure(0, 1)
return circuit
def conditional_branch_on_bit():
qr = QuantumRegister(2, "qreg")
cr = ClassicalRegister(2, "creg")
circuit = QuantumCircuit(qr, cr, name="conditional_branch_on_bit")
circuit.x(0)
circuit.measure(0, 0)
circuit.x(1).c_if(cr[0], 1)
circuit.measure(1, 1)
return circuit
# Utility using new visitor
def circuit_to_qir(circuit, profile: str = "AdaptiveExecution"):
module = QiskitModule.from_quantum_circuit(circuit=circuit)
visitor = BasicQisVisitor(profile)
module.accept(visitor)
return visitor.ir()
def test_branching_on_measurement_fails_without_required_capability():
circuit = teleport()
with pytest.raises(ConditionalBranchingOnResultError) as exc_info:
_ = circuit_to_qir(circuit, "BasicExecution")
exception_raised = exc_info.value
assert (
str(exception_raised.instruction)
== "Instruction(name='x', num_qubits=1, num_clbits=0, params=[])"
)
assert (
str(exception_raised.instruction.condition) == "(ClassicalRegister(2, 'cr'), 2)"
)
assert str(exception_raised.qargs) == "[Qubit(QuantumRegister(3, 'qq'), 2)]"
assert str(exception_raised.cargs) == "[]"
assert str(exception_raised.profile) == "BasicExecution"
assert exception_raised.instruction_string == "if(cr == 2) x qq[2]"
def test_branching_on_measurement_fails_without_required_capability():
circuit = use_conditional_branch_on_single_register_true_value()
with pytest.raises(ConditionalBranchingOnResultError) as exc_info:
_ = circuit_to_qir(circuit, "BasicExecution")
exception_raised = exc_info.value
assert (
str(exception_raised.instruction)
== "Instruction(name='x', num_qubits=1, num_clbits=0, params=[])"
)
assert (
str(exception_raised.instruction.condition)
== "(Clbit(ClassicalRegister(3, 'creg'), 2), True)"
)
assert str(exception_raised.qargs) == "[Qubit(QuantumRegister(2, 'qreg'), 1)]"
assert str(exception_raised.cargs) == "[]"
assert str(exception_raised.profile) == "BasicExecution"
assert exception_raised.instruction_string == "if(creg[2] == True) x qreg[1]"
def test_branching_on_measurement_fails_without_required_capability():
circuit = use_conditional_branch_on_single_register_false_value()
with pytest.raises(ConditionalBranchingOnResultError) as exc_info:
_ = circuit_to_qir(circuit, "BasicExecution")
exception_raised = exc_info.value
assert (
str(exception_raised.instruction)
== "Instruction(name='x', num_qubits=1, num_clbits=0, params=[])"
)
assert (
str(exception_raised.instruction.condition)
== "(Clbit(ClassicalRegister(3, 'creg'), 2), False)"
)
assert str(exception_raised.qargs) == "[Qubit(QuantumRegister(2, 'qreg'), 1)]"
assert str(exception_raised.cargs) == "[]"
assert str(exception_raised.profile) == "BasicExecution"
assert exception_raised.instruction_string == "if(creg[2] == False) x qreg[1]"
def test_branching_on_measurement_register_passses_with_required_capability():
circuit = teleport()
_ = circuit_to_qir(circuit)
def test_branching_on_measurement_bit_passses_with_required_capability():
circuit = conditional_branch_on_bit()
_ = circuit_to_qir(circuit)
def test_reuse_after_measurement_fails_without_required_capability():
circuit = use_after_measure()
with pytest.raises(QubitUseAfterMeasurementError) as exc_info:
_ = circuit_to_qir(circuit, "BasicExecution")
exception_raised = exc_info.value
assert (
str(exception_raised.instruction)
== "Instruction(name='h', num_qubits=1, num_clbits=0, params=[])"
)
assert exception_raised.instruction.condition is None
assert str(exception_raised.qargs) == "[Qubit(QuantumRegister(2, 'qq'), 1)]"
assert str(exception_raised.cargs) == "[]"
assert str(exception_raised.profile) == "BasicExecution"
assert exception_raised.instruction_string == "h qq[1]"
def test_reuse_after_measurement_passes_with_required_capability():
circuit = use_after_measure()
_ = circuit_to_qir(circuit)
def test_using_an_unread_qubit_after_measuring_passes_without_required_capability():
circuit = use_another_after_measure()
_ = circuit_to_qir(circuit, "BasicExecution")
def test_use_another_after_measure_and_condition_passes_with_required_capability():
circuit = use_another_after_measure_and_condition()
_ = circuit_to_qir(circuit)
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from qiskit_qir.translate import to_qir_module
from qiskit import ClassicalRegister, QuantumCircuit
from qiskit.circuit import Clbit
from qiskit.circuit.exceptions import CircuitError
import pytest
import pyqir
import os
from pathlib import Path
# result_stream, condition value, expected gates
falsy_single_bit_variations = [False, 0]
truthy_single_bit_variations = [True, 1]
invalid_single_bit_varitions = [-1]
def compare_reference_ir(generated_bitcode: bytes, name: str) -> None:
module = pyqir.Module.from_bitcode(pyqir.Context(), generated_bitcode, f"{name}")
ir = str(module)
file = os.path.join(os.path.dirname(__file__), f"resources/{name}.ll")
expected = Path(file).read_text()
assert ir == expected
@pytest.mark.parametrize("value", falsy_single_bit_variations)
def test_single_clbit_variations_falsy(value: bool) -> None:
circuit = QuantumCircuit(2, 0, name=f"test_single_clbit_variations")
cr = ClassicalRegister(2, "creg")
circuit.add_register(cr)
circuit.measure(0, 0)
bit: Clbit = cr[0]
circuit.measure(1, 1).c_if(bit, value)
generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode
compare_reference_ir(generated_bitcode, "test_single_clbit_variations_falsy")
@pytest.mark.parametrize("value", truthy_single_bit_variations)
def test_single_clbit_variations_truthy(value: bool) -> None:
circuit = QuantumCircuit(2, 0, name=f"test_single_clbit_variations")
cr = ClassicalRegister(2, "creg")
circuit.add_register(cr)
circuit.measure(0, 0)
bit: Clbit = cr[0]
circuit.measure(1, 1).c_if(bit, value)
generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode
compare_reference_ir(generated_bitcode, "test_single_clbit_variations_truthy")
@pytest.mark.parametrize("value", truthy_single_bit_variations)
def test_single_register_index_variations_truthy(value: bool) -> None:
circuit = QuantumCircuit(2, 0, name=f"test_single_register_index_variations")
cr = ClassicalRegister(2, "creg")
circuit.add_register(cr)
circuit.measure(0, 0)
circuit.measure(1, 1).c_if(0, value)
generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode
compare_reference_ir(
generated_bitcode, "test_single_register_index_variations_truthy"
)
@pytest.mark.parametrize("value", falsy_single_bit_variations)
def test_single_register_index_variations_falsy(value: bool) -> None:
circuit = QuantumCircuit(2, 0, name=f"test_single_register_index_variations")
cr = ClassicalRegister(2, "creg")
circuit.add_register(cr)
circuit.measure(0, 0)
circuit.measure(1, 1).c_if(0, value)
generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode
compare_reference_ir(
generated_bitcode, "test_single_register_index_variations_falsy"
)
@pytest.mark.parametrize("value", truthy_single_bit_variations)
def test_single_register_variations_truthy(value: bool) -> None:
circuit = QuantumCircuit(2, 0, name=f"test_single_register_variations")
cr = ClassicalRegister(2, "creg")
circuit.add_register(cr)
circuit.measure(0, 0)
circuit.measure(1, 1).c_if(cr, value)
generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode
compare_reference_ir(generated_bitcode, "test_single_register_variations_truthy")
@pytest.mark.parametrize("value", falsy_single_bit_variations)
def test_single_register_variations_falsy(value: bool) -> None:
circuit = QuantumCircuit(2, 0, name=f"test_single_register_variations")
cr = ClassicalRegister(2, "creg")
circuit.add_register(cr)
circuit.measure(0, 0)
circuit.measure(1, 1).c_if(cr, value)
generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode
compare_reference_ir(generated_bitcode, "test_single_register_variations_falsy")
@pytest.mark.parametrize("value", invalid_single_bit_varitions)
def test_single_clbit_invalid_variations(value: int) -> None:
circuit = QuantumCircuit(2, 0, name=f"test_single_clbit_invalid_variations")
cr = ClassicalRegister(2, "creg")
circuit.add_register(cr)
circuit.measure(0, 0)
bit: Clbit = cr[0]
with pytest.raises(CircuitError) as exc_info:
_ = circuit.measure(1, 1).c_if(bit, value)
assert exc_info is not None
@pytest.mark.parametrize("value", invalid_single_bit_varitions)
def test_single_register_index_invalid_variations(value: int) -> None:
circuit = QuantumCircuit(
2,
0,
name=f"test_single_register_index_invalid_variations",
)
cr = ClassicalRegister(2, "creg")
circuit.add_register(cr)
circuit.measure(0, 0)
with pytest.raises(CircuitError) as exc_info:
_ = circuit.measure(1, 1).c_if(0, value)
assert exc_info is not None
@pytest.mark.parametrize("value", invalid_single_bit_varitions)
def test_single_register_invalid_variations(value: int) -> None:
circuit = QuantumCircuit(2, 0, name=f"test_single_register_invalid_variations")
cr = ClassicalRegister(2, "creg")
circuit.add_register(cr)
circuit.measure(0, 0)
with pytest.raises(CircuitError) as exc_info:
_ = circuit.measure(1, 1).c_if(cr, value)
assert exc_info is not None
two_bit_variations = [
[False, "falsy"],
[0, "falsy"],
[True, "truthy"],
[1, "truthy"],
[2, "two"],
[3, "three"],
]
# # -1: 11
# # -2: 10
# # -3: 01
# # -4: 00
invalid_two_bit_variations = [-4, -3, -2, -1]
@pytest.mark.parametrize("matrix", two_bit_variations)
def test_two_bit_register_variations(matrix) -> None:
value, name = matrix
circuit = QuantumCircuit(
3,
0,
name=f"test_two_bit_register_variations",
)
cr = ClassicalRegister(2, "creg")
circuit.add_register(cr)
cond = ClassicalRegister(1, "cond")
circuit.add_register(cond)
circuit.measure(0, 0)
circuit.measure(1, 1)
circuit.measure(2, 2).c_if(cr, value)
generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode
compare_reference_ir(generated_bitcode, f"test_two_bit_register_variations_{name}")
@pytest.mark.parametrize("value", invalid_two_bit_variations)
def test_two_bit_register_invalid_variations(value: int) -> None:
circuit = QuantumCircuit(
3,
0,
name=f"test_two_bit_register_invalid_variations",
)
cr = ClassicalRegister(2, "creg")
circuit.add_register(cr)
cond = ClassicalRegister(1, "cond")
circuit.add_register(cond)
circuit.measure(0, 0)
circuit.measure(1, 1)
with pytest.raises(CircuitError) as exc_info:
_ = circuit.measure(2, 2).c_if(cr, value)
assert exc_info is not None
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from qiskit_qir.translate import to_qir_module
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import test_utils
def test_single_array():
circuit = QuantumCircuit(3, 3)
circuit.name = "test_single_array"
circuit.h(1)
circuit.s(2)
circuit.t(0)
circuit.measure([0, 1, 2], [2, 0, 1])
generated_qir = str(to_qir_module(circuit)[0]).splitlines()
test_utils.check_attributes(generated_qir, 3, 3)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.single_op_call_string("h", 1)
assert func[2] == test_utils.single_op_call_string("s", 2)
assert func[3] == test_utils.single_op_call_string("t", 0)
assert func[4] == test_utils.measure_call_string("mz", 2, 0)
assert func[5] == test_utils.measure_call_string("mz", 0, 1)
assert func[6] == test_utils.measure_call_string("mz", 1, 2)
assert func[7] == test_utils.array_record_output_string(3)
assert func[8] == test_utils.result_record_output_string(2)
assert func[9] == test_utils.result_record_output_string(1)
assert func[10] == test_utils.result_record_output_string(0)
assert func[11] == test_utils.return_string()
assert len(func) == 12
def test_no_measure_with_no_registers():
circuit = QuantumCircuit(1, 0)
circuit.name = "test_no_measure_with_no_registers"
circuit.h(0)
generated_qir = str(to_qir_module(circuit)[0]).splitlines()
test_utils.check_attributes(generated_qir, 1, 0)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.single_op_call_string("h", 0)
assert func[2] == test_utils.return_string()
assert len(func) == 3
def test_no_measure_with_register():
circuit = QuantumCircuit(1, 1)
circuit.name = "test_no_measure_with_register"
circuit.h(0)
generated_qir = str(to_qir_module(circuit)[0]).splitlines()
test_utils.check_attributes(generated_qir, 1, 1)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.single_op_call_string("h", 0)
assert func[2] == test_utils.array_record_output_string(1)
assert func[3] == test_utils.result_record_output_string(0)
assert func[4] == test_utils.return_string()
assert len(func) == 5
def test_branching_on_bit_emits_correct_ir():
qr = QuantumRegister(1, "qreg")
cr = ClassicalRegister(1, "creg")
circuit = QuantumCircuit(qr, cr, name="branching_on_bit_emits_correct_ir")
circuit.x(0)
circuit.measure(0, 0)
circuit.x(0).c_if(cr[0], 1)
ir = str(to_qir_module(circuit)[0])
generated_qir = ir.splitlines()
test_utils.check_attributes(generated_qir, 1, 1)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.single_op_call_string("x", 0)
assert func[2] == test_utils.measure_call_string("mz", 0, 0)
assert func[3] == test_utils.equal("0", 0)
assert func[4] == f"br i1 %0, label %then, label %else"
assert func[5] == ""
assert (
func[6] == f"then: ; preds = %entry"
)
assert func[7] == test_utils.single_op_call_string("x", 0)
assert func[8] == f"br label %continue"
assert func[9] == ""
assert (
func[10]
== f"else: ; preds = %entry"
)
assert func[11] == f"br label %continue"
assert func[12] == ""
assert (
func[13]
== f"continue: ; preds = %else, %then"
)
assert func[14] == test_utils.array_record_output_string(1)
assert func[15] == test_utils.result_record_output_string(0)
assert func[16] == test_utils.return_string()
assert len(func) == 17
def test_branching_on_register_with_one_bit_emits_correct_ir():
qr = QuantumRegister(1, "qreg")
cr = ClassicalRegister(1, "creg")
circuit = QuantumCircuit(
qr, cr, name="branching_on_register_with_one_bit_emits_correct_ir"
)
circuit.x(0)
circuit.measure(0, 0)
circuit.x(0).c_if(cr, 1)
ir = str(to_qir_module(circuit)[0])
generated_qir = ir.splitlines()
test_utils.check_attributes(generated_qir, 1, 1)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.single_op_call_string("x", 0)
assert func[2] == test_utils.measure_call_string("mz", 0, 0)
assert func[3] == test_utils.equal("0", 0)
assert func[4] == f"br i1 %0, label %then, label %else"
assert func[5] == ""
assert (
func[6] == f"then: ; preds = %entry"
)
assert func[7] == test_utils.single_op_call_string("x", 0)
assert func[8] == f"br label %continue"
assert func[9] == ""
assert (
func[10]
== f"else: ; preds = %entry"
)
assert func[11] == f"br label %continue"
assert func[12] == ""
assert (
func[13]
== f"continue: ; preds = %else, %then"
)
assert func[14] == test_utils.array_record_output_string(1)
assert func[15] == test_utils.result_record_output_string(0)
assert func[16] == test_utils.return_string()
assert len(func) == 17
def test_no_measure_without_registers():
circuit = QuantumCircuit(1)
circuit.name = "test_no_measure_no_registers"
circuit.h(0)
generated_qir = str(to_qir_module(circuit)[0]).splitlines()
test_utils.check_attributes(generated_qir, 1, 0)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.single_op_call_string("h", 0)
assert func[2] == test_utils.return_string()
assert len(func) == 3
def test_measurement_into_multiple_registers_is_mapped_correctly():
cr0 = ClassicalRegister(2, "first")
cr1 = ClassicalRegister(3, "second")
circuit = QuantumCircuit(5)
circuit.add_register(cr0)
circuit.add_register(cr1)
circuit.name = "measurement_into_multiple_registers"
circuit.h(0)
circuit.measure([0, 0], [0, 2])
generated_qir = str(to_qir_module(circuit)[0]).splitlines()
test_utils.check_attributes(generated_qir, 5, 5)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.single_op_call_string("h", 0)
assert func[2] == test_utils.measure_call_string("mz", 0, 0)
assert func[3] == test_utils.measure_call_string("mz", 2, 0)
assert func[4] == test_utils.array_record_output_string(2)
assert func[5] == test_utils.result_record_output_string(1)
assert func[6] == test_utils.result_record_output_string(0)
assert func[7] == test_utils.array_record_output_string(3)
assert func[8] == test_utils.result_record_output_string(4)
assert func[9] == test_utils.result_record_output_string(3)
assert func[10] == test_utils.result_record_output_string(2)
assert func[11] == test_utils.return_string()
assert len(func) == 12
def test_using_static_allocation_is_mapped_correctly():
circuit = QuantumCircuit(1, 1)
circuit.h(0)
circuit.measure(0, 0)
ir = str(to_qir_module(circuit)[0])
generated_qir = ir.splitlines()
test_utils.check_attributes(generated_qir, 1, 1)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.single_op_call_string("h", 0)
assert func[2] == test_utils.measure_call_string("mz", 0, 0)
assert func[3] == test_utils.array_record_output_string(1)
assert func[4] == test_utils.result_record_output_string(0)
assert func[5] == test_utils.return_string()
assert len(func) == 6
def test_record_output_when_true_mapped_correctly():
circuit = QuantumCircuit(1, 1)
circuit.h(0)
circuit.measure(0, 0)
ir = str(to_qir_module(circuit, record_output=True)[0])
generated_qir = ir.splitlines()
test_utils.check_attributes(generated_qir, 1, 1)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.single_op_call_string("h", 0)
assert func[2] == test_utils.measure_call_string("mz", 0, 0)
assert func[3] == test_utils.array_record_output_string(1)
assert func[4] == test_utils.result_record_output_string(0)
assert func[5] == test_utils.return_string()
assert len(func) == 6
def test_record_output_when_false_mapped_correctly():
circuit = QuantumCircuit(1, 1)
circuit.h(0)
circuit.measure(0, 0)
ir = str(to_qir_module(circuit, record_output=False)[0])
generated_qir = ir.splitlines()
test_utils.check_attributes(generated_qir, 1, 1)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.single_op_call_string("h", 0)
assert func[2] == test_utils.measure_call_string("mz", 0, 0)
assert func[3] == test_utils.return_string()
assert len(func) == 4
def test_barrier_default_bypass():
circuit = QuantumCircuit(1)
circuit.barrier()
circuit.x(0)
ir = str(to_qir_module(circuit)[0])
generated_qir = ir.splitlines()
test_utils.check_attributes(generated_qir, 1, 0)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.single_op_call_string("x", 0)
assert func[2] == test_utils.return_string()
assert len(func) == 3
def test_barrier_with_qubits_default_bypass():
circuit = QuantumCircuit(3)
circuit.barrier([2, 0, 1])
circuit.x(0)
ir = str(to_qir_module(circuit)[0])
generated_qir = ir.splitlines()
test_utils.check_attributes(generated_qir, 3, 0)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.single_op_call_string("x", 0)
assert func[2] == test_utils.return_string()
assert len(func) == 3
def test_barrier_with_override():
circuit = QuantumCircuit(1)
circuit.barrier()
ir = str(to_qir_module(circuit, emit_barrier_calls=True)[0])
generated_qir = ir.splitlines()
test_utils.check_attributes(generated_qir, 1, 0)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.generic_op_call_string("barrier", [])
assert func[2] == test_utils.return_string()
assert len(func) == 3
def test_barrier_with_qubits_with_override():
circuit = QuantumCircuit(3)
circuit.barrier([2, 0, 1])
ir = str(to_qir_module(circuit, emit_barrier_calls=True)[0])
generated_qir = ir.splitlines()
test_utils.check_attributes(generated_qir, 3, 0)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.generic_op_call_string("barrier", [])
assert func[2] == test_utils.return_string()
assert len(func) == 3
def test_swap():
circuit = QuantumCircuit(3)
circuit.swap(2, 0)
ir = str(to_qir_module(circuit)[0])
generated_qir = ir.splitlines()
test_utils.check_attributes(generated_qir, 3, 0)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.double_op_call_string("swap", 2, 0)
assert func[2] == test_utils.return_string()
assert len(func) == 3
def test_ccx():
circuit = QuantumCircuit(3)
circuit.ccx(2, 0, 1)
ir = str(to_qir_module(circuit)[0])
generated_qir = ir.splitlines()
test_utils.check_attributes(generated_qir, 3, 0)
func = test_utils.get_entry_point_body(generated_qir)
assert func[0] == test_utils.initialize_call_string()
assert func[1] == test_utils.generic_op_call_string("ccx", [2, 0, 1])
assert func[2] == test_utils.return_string()
assert len(func) == 3
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from builtins import format
import pytest
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
@pytest.fixture()
def ghz():
circuit = QuantumCircuit(4, 3)
circuit.name = "Qiskit Sample - 3-qubit GHZ circuit"
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.measure([0, 1, 2], [0, 1, 2])
return circuit
@pytest.fixture()
def teleport():
q = QuantumRegister(3, name="q")
cr = ClassicalRegister(2, name="cr")
circuit = QuantumCircuit(q, cr, name="Teleport")
circuit.h(1)
circuit.cx(1, 2)
circuit.cx(0, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.measure(1, 1)
circuit.x(2).c_if(cr, int("10", 2))
circuit.z(2).c_if(cr, int("01", 2))
return circuit
@pytest.fixture()
def unroll():
circ = QuantumCircuit(3)
circ.ccx(0, 1, 2)
circ.crz(theta=0.1, control_qubit=0, target_qubit=1)
circ.id(2)
return circ.decompose()
@pytest.fixture()
def teleport_with_subroutine():
bell_circ = QuantumCircuit(2, name="CreateBellPair")
bell_circ.h(0)
bell_circ.cx(0, 1)
q = QuantumRegister(3, name="q")
cr = ClassicalRegister(2, name="cr")
circuit = QuantumCircuit(q, cr, name="Teleport")
circuit.append(bell_circ.to_instruction(), [1, 2])
circuit.cx(0, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.measure(1, 1)
circuit.x(2).c_if(cr, int("10", 2))
circuit.z(2).c_if(cr, int("01", 2))
return circuit
@pytest.fixture()
def bernstein_vazirani_with_delay():
num_qubits = 5
qq = QuantumRegister(num_qubits + 1, name="qq")
cr = ClassicalRegister(num_qubits, name="cr")
circuit = QuantumCircuit(qq, cr, name="Bernstein-Vazirani")
circuit.h(num_qubits)
circuit.z(num_qubits)
for index in range(num_qubits):
circuit.h(index)
circuit.delay(42, qq[0], "ps")
oracle = format(2, "b").zfill(num_qubits)
oracle = oracle[::-1]
for index in range(num_qubits):
if oracle[index] == "0":
circuit.id(index)
else:
circuit.cx(index, num_qubits)
circuit.delay(23, 2, "ms")
for index in range(num_qubits):
circuit.h(index)
for index in range(num_qubits):
circuit.measure(index, index)
return circuit
@pytest.fixture()
def ghz_with_delay():
qq = QuantumRegister(4, name="qq")
cr = ClassicalRegister(3, name="cr")
circuit = QuantumCircuit(qq, cr)
circuit.name = "Qiskit Sample - 3-qubit GHZ circuit"
circuit.delay(23.54, None, "us")
circuit.h(0)
circuit.delay(42, qq[0], "ps")
circuit.cx(0, 1)
circuit.delay(23, 2, "ms")
circuit.cx(1, 2)
circuit.delay(3, qq[1])
circuit.measure([0, 1, 2], [0, 1, 2])
return circuit
@pytest.fixture()
def measure_x_as_subroutine():
measure_x_circuit = QuantumCircuit(1, 1, name="measure_x")
measure_x_circuit.h(0)
measure_x_circuit.measure(0, 0)
measure_x_circuit.h(0)
measure_x_gate = measure_x_circuit.to_instruction()
qq = QuantumRegister(1, name="qq")
cr = ClassicalRegister(1, name="cr")
circuit = QuantumCircuit(qq, cr)
circuit.name = "Qiskit Sample - Measure in the X-basis as a subroutine"
circuit.append(measure_x_gate, [0], [0])
return circuit
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
#--------------------------------------------------------------------------------------------------------------
# This module contains basic gates that can be used while developing circuits on IBM QExperience
#--------------------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------------------
# Import necessary modules
#--------------------------------------------------------------------------------------------------------------
from qiskit import QuantumProgram
import Qconfig
#--------------------------------------------------------------------------------------------------------------
# The CSWAP gate
# Input : Quantum program object, the Circuit name, the quantum register name, control bit number and target
# bit numbers.
# Output : Quantum_program_object with the relevant connections
# Circuit implemented - CSWAP
#--------------------------------------------------------------------------------------------------------------
def CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,Target_bit_numbers):
# Get the circuit and the quantum register by name
qc = Quantum_program_object.get_circuit(Circuit_name)
qr = Quantum_program_object.get_quantum_register(Quantum_register_name)
# Get control bit numbers and the target bit number for the addressing the qubits
Control = Control_bit_number
Target_1 = Target_bit_numbers[0]
Target_2 = Target_bit_numbers[1]
# Implement CSWAP using 3 CCNOT implementations
# Implement CCNOT on Control,Target_1 and Target_2 using decomposition given by Nelson and Chuang
qc.h(qr[Target_2])
qc.cx(qr[Target_1],qr[Target_2])
qc.tdg(qr[Target_2])
qc.cx(qr[Control],qr[Target_2])
qc.t(qr[Target_2])
qc.cx(qr[Target_1],qr[Target_2])
qc.tdg(qr[Target_2])
qc.cx(qr[Control],qr[Target_2])
qc.tdg(qr[Target_1])
qc.t(qr[Target_2])
qc.h(qr[Target_2])
qc.cx(qr[Control],qr[Target_1])
qc.tdg(qr[Target_1])
qc.cx(qr[Control],qr[Target_1])
qc.t(qr[Control])
qc.s(qr[Target_1])
# Implement CCNOT on Control,Target_2 and Target_1 using decomposition given by Nelson and Chuang
qc.h(qr[Target_1])
qc.cx(qr[Target_2],qr[Target_1])
qc.tdg(qr[Target_1])
qc.cx(qr[Control],qr[Target_1])
qc.t(qr[Target_1])
qc.cx(qr[Target_2],qr[Target_1])
qc.tdg(qr[Target_1])
qc.cx(qr[Control],qr[Target_1])
qc.tdg(qr[Target_2])
qc.t(qr[Target_1])
qc.h(qr[Target_1])
qc.cx(qr[Control],qr[Target_2])
qc.tdg(qr[Target_2])
qc.cx(qr[Control],qr[Target_2])
qc.t(qr[Control])
qc.s(qr[Target_2])
# Implement CCNOT on Control,Target_1 and Target_2 using decomposition given by Nelson and Chuang
qc.h(qr[Target_2])
qc.cx(qr[Target_1],qr[Target_2])
qc.tdg(qr[Target_2])
qc.cx(qr[Control],qr[Target_2])
qc.t(qr[Target_2])
qc.cx(qr[Target_1],qr[Target_2])
qc.tdg(qr[Target_2])
qc.cx(qr[Control],qr[Target_2])
qc.tdg(qr[Target_1])
qc.t(qr[Target_2])
qc.h(qr[Target_2])
qc.cx(qr[Control],qr[Target_1])
qc.tdg(qr[Target_1])
qc.cx(qr[Control],qr[Target_1])
qc.t(qr[Control])
qc.s(qr[Target_1])
# Return the program object
return Quantum_program_object
#--------------------------------------------------------------------------------------------------------------
# The CCNOT gate
# Input : Quantum program object, the Circuit name, the quantum register name, control bit numbers and target
# bit number.
# Output : Quantum_program_object with the relevant connections
# Circuit implemented - CCNOT
#--------------------------------------------------------------------------------------------------------------
def CCNOT(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_numbers,Target_bit_number):
# Get the circuit and the quantum register by name
qc = Quantum_program_object.get_circuit(Circuit_name)
qr = Quantum_program_object.get_quantum_register(Quantum_register_name)
# Get control bit numbers and the target bit number for the addressing the qubits
Control_1 = Control_bit_numbers[0]
Control_2 = Control_bit_numbers[1]
Target = Target_bit_number
# Implement Hadamard on target qubits
qc.h(qr[Target])
# Implement CNOT between Control_2 and Target
qc.cx(qr[Control_2],qr[Target])
# Implement T (dagger) on target qubits
qc.tdg(qr[Target])
# Implement CNOT between Control_1 and Target
qc.cx(qr[Control_1],qr[Target])
# Implement T on target qubits
qc.t(qr[Target])
# Implement CNOT between Control_2 and Target
qc.cx(qr[Control_2],qr[Target])
# Implement T (dagger) on target qubits
qc.tdg(qr[Target])
# Implement CNOT between Control_1 and Target
qc.cx(qr[Control_1],qr[Target])
# Implement T (dagger) on Control_2, T and H on Target
qc.tdg(qr[Control_2])
qc.t(qr[Target])
qc.h(qr[Target])
# Implement CNOT from Control_1 to Control_2 followed by T (dagger) on Control_2
qc.cx(qr[Control_1],qr[Control_2])
qc.tdg(qr[Control_2])
# Implement CNOT from Control_1 to Control_2 followed by T on Control_1 and S on Control_2
qc.cx(qr[Control_1],qr[Control_2])
qc.t(qr[Control_1])
qc.s(qr[Control_2])
# Return the program object
return Quantum_program_object
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
import pytest
from qiskit import QuantumCircuit
@pytest.fixture()
def while_loop():
circuit = QuantumCircuit(1, 1)
circuit.name = "Simple while-loop circuit"
with circuit.while_loop((circuit.clbits[0], 0)):
circuit.h(0)
circuit.measure(0, 0)
return circuit
@pytest.fixture()
def for_loop():
circuit = QuantumCircuit(4, 0)
circuit.name = "Simple for-loop circuit"
circuit.h(3)
with circuit.for_loop(range(3)):
# Qiskit doesn't (yet) support cnot(3, i)
circuit.cx(3, 0)
return circuit
@pytest.fixture()
def if_else():
circuit = QuantumCircuit(3, 2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure(0, 0)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure(0, 1)
with circuit.if_test((circuit.clbits[0], 0)) as else_:
circuit.x(2)
with else_:
circuit.h(2)
circuit.z(2)
return circuit
cf_fixtures = ["while_loop", "for_loop", "if_else"]
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
"""Docstring."""
from qiskit import QuantumCircuit, execute, QuantumRegister, ClassicalRegister
from qiskit_aer import Aer
class Random:
"""Demo random."""
def __init__(self):
"""Demo random."""
self.pow = 2
self.qasm = Aer.get_backend("aer_simulator")
def run(self, number: int) -> int:
"""Run method."""
nb_qubits = number
print("Generate random number")
circ = QuantumRegister(nb_qubits, "the number")
meas = ClassicalRegister(nb_qubits, "measurement")
quant_circ = QuantumCircuit(circ, meas)
for i in range(0, nb_qubits):
quant_circ.x(i)
quant_circ.measure(circ, meas)
job = execute(quant_circ, self.qasm, shots=1, memory=True)
result_sim = job.result()
memory = result_sim.get_memory()
result = int(memory[0], 2) + 1
return result
def __repr__(self):
return f"Random(circuit of: {self.pow})"
|
https://github.com/Qiskit/qiskit-qasm3-import
|
Qiskit
|
import qiskit_qasm3_import
project = 'Qiskit OpenQASM 3 Importer'
copyright = '2022, Jake Lishman'
author = 'Jake Lishman'
version = qiskit_qasm3_import.__version__
release = qiskit_qasm3_import.__version__
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"reno.sphinxext",
'qiskit_sphinx_theme',
]
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# Document the docstring for the class and the __init__ method together.
autoclass_content = "both"
html_theme = "qiskit-ecosystem"
html_title = f"{project} {release}"
intersphinx_mapping = {
"qiskit-terra": ("https://docs.quantum.ibm.com/api/qiskit/", None),
}
|
https://github.com/Qiskit/qiskit-qasm3-import
|
Qiskit
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may obtain a copy of this license
# in the LICENSE.txt file in the root directory of this source tree or at
# http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this copyright notice, and modified
# files need to carry a notice indicating that they have been altered from the originals.
import openqasm3
from qiskit import QuantumCircuit
from .converter import ConvertVisitor
def convert(node: openqasm3.ast.Program) -> QuantumCircuit:
"""Convert a parsed OpenQASM 3 program in AST form, into a Qiskit
:class:`~qiskit.circuit.QuantumCircuit`."""
return ConvertVisitor().convert(node).circuit
def parse(string: str, /) -> QuantumCircuit:
"""Wrapper around :func:`.convert`, which first parses the OpenQASM 3 program into AST form, and
then converts the output to Qiskit format."""
return convert(openqasm3.parse(string))
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
# for loading execution context parameters from the environment
import os
from dotenv import load_dotenv
# for (de)serializing results
import json
# for processing data
import numpy as np
# for plotting results
import matplotlib as mpl
import matplotlib.pyplot as plt
# for defining the circuits and observables constituting our expectation value problems
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.quantum_info import SparsePauliOp
# for using real quantum hardware
from qiskit import IBMQ, transpile
from qiskit_ibm_runtime import QiskitRuntimeService
from zne import ZNEStrategy
from zne import Estimator as ZneEstimator
from zne.noise_amplification import NoiseAmplifier
load_dotenv()
TOKEN = os.environ["TOKEN"]
HUB = os.environ["HUB"]
GROUP = os.environ["GROUP"]
PROJECT = os.environ["PROJECT"]
BACKEND = os.environ["BACKEND"]
service = QiskitRuntimeService(channel="ibm_quantum", instance=f"{HUB}/{GROUP}/{PROJECT}", token=TOKEN)
IBMQ.enable_account(TOKEN)
provider = IBMQ.get_provider(hub=HUB, group=GROUP, project=PROJECT)
backend = provider.get_backend(BACKEND)
mpl.rcParams['figure.dpi'] = 500
plt.rcParams.update({
"text.usetex": True,
"font.family": "Computer Modern Roman"
})
def plot_trial(
noise_factors,
measured_evs,
measured_errors,
trial_id="A",
alpha=0.5,
color="#dc267f",
):
plt.plot(noise_factors, measured_evs, label=f"Measured (Trial {trial_id})", color=color)
plt.fill_between(
noise_factors,
measured_evs - measured_errors,
measured_evs + measured_errors,
alpha=alpha,
color=color,
linewidth=0
)
def show_experiment(
trials,
exact_ev,
experiment_repr,
observable_repr,
num_shots=4000,
ev_range=None
):
noise_factors = np.array(trials[0]["noise_factors"])
plt.plot([0, noise_factors[-1]], [exact_ev, exact_ev], "--", label=f"Exact", color="#000000")
for trial_id, color, measured_data in zip(('A', 'B'), ("#dc267f", "#785ef0"), trials):
measured_evs = np.array(measured_data["values"])
measured_errors = np.sqrt(np.array(measured_data["variances"]) / num_shots)
plot_trial(
noise_factors,
measured_evs,
measured_errors,
trial_id=trial_id,
color=color
)
plt.title(experiment_repr)
plt.xlabel("Noise Factor ($n$)")
plt.ylabel(f"Expectation Value ($\langle {observable_repr} \\rangle$)")
if ev_range:
plt.ylim(ev_range)
plt.legend()
plt.show()
class SingleGateFoldingAmplifier(NoiseAmplifier):
def __init__(self, gate_name: str):
self.gate_name = gate_name
def amplify_circuit_noise(self, circuit: QuantumCircuit, noise_factor: float) -> QuantumCircuit:
noisy_circuit = circuit.copy_empty_like()
for instruction, qargs, cargs in circuit:
if instruction.name == self.gate_name:
for i in range(noise_factor):
if i % 2 == 0:
noisy_circuit.append(instruction, qargs, cargs)
else:
noisy_circuit.append(instruction.inverse(), qargs, cargs)
noisy_circuit.barrier(qargs)
else:
noisy_circuit.append(instruction, qargs, cargs)
return noisy_circuit
x_circuit = QuantumCircuit(1)
x_circuit.x(0)
x_observable = SparsePauliOp.from_list([('Z', 1)])
x_exact_ev = -1.0
display(x_circuit.draw("mpl"))
print(x_observable)
print(x_exact_ev)
x_granular_noise_factors = tuple(range(1, 599 + 2, 2))
x_behavioral_noise_factors = tuple(range(1, 5999, 20))
# with ZneEstimator(
# circuits=[x_circuit],
# observables=[x_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=x_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()),
# ) as estimator:
# x_granular_a_results = estimator(
# circuits=[0],
# observables=[0],
# )
# x_granular_a_data = {
# "noise_factors": list(x_granular_a_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(x_granular_a_results.metadata[0]["zne"]["values"]),
# "variances": list(x_granular_a_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/x/x_granular_a.json', 'w') as f:
# json.dump(x_granular_a_data, f)
with open('data/x/x_granular_a.json', 'r') as f:
x_granular_a_data = json.load(f)
# with ZneEstimator(
# circuits=[x_circuit],
# observables=[x_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=x_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()),
# ) as estimator:
# x_granular_b_results = estimator(
# circuits=[0],
# observables=[0],
# )
# x_granular_b_data = {
# "noise_factors": list(x_granular_b_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(x_granular_b_results.metadata[0]["zne"]["values"]),
# "variances": list(x_granular_b_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/x/x_granular_b.json', 'w') as f:
# json.dump(x_granular_b_data, f)
with open('data/x/x_granular_b.json', 'r') as f:
x_granular_b_data = json.load(f)
# with ZneEstimator(
# circuits=[x_circuit],
# observables=[x_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=x_behavioral_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()),
# ) as estimator:
# x_behavioral_a_results = estimator(
# circuits=[0],
# observables=[0],
# )
# x_behavioral_a_data = {
# "noise_factors": list(x_behavioral_a_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(x_behavioral_a_results.metadata[0]["zne"]["values"]),
# "variances": list(x_behavioral_a_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/x/x_behavioral_a.json', 'w') as f:
# json.dump(x_behavioral_a_data, f)
with open('data/x/x_behavioral_a.json', 'r') as f:
x_behavioral_a_data = json.load(f)
# with ZneEstimator(
# circuits=[x_circuit],
# observables=[x_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=x_behavioral_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()),
# ) as estimator:
# x_behavioral_b_results = estimator(
# circuits=[0],
# observables=[0],
# )
# x_behavioral_b_data = {
# "noise_factors": list(x_behavioral_b_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(x_behavioral_b_results.metadata[0]["zne"]["values"]),
# "variances": list(x_behavioral_b_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/x/x_behavioral_b.json', 'w') as f:
# json.dump(x_behavioral_b_data, f)
with open('data/x/x_behavioral_b.json', 'r') as f:
x_behavioral_b_data = json.load(f)
show_experiment([x_granular_a_data, x_granular_b_data], x_exact_ev, "$X$ Granular Folding Profile — $\langle 0 | X^n Z X^n | 0 \\rangle(n)$", 'Z')
show_experiment([x_behavioral_a_data, x_behavioral_b_data], x_exact_ev, "$X$ Behavioral Folding Profile — $\langle 0 | X^n Z X^n | 0 \\rangle(n)$", 'Z')
sx_circuit = QuantumCircuit(1)
sx_circuit.sx(0)
sx_observable = SparsePauliOp.from_list([('Y', 1)])
sx_exact_ev = -1.0
display(sx_circuit.draw("mpl"))
print(sx_observable)
print(sx_exact_ev)
sx_granular_noise_factors = tuple(range(1, 599 + 2, 2))
sx_behavioral_noise_factors = tuple(range(1, 4999, 20))
# with ZneEstimator(
# circuits=[sx_circuit],
# observables=[sx_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=sx_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()),
# ) as estimator:
# sx_granular_a_results = estimator(
# circuits=[0],
# observables=[0],
# )
# sx_granular_a_data = {
# "noise_factors": list(sx_granular_a_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(sx_granular_a_results.metadata[0]["zne"]["values"]),
# "variances": list(sx_granular_a_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/sx/sx_granular_a.json', 'w') as f:
# json.dump(sx_granular_a_data, f)
with open('data/sx/sx_granular_a.json', 'r') as f:
sx_granular_a_data = json.load(f)
# with ZneEstimator(
# circuits=[sx_circuit],
# observables=[sx_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=sx_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()),
# ) as estimator:
# sx_granular_b_results = estimator(
# circuits=[0],
# observables=[0],
# )
# sx_granular_b_data = {
# "noise_factors": list(sx_granular_b_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(sx_granular_b_results.metadata[0]["zne"]["values"]),
# "variances": list(sx_granular_b_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/sx/sx_granular_b.json', 'w') as f:
# json.dump(sx_granular_b_data, f)
with open('data/sx/sx_granular_b.json', 'r') as f:
sx_granular_b_data = json.load(f)
# with ZneEstimator(
# circuits=[sx_circuit],
# observables=[sx_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=sx_behavioral_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()),
# ) as estimator:
# sx_behavioral_a_results = estimator(
# circuits=[0],
# observables=[0],
# )
# sx_behavioral_a_data = {
# "noise_factors": list(sx_behavioral_a_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(sx_behavioral_a_results.metadata[0]["zne"]["values"]),
# "variances": list(sx_behavioral_a_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/sx/sx_behavioral_a.json', 'w') as f:
# json.dump(sx_behavioral_a_data, f)
with open('data/sx/sx_behavioral_a.json', 'r') as f:
sx_behavioral_a_data = json.load(f)
# with ZneEstimator(
# circuits=[sx_circuit],
# observables=[sx_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=sx_behavioral_noise_factors, noise_amplifier=SingleGateFoldingAmplifier()),
# ) as estimator:
# sx_behavioral_b_results = estimator(
# circuits=[0],
# observables=[0],
# )
# sx_behavioral_b_data = {
# "noise_factors": list(sx_behavioral_b_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(sx_behavioral_b_results.metadata[0]["zne"]["values"]),
# "variances": list(sx_behavioral_b_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/sx/sx_behavioral_b.json', 'w') as f:
# json.dump(sx_behavioral_b_data, f)
with open('data/sx/sx_behavioral_b.json', 'r') as f:
sx_behavioral_b_data = json.load(f)
show_experiment([sx_granular_a_data, sx_granular_b_data], sx_exact_ev, "$\sqrt X$ Granular Folding Profile — $\langle 0|{\sqrt X}^nY{\sqrt X}^n|0\\rangle(n)$", 'Y')
show_experiment([sx_behavioral_a_data, sx_behavioral_b_data], sx_exact_ev, "$\sqrt X$ Behavioral Folding Profile — $\langle 0|{\sqrt X}^nY{\sqrt X}^n|0\\rangle(n)$", 'Y')
rz_theta = Parameter('theta')
rz_circuit = QuantumCircuit(1)
rz_circuit.h(0)
rz_circuit.rz(rz_theta, 0)
rz_circuit.h(0)
rz_observable = SparsePauliOp.from_list([('Z', 1)])
rz_theta = np.pi / 4
rz_exact_ev = np.cos(rz_theta)
display(rz_circuit.draw('mpl'))
print(rz_observable)
print(rz_theta)
print(rz_exact_ev)
rz_granular_noise_factors = tuple(range(1, 599 + 2, 2))
# with ZneEstimator(
# circuits=[rz_circuit],
# observables=[rz_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=rz_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier(gate_name='rz')),
# ) as estimator:
# rz_granular_a_results = estimator(
# circuits=[0],
# observables=[0],
# parameter_values=[rz_theta]
# )
# rz_granular_a_data = {
# "noise_factors": list(rz_granular_a_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(rz_granular_a_results.metadata[0]["zne"]["values"]),
# "variances": list(rz_granular_a_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/rz/rz_granular_a.json', 'w') as f:
# json.dump(rz_granular_a_data, f)
with open('data/rz/rz_granular_a.json', 'r') as f:
rz_granular_a_data = json.load(f)
# with ZneEstimator(
# circuits=[rz_circuit],
# observables=[rz_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=rz_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier(gate_name='rz')),
# ) as estimator:
# rz_granular_b_results = estimator(
# circuits=[0],
# observables=[0],
# parameter_values=[rz_theta]
# )
# rz_granular_b_data = {
# "noise_factors": list(rz_granular_b_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(rz_granular_b_results.metadata[0]["zne"]["values"]),
# "variances": list(rz_granular_b_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/rz/rz_granular_b.json', 'w') as f:
# json.dump(rz_granular_b_data, f)
with open('data/rz/rz_granular_b.json', 'r') as f:
rz_granular_b_data = json.load(f)
show_experiment([rz_granular_a_data, rz_granular_b_data], rz_exact_ev, "$R_Z$ Folding Profile — $\langle0|H{R_Z(-\\frac\pi4)}^nHZH{R_Z(\\frac\pi4)}^nH|0\\rangle(n)$", 'Z', ev_range=(0.5, 0.9))
cx_circuit = QuantumCircuit(2)
cx_circuit.x(0)
cx_circuit.cx(0, 1)
cx_observable = SparsePauliOp.from_list([('ZI', 1)])
cx_exact_ev = -1.0
display(cx_circuit.draw("mpl"))
print(cx_observable)
print(cx_exact_ev)
cx_granular_noise_factors = tuple(range(1, 599 + 2, 2))
cx_behavioral_noise_factors = tuple(range(1, 5999, 20))
# with ZneEstimator(
# circuits=[cx_circuit],
# observables=[cx_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=cx_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier(gate_name='cx')),
# ) as estimator:
# cx_granular_a_results = estimator(
# circuits=[0],
# observables=[0],
# )
# cx_granular_a_data = {
# "noise_factors": list(cx_granular_a_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(cx_granular_a_results.metadata[0]["zne"]["values"]),
# "variances": list(cx_granular_a_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/cx/cx_granular_a.json', 'w') as f:
# json.dump(cx_granular_a_data, f)
with open('data/cx/cx_granular_a.json', 'r') as f:
cx_granular_a_data = json.load(f)
# with ZneEstimator(
# circuits=[cx_circuit],
# observables=[cx_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=cx_granular_noise_factors, noise_amplifier=SingleGateFoldingAmplifier(gate_name='cx')),
# ) as estimator:
# cx_granular_b_results = estimator(
# circuits=[0],
# observables=[0],
# )
# cx_granular_b_data = {
# "noise_factors": list(cx_granular_b_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(cx_granular_b_results.metadata[0]["zne"]["values"]),
# "variances": list(cx_granular_b_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/cx/cx_granular_b.json', 'w') as f:
# json.dump(cx_granular_b_data, f)
with open('data/cx/cx_granular_b.json', 'r') as f:
cx_granular_b_data = json.load(f)
# with ZneEstimator(
# circuits=[cx_circuit],
# observables=[cx_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=cx_behavioral_noise_factors, noise_amplifier=SingleGateFoldingAmplifier(gate_name='cx')),
# ) as estimator:
# cx_behavioral_a_results = estimator(
# circuits=[0],
# observables=[0],
# )
# cx_behavioral_a_data = {
# "noise_factors": list(cx_behavioral_a_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(cx_behavioral_a_results.metadata[0]["zne"]["values"]),
# "variances": list(cx_behavioral_a_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/cx/cx_behavioral_a.json', 'w') as f:
# json.dump(cx_behavioral_a_data, f)
with open('data/cx/cx_behavioral_a.json', 'r') as f:
cx_behavioral_a_data = json.load(f)
# with ZneEstimator(
# circuits=[cx_circuit],
# observables=[cx_observable],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=cx_behavioral_noise_factors, noise_amplifier=SingleGateFoldingAmplifier(gate_name='cx')),
# ) as estimator:
# cx_behavioral_b_results = estimator(
# circuits=[0],
# observables=[0],
# )
# cx_behavioral_b_data = {
# "noise_factors": list(cx_behavioral_b_results.metadata[0]["zne"]["noise_factors"]),
# "values": list(cx_behavioral_b_results.metadata[0]["zne"]["values"]),
# "variances": list(cx_behavioral_b_results.metadata[0]["zne"]["variances"]),
# }
# with open('data/cx/cx_behavioral_b.json', 'w') as f:
# json.dump(cx_behavioral_b_data, f)
with open('data/cx/cx_behavioral_b.json', 'r') as f:
cx_behavioral_b_data = json.load(f)
show_experiment([cx_granular_a_data, cx_granular_b_data], cx_exact_ev, "$CX$ Granular Folding Profile — $\langle 00|(XI)({CX})^n(ZI)({CX})^n(XI)|00\\rangle(n)$", 'ZI')
show_experiment([cx_behavioral_a_data, cx_behavioral_b_data], cx_exact_ev, "$CX$ Behavioral Folding Profile — $\langle 00|(XI)({CX})^n(ZI)({CX})^n(XI)|00\\rangle(n)$", 'ZI')
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
# for loading execution context parameters from the environment
import os
from dotenv import load_dotenv
# for (de)serializing results
import json
# for processing data
import numpy as np
# for extrapolation
from scipy.optimize import curve_fit
# for plotting results
import matplotlib as mpl
import matplotlib.pyplot as plt
# for defining the circuits and observables constituting our expectation value problems
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.quantum_info import SparsePauliOp
from qiskit.circuit.library import TwoLocal
# for using real quantum hardware
from qiskit import IBMQ, transpile
from qiskit.primitives import Estimator
from qiskit_ibm_runtime import QiskitRuntimeService
from zne import ZNEStrategy
from zne import Estimator as ZneEstimator
from zne.noise_amplification import LocalFoldingAmplifier
load_dotenv()
TOKEN = os.environ["TOKEN"]
HUB = os.environ["HUB"]
GROUP = os.environ["GROUP"]
PROJECT = os.environ["PROJECT"]
BACKEND = os.environ["BACKEND"]
service = QiskitRuntimeService(channel="ibm_quantum", instance=f"{HUB}/{GROUP}/{PROJECT}", token=TOKEN)
IBMQ.enable_account(TOKEN)
provider = IBMQ.get_provider(hub=HUB, group=GROUP, project=PROJECT)
backend = provider.get_backend(BACKEND)
mpl.rcParams['figure.dpi'] = 500
plt.rcParams.update({
"text.usetex": True,
"font.family": "Computer Modern Roman"
})
def plot_results(
measured_data,
exact_ev,
experiment_repr,
observable_repr,
regime=None,
regression_model=None,
regression_guess=None,
exact_color="#000000",
measured_color="#dc267f",
regression_color="#785ef0"
):
if not regime: regime = len(measured_data["noise_factors"])
noise_factors = np.array(measured_data["noise_factors"][:regime])
measured_evs = np.array(measured_data["values"][:regime])
measured_errors = np.sqrt(np.array(measured_data["variances"][:regime]) / np.array(measured_data["num_shots"][:regime]))
plt.plot([0, noise_factors[regime-1]], [exact_ev, exact_ev], "--", label=f"Exact", color=exact_color)
unmitigated_ev = measured_evs[0]
unmitigated_error = np.abs(exact_ev - unmitigated_ev)
plt.errorbar([1], measured_evs[0], yerr=measured_errors[0], label=f"Unmitigated ($\Delta\left\langle H \\right\\rangle = {unmitigated_error:.3f}$)", fmt="s", color=measured_color)
plt.plot(noise_factors, measured_evs, label=f"Measured", color=measured_color)
plt.fill_between(
noise_factors,
measured_evs - measured_errors,
measured_evs + measured_errors,
alpha=0.5,
color=measured_color,
linewidth=0
)
if regression_model:
popt, pcov = curve_fit(regression_model, measured_data['noise_factors'][:regime], measured_data['values'][:regime], p0=regression_guess)
goodness_of_fit = np.linalg.norm(np.diag(pcov))
regression_domain = np.linspace(0, noise_factors[regime-1], 100)
plt.plot(regression_domain, regression_model(regression_domain, *popt), label=f"Regression", color=regression_color)
zne_ev = regression_model(0, *popt)
zne_error = np.abs(exact_ev - zne_ev)
plt.scatter([0], [zne_ev], label=f"Extrapolated ($\Delta\left\langle H \\right\\rangle = {zne_error:.3f}$)", marker="x", color=regression_color)
plt.title(experiment_repr)
plt.xlabel("Noise Factor ($n$)")
plt.ylabel(f"Expectation Value ($\langle {observable_repr} \\rangle$)")
plt.legend()
plt.show()
H2_GNDSTATE_WAVEFN = QuantumCircuit(2).compose(
TwoLocal(
rotation_blocks=["ry", "rz"], entanglement_blocks="cz", num_qubits=2
).assign_parameters(
[
4.104009273873245,
-6.046872443309065,
5.277223342332378,
1.5319564597237907,
4.893000083985066,
-3.0921586512224257,
-0.34939132286472496,
5.584790805066014,
-4.161687737508674,
-3.2391548739165845,
1.7436977108208878,
0.17441513089260774,
2.623695306064223,
0.03678956439381653,
2.410055788777767,
-2.3250358101154913,
]
)
)
H2_HAMILTONIAN = SparsePauliOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
H2_GNDSTATE_ENERGY = -1.85727503
NOISE_FACTORS = tuple(range(1, 199 + 2, 2))
len(NOISE_FACTORS)
with Estimator([H2_GNDSTATE_WAVEFN], [H2_HAMILTONIAN]) as estimator:
simulated_energy = estimator([0], [0]).values[0]
simulated_energy
np.isclose(simulated_energy, H2_GNDSTATE_ENERGY)
# with ZneEstimator(
# circuits=[H2_GNDSTATE_WAVEFN],
# observables=[H2_HAMILTONIAN],
# service=service,
# options={"backend": backend.name()},
# zne_strategy=ZNEStrategy(noise_factors=NOISE_FACTORS, noise_amplifier=LocalFoldingAmplifier()),
# ) as estimator:
# results = estimator(
# circuits=[0],
# observables=[0],
# )
# data = {
# "noise_factors": list(results.metadata[0]["zne"]["noise_factors"]),
# "values": list(results.metadata[0]["zne"]["values"]),
# "variances": list(results.metadata[0]["zne"]["variances"]),
# "num_shots": [ result["shots"] for result in results.metadata[0]['zne']['remaining_metadata'] ]
# }
# with open('data.json', 'w') as f:
# json.dump(data, f)
with open('data.json', 'r') as f:
data = json.load(f)
plot_results(data, H2_GNDSTATE_ENERGY, "$H_2$ Ground State Simulation", "H")
def linear(noise_factor, noiseless_ev, decay_rate):
return noiseless_ev + decay_rate * noise_factor
for regime in [3, 5, 20]:
plot_results(data, H2_GNDSTATE_ENERGY, "$H_2$ Ground State Simulation (Linear ZNE)", "H", regime=regime, regression_model=linear)
def damped_sinusoid(noise_factor, noiseless_ev, amplitude, frequency, decay_rate):
return noiseless_ev + amplitude * (
1 - np.cos(frequency * noise_factor) * np.exp(-decay_rate * noise_factor)
)
plot_results(data, H2_GNDSTATE_ENERGY, "$H_2$ Ground State Simulation (Damped Sinusoid ZNE)", "H", regression_model=damped_sinusoid, regression_guess=[data["values"][0], 1, (2*np.pi)/(60*4), 0.01])
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp("XZ")
print(f" > Observable: {observable.paulis}")
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(circuit, observable)
print(f">>> {job.job_id()}")
print(f">>> {job.status()}")
result = job.result()
print(f">>> {result}")
expval = result.values[0]
metadatum = result.metadata[0]
print(f" > Expectation value: {expval}")
print(f" > Metadata: {metadatum}")
circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
observable = SparsePauliOp("IY")
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]}")
circuits = (
random_circuit(2, 2, seed=0).decompose(reps=1),
random_circuit(2, 2, seed=1).decompose(reps=1),
)
observables = (
SparsePauliOp("XZ"),
SparsePauliOp("IY"),
)
job = estimator.run(circuits, observables)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f" > Observables: {[obs.paulis for obs in observables]}")
print(f" > Expectation values: {result.values.tolist()}")
print(f" > Metadata: {result.metadata}")
circuits = (
random_circuit(2, 2, seed=0).decompose(reps=1),
random_circuit(2, 2, seed=1).decompose(reps=1),
)
observables = (
SparsePauliOp("XZ"),
SparsePauliOp("IY"),
)
job_0 = estimator.run(circuits[0], observables[0])
job_1 = estimator.run(circuits[1], observables[1])
result_0 = job_0.result()
result_1 = job_1.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f" > Observables: {[obs.paulis for obs in observables]}")
print(f" > Expectation values [0]: {result_0.values.tolist()[0]}")
print(f" > Metadata [0]: {result_0.metadata[0]}")
print(f" > Expectation values [1]: {result_1.values.tolist()[0]}")
print(f" > Metadata [1]: {result_1.metadata[0]}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
observable = SparsePauliOp("ZI")
parameter_values = [0, 1, 2, 3, 4, 5]
job = estimator.run(circuit, observable, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Parameter values: {parameter_values}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
estimator = Estimator(options={"shots": 2048}) # Defaults !!!
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
observable = SparsePauliOp("XZ")
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]}")
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
observable = SparsePauliOp("XZ")
job = estimator.run(circuit, observable, shots=1024) # Job-only !!!
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 BackendEstimator
from qiskit.providers.fake_provider import FakeNairobi # Bring the noise!
backend = FakeNairobi()
estimator = BackendEstimator(backend)
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
observable = SparsePauliOp("XZ")
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]}")
import qiskit.tools.jupyter # pylint: disable=unused-import,wrong-import-order
%qiskit_version_table
%qiskit_copyright
|
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/qiskit-community/prototype-zne
|
qiskit-community
|
from warnings import filterwarnings
filterwarnings('ignore')
import json
import numpy.random as npr
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
# mpl.rcParams["figure.dpi"] = 300
# plt.rcParams.update({"text.usetex": True, "font.family": "Computer Modern Roman"})
from qiskit.circuit.library import TwoLocal
from qiskit.circuit.random import random_circuit
circuits = [
TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz").decompose(reps=1),
random_circuit(2, 4, seed=1).decompose(reps=1),
random_circuit(2, 2, seed=0).decompose(reps=1)
]
_ = [display(c.draw("mpl")) for c in circuits]
from qiskit.quantum_info import SparsePauliOp
observables = [
SparsePauliOp("ZZ"),
SparsePauliOp("XX"),
SparsePauliOp("YY"),
]
from qiskit.primitives import Estimator, BackendEstimator
from qiskit.providers.fake_provider import FakeNairobi as Backend
estimator = BackendEstimator(backend=Backend())
# measure expectation values of observable-0 and 1 on circuit-0 (with specified parameters)
job_0 = estimator.run(
circuits=[circuits[0]] * len(observables),
observables=observables,
parameter_values=[[*npr.random(16)]] * len(observables),
shots=2048,
)
# measure expectation values of observable-0 and 1 on circuit-1
job_1 = estimator.run(
circuits=[circuits[1]] * len(observables),
observables=observables,
shots=2048,
)
result_1 = job_1.result()
result_1
result_1 # print again for comparison on consecutive runs
from zne import zne
ZNEEstimator = zne(BackendEstimator) # Any implementation of BaseEstimator can be passed
from zne import ZNEStrategy
# from zne.noise_amplification import GlobalFoldingAmplifier, LocalFoldingAmplifier
# from zne.extrapolation import LinearExtrapolator, PolynomialExtrapolator
zne_strategy = ZNEStrategy(
noise_factors=(1, 3, 5),
# noise_amplifier = LocalFoldingAmplifier()
# extrapolator = LinearExtrapolator()
)
estimator = ZNEEstimator(
backend=Backend(),
zne_strategy=zne_strategy # !!!
)
# measure expectation values of observable-0 and 1 on circuit-0 (with specified parameters)
job_0 = estimator.run(
circuits=[circuits[0]] * len(observables),
observables=observables,
parameter_values=[[*npr.random(16)]] * len(observables),
shots=2048,
)
# measure expectation values of observable-0 and 1 on circuit-1
job_1 = estimator.run(
circuits=[circuits[1]] * len(observables),
observables=observables,
shots=2048,
)
result_1 = job_1.result()
result_1
from zne.utils.serialization import EstimatorResultEncoder
print(EstimatorResultEncoder.dumps(result_1, indent=2))
from zne import NOISE_AMPLIFIER_LIBRARY
NOISE_AMPLIFIER_LIBRARY.keys()
from zne.noise_amplification import GlobalFoldingAmplifier, LocalFoldingAmplifier
mpl.rcParams["figure.dpi"] = 300
plt.rcParams.update({"text.usetex": True, "font.family": "Computer Modern Roman"})
noise_amplifier = GlobalFoldingAmplifier()
noisy_circuit = noise_amplifier.amplify_circuit_noise(circuit=circuits[2], noise_factor=1)
display(noisy_circuit.draw("mpl", plot_barriers=True))
noise_amplifier = LocalFoldingAmplifier()
noisy_circuit = noise_amplifier.amplify_circuit_noise(circuit=circuits[2], noise_factor=1)
display(noisy_circuit.draw("mpl", plot_barriers=False))
noise_amplifier = GlobalFoldingAmplifier(
sub_folding_option = "from_first",
# random_seed = 123,
)
noisy_circuit = noise_amplifier.amplify_circuit_noise(circuit=circuits[2], noise_factor=4)
display(noisy_circuit.draw("mpl", plot_barriers=True))
noise_amplifier = LocalFoldingAmplifier(
sub_folding_option = "from_first",
# random_seed = 123,
)
noisy_circuit = noise_amplifier.amplify_circuit_noise(circuit=circuits[2], noise_factor=4)
display(noisy_circuit.draw("mpl", plot_barriers=False))
noise_amplifier = LocalFoldingAmplifier(
gates_to_fold = 2, # Two-qubit gates
# gates_to_fold = "cx",
# gates_to_fold = ["cx", "rz"],
# gates_to_fold = [2, "rz"],
)
noisy_circuit = noise_amplifier.amplify_circuit_noise(circuit=circuits[2], noise_factor=3)
display(noisy_circuit.draw("mpl", plot_barriers=False))
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
zne_strategy = ZNEStrategy(
noise_amplifier=CustomAmplifier(),
noise_factors=(1, 3),
extrapolator=CustomExtrapolator(),
)
estimator = ZNEEstimator(backend=Backend(), zne_strategy=zne_strategy)
job = estimator.run(
circuits=circuits[1],
observables=observables[1],
)
result = job.result()
print(EstimatorResultEncoder.dumps(result, indent=2))
cir = circuits[1]
display(cir.draw("mpl"))
obs = observables[0]
print(obs)
noise_factors = range(1,9)
list(noise_factors)
from zne.extrapolation import PolynomialExtrapolator
## ZNE STRATEGY
noise_amplifier = LocalFoldingAmplifier(
gates_to_fold=2,
sub_folding_option='from_first',
)
extrapolator = PolynomialExtrapolator(
degree=2,
)
zne_strategy = ZNEStrategy(
noise_factors=noise_factors,
noise_amplifier=noise_amplifier,
extrapolator=extrapolator,
)
## CALCULATION
estimator = ZNEEstimator(backend=Backend(), zne_strategy=zne_strategy)
job = estimator.run(
circuits=cir,
observables=obs,
)
result = job.result()
############################ DATA ############################
exact = Estimator().run(cir, obs).result().values[0]
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/qiskit-community/prototype-zne
|
qiskit-community
|
## QISKIT
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.quantum_info import SparsePauliOp
from qiskit.primitives import Estimator, BackendEstimator
from qiskit.providers.fake_provider import FakeNairobi as Backend
## ZNE
from zne import zne, ZNEStrategy
from zne.noise_amplification import LocalFoldingAmplifier
from zne.extrapolation import PolynomialExtrapolator
## OTHER
import numpy as np
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"})
plt.rcParams.update({'font.size': 16})
## CIRCUIT
cir = QuantumCircuit(2)
cir.h(0)
cir.cx(0, 1)
cir.ry(Parameter("theta"), 0)
display(cir.draw("mpl"))
## THETA
theta_vec = np.linspace(-np.pi, np.pi, 15)
## OBSERVABLE
obs1 = SparsePauliOp(["ZZ", "ZX", "XZ", "XX"], [1, -1, +1, 1])
obs2 = SparsePauliOp(["ZZ", "ZX", "XZ", "XX"], [1, +1, -1, 1])
## IDEAL ESTIMATOR
estimator = Estimator()
## JOBS
job1 = estimator.run(
circuits = [cir] * len(theta_vec),
observables = [obs1] * len(theta_vec),
parameter_values = [[v] for v in theta_vec],
)
job2 = estimator.run(
circuits = [cir] * len(theta_vec),
observables = [obs2] * len(theta_vec),
parameter_values = [[v] for v in theta_vec],
)
## RESULTS
CHSH1_ideal = job1.result()
CHSH2_ideal = job2.result()
## NOISY ESTIMATOR
backend = Backend()
estimator = BackendEstimator(backend=backend)
## JOBS
job1 = estimator.run(
circuits = [cir] * len(theta_vec),
observables = [obs1] * len(theta_vec),
parameter_values = [[v] for v in theta_vec],
)
job2 = estimator.run(
circuits = [cir] * len(theta_vec),
observables = [obs2] * len(theta_vec),
parameter_values = [[v] for v in theta_vec],
)
## RESULTS
CHSH1_noisy = job1.result()
CHSH2_noisy = job2.result()
## MITIGATED ESTIMATOR
ZNEEstimator = zne(BackendEstimator)
zne_strategy = ZNEStrategy(
noise_factors=(1,7,13),
noise_amplifier=LocalFoldingAmplifier()
)
estimator = ZNEEstimator(backend=backend, zne_strategy=zne_strategy)
## JOBS
job1 = estimator.run(
circuits = [cir] * len(theta_vec),
observables = [obs1] * len(theta_vec),
parameter_values = [[v] for v in theta_vec],
)
job2 = estimator.run(
circuits = [cir] * len(theta_vec),
observables = [obs2] * len(theta_vec),
parameter_values = [[v] for v in theta_vec],
)
## RESULTS
CHSH1_mitigated = job1.result()
CHSH2_mitigated = job2.result()
## CONFIG
# plt.rcParams.update({'font.size': 22, 'lines.markersize': 10, 'lines.linewidth': 1.8})
plt.figure(figsize=(8,5))
## LIMITS
plt.axhline(y=2, color='r', linestyle='-')
plt.axhline(y=-2, color='r', linestyle='-')
plt.axhline(y=np.sqrt(2)*2, color='k', linestyle='-.')
plt.axhline(y=-np.sqrt(2)*2, color='k', linestyle='-.')
## PLOTS
plt.plot(theta_vec,CHSH1_ideal,'s-',label = 'CHSH1 Ideal')
plt.plot(theta_vec,CHSH2_ideal,'s-',label = 'CHSH2 Ideal')
plt.plot(theta_vec,CHSH1_mitigated,'^-',label = 'CHSH1 Mitigated')
plt.plot(theta_vec,CHSH2_mitigated,'^-',label = 'CHSH2 Mitigated')
plt.plot(theta_vec,CHSH1_noisy,'o-',label = 'CHSH1 Noisy')
plt.plot(theta_vec,CHSH2_noisy,'o-',label = 'CHSH2 Noisy')
## EMBELLISH
plt.title("Zero noise extrapolation on CHSH")
plt.xlabel('Theta')
plt.ylabel('CHSH witness')
plt.grid(which='major',axis='both')
plt.rcParams.update({'font.size': 11})
plt.legend()
plt.show()
print(" # | MITIGATED <- (NOISY DATA POINTS) \n" + "-" * 70)
for i in range(len(CHSH1_mitigated.values)):
print(
f"{i:2} | "
f"{CHSH1_mitigated.values[i]:+.5f}"
f" <- "
f"{CHSH1_mitigated.metadata[i]['zne']['noise_amplification']['values']}"
)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 4, seed=1).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp("ZZ")
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(circuit, observable)
simulation = job.result()
from zne.utils.serialization import EstimatorResultEncoder
print(EstimatorResultEncoder.dumps(simulation, indent=2))
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 zne import ZNEStrategy
from zne.noise_amplification import LocalFoldingAmplifier
from zne.extrapolation import PolynomialExtrapolator
## NOISE FACTORS
noise_factors = range(1,9)
## NOISE AMPLIFIER
noise_amplifier = LocalFoldingAmplifier(
gates_to_fold=2,
)
## EXTRPOLATOR
extrapolator = PolynomialExtrapolator(
degree=2,
)
## ZNE STRATEGY
zne_strategy = ZNEStrategy(
noise_factors=noise_factors,
noise_amplifier=noise_amplifier,
extrapolator=extrapolator,
)
job = estimator.run(circuit, observable, zne_strategy=zne_strategy)
result = job.result()
print(EstimatorResultEncoder.dumps(result, indent=2))
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 = simulation.values[0]
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()
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
noise_amplifier = LocalFoldingAmplifier(
gates_to_fold = 2,
sub_folding_option = "from_first",
random_seed = None,
)
noisy_circuit = noise_amplifier.amplify_circuit_noise(circuit=circuit, noise_factor=2)
display(noisy_circuit.draw("mpl", plot_barriers=False))
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
zne_strategy = ZNEStrategy(
noise_amplifier=CustomAmplifier(),
noise_factors=(1, 3),
extrapolator=CustomExtrapolator(),
)
job = estimator.run(circuit, observable, zne_strategy=zne_strategy)
result = job.result()
print(EstimatorResultEncoder.dumps(result, indent=2))
import qiskit.tools.jupyter # pylint: disable=unused-import,wrong-import-order
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
# 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.
from collections.abc import Sequence
from itertools import count, product
from unittest.mock import Mock
from numpy import array
from pytest import fixture, mark, raises, warns
from qiskit import QuantumCircuit
from qiskit.circuit.random import random_circuit
from qiskit.primitives import EstimatorResult
from zne.extrapolation import Extrapolator, LinearExtrapolator
from zne.noise_amplification import NoiseAmplifier
from zne.noise_amplification.folding_amplifier import MultiQubitAmplifier
from zne.zne_strategy import ZNEStrategy
from . import NO_ITERS_NONE, NO_NONE
################################################################################
## FIXTURES
################################################################################
@fixture(scope="function")
def amplifier_mock():
"""NoiseAmplifier mock object."""
amplifier = Mock(NoiseAmplifier)
amplifier.amplify_circuit_noise.side_effect = count()
return amplifier
@fixture(scope="function")
def extrapolator_mock():
"""Extrapolator mock object."""
def infer(target, data):
_, y, _ = zip(*data)
return 1, 0, {}
extrapolator = Mock(Extrapolator)
extrapolator.infer.side_effect = infer
return extrapolator
################################################################################
## TESTS
################################################################################
def test_definition():
assert ZNEStrategy._DEFINING_ATTRS == (
"noise_factors",
"noise_amplifier",
"extrapolator",
)
class TestInit:
"""Test ZNEStrategy initialization logic."""
def test_defaults(self):
"""Test default configuration."""
assert ZNEStrategy().noise_amplifier == MultiQubitAmplifier()
assert ZNEStrategy().noise_factors == (1,)
assert ZNEStrategy().extrapolator == LinearExtrapolator()
@mark.parametrize(
"noise_factors",
[(1,), (1, 3), (1, 3, 5)],
)
def test_custom(
self,
noise_factors,
):
"""Test custom configuration.
Proper inputs can be assumed since validation is tested separately.
"""
noise_amplifier = Mock(NoiseAmplifier)
extrapolator = Mock(Extrapolator)
zne_strategy = ZNEStrategy(
noise_factors=noise_factors,
noise_amplifier=noise_amplifier,
extrapolator=extrapolator,
)
assert zne_strategy.noise_factors == noise_factors
assert zne_strategy.noise_amplifier is noise_amplifier
assert zne_strategy.extrapolator is extrapolator
@mark.parametrize(
"noise_factors",
[(1,), (1, 3), (1, 3, 5)],
)
class TestMagic:
"""Test generic ZNEStrategy magic methods."""
def test_repr(self, noise_factors):
"""Test ZNEStrategy.__repr__() magic method."""
noise_amplifier = Mock(NoiseAmplifier)
extrapolator = Mock(Extrapolator)
zne_strategy = ZNEStrategy(
noise_factors=noise_factors,
noise_amplifier=noise_amplifier,
extrapolator=extrapolator,
)
expected = "ZNEStrategy("
expected += f"noise_factors={repr(noise_factors)}, "
expected += f"noise_amplifier={repr(noise_amplifier)}, "
expected += f"extrapolator={repr(extrapolator)})"
assert repr(zne_strategy) == expected
def test_eq(self, noise_factors):
"""Test ZNEStrategy.__eq__() magic method."""
noise_amplifier = Mock(NoiseAmplifier)
extrapolator = Mock(Extrapolator)
zne_strategy = ZNEStrategy(
noise_factors=noise_factors,
noise_amplifier=noise_amplifier,
extrapolator=extrapolator,
)
assert zne_strategy == ZNEStrategy(
noise_factors=noise_factors,
noise_amplifier=noise_amplifier,
extrapolator=extrapolator,
)
assert zne_strategy != ZNEStrategy(
noise_factors=(*noise_factors, 707),
noise_amplifier=noise_amplifier,
extrapolator=extrapolator,
)
assert zne_strategy != ZNEStrategy(
noise_factors=noise_factors,
noise_amplifier=Mock(NoiseAmplifier),
extrapolator=extrapolator,
)
assert zne_strategy != ZNEStrategy(
noise_factors=noise_factors,
noise_amplifier=noise_amplifier,
extrapolator=Mock(Extrapolator),
)
assert zne_strategy != "zne_strategy"
def test_bool(self, noise_factors):
noise_amplifier = Mock(NoiseAmplifier)
extrapolator = Mock(Extrapolator)
zne_strategy = ZNEStrategy(
noise_factors=noise_factors,
noise_amplifier=noise_amplifier,
extrapolator=extrapolator,
)
truth_value = not zne_strategy.is_noop
assert bool(zne_strategy) is truth_value
class TestConstructors:
"""Test ZNEStrategy constructors."""
def test_noop(self):
zne_strategy = ZNEStrategy.noop()
assert zne_strategy.is_noop
class TestNoiseFactors:
"""Test ZNEStrategy `noise_factors` property."""
def test_default(self):
zne_strategy = ZNEStrategy()
zne_strategy.noise_factors = None
assert zne_strategy.noise_factors == (1,)
@mark.parametrize(
"noise_factors",
cases := [(1,), (3,), (1, 3), (1, 3, 5), [1, 3, 5], [1.2, 3, 5.4]],
ids=[f"{nf}" for nf in cases],
)
def test_dispatch(self, noise_factors):
"""Test proper noise factors of different types."""
zne_strategy = ZNEStrategy()
zne_strategy.noise_factors = noise_factors
assert zne_strategy.noise_factors == tuple(noise_factors)
@mark.parametrize(
"noise_factors, expected",
cases := list(
zip(
[(1, 5, 3), (3.3, 1.2, 5.4)],
[(1, 3, 5), (1.2, 3.3, 5.4)],
)
),
ids=[f"{nf}" for nf, _ in cases],
)
def test_sort(self, noise_factors, expected):
"""Test unsorted noise factors."""
zne_strategy = ZNEStrategy()
with warns(UserWarning):
zne_strategy.noise_factors = noise_factors
assert zne_strategy.noise_factors == expected
@mark.parametrize(
"noise_factors, expected",
cases := list(
zip(
[(1, 1), (1, 3, 1, 5), (5, 5, 3), (2.4, 2.4)],
[(1,), (1, 3, 5), (3, 5), (2.4,)],
)
),
ids=[f"{nf}" for nf, _ in cases],
)
def test_duplicates(self, noise_factors, expected):
"""Test duplicate noise factors."""
zne_strategy = ZNEStrategy()
with warns(UserWarning):
zne_strategy.noise_factors = noise_factors
assert zne_strategy.noise_factors == expected
@mark.parametrize(
"noise_factors",
cases := NO_ITERS_NONE,
ids=[f"{type(c)}" for c in cases],
)
def test_sequence(self, noise_factors):
"""Test type error is raised if noise factors are not Sequence."""
zne_strategy = ZNEStrategy()
with raises(TypeError):
zne_strategy.noise_factors = noise_factors
@mark.parametrize(
"noise_factors",
cases := [(), []],
ids=[f"{type(c)}" for c in cases],
)
def test_empty(self, noise_factors):
"""Test value error is raised for empty lists of noise factors."""
zne_strategy = ZNEStrategy()
with raises(ValueError):
zne_strategy.noise_factors = noise_factors
@mark.parametrize(
"noise_factors",
cases := ["1", True, False, float("NaN"), [1, 3, "5"]],
ids=[f"{type(c)}" for c in cases],
)
def test_real(self, noise_factors):
"""Test type error is raised if noise factors are not real numbers."""
if not isinstance(noise_factors, Sequence):
noise_factors = [noise_factors]
zne_strategy = ZNEStrategy()
with raises(TypeError):
zne_strategy.noise_factors = noise_factors
@mark.parametrize(
"noise_factors",
cases := [0, 0.9999, -1, -0.5, (1, 0), (0.9, 1.2)],
ids=[f"{c}" for c in cases],
)
def test_geq_one(self, noise_factors):
"""Test value error is raised if any noise factor is less than one."""
if not isinstance(noise_factors, Sequence):
noise_factors = [noise_factors]
zne_strategy = ZNEStrategy()
with raises(ValueError):
zne_strategy.noise_factors = noise_factors
class TestNoiseAmplifier:
"""Test ZNEStrategy `noise_amplifier` property."""
def test_default(self):
zne_strategy = ZNEStrategy()
zne_strategy.noise_amplifier = None
assert zne_strategy.noise_amplifier == MultiQubitAmplifier()
@mark.parametrize(
"noise_amplifier",
cases := NO_NONE,
ids=[f"{type(c)}" for c in cases],
)
def test_type_error(self, noise_amplifier):
"""Test type error is raised if not `NoiseAmplifier`."""
zne_strategy = ZNEStrategy()
with raises(TypeError):
zne_strategy.noise_amplifier = noise_amplifier
class TestExtrapolator:
"""Test ZNEStrategy `extrapolator` property."""
def test_default(self):
zne_strategy = ZNEStrategy()
zne_strategy.extrapolator = None
assert zne_strategy.extrapolator == LinearExtrapolator()
@mark.parametrize(
"extrapolator",
cases := NO_NONE,
ids=[f"{type(c)}" for c in cases],
)
def test_type_error(self, extrapolator):
"""Test type error is raised if not `NoiseAmplifier`."""
zne_strategy = ZNEStrategy()
with raises(TypeError):
zne_strategy.extrapolator = extrapolator
class TestProperties:
"""Test generic ZNEStrategy properties."""
@mark.parametrize("noise_factors", [(1,), (1, 3), (1.2,), (2.1, 4.5)])
def test_performs_noise_amplification(self, noise_factors):
"""Test if ZNEStrategy performs noise amplification."""
zne_strategy = ZNEStrategy(noise_factors=noise_factors)
truth_value = any(nf > 1 for nf in noise_factors)
if truth_value:
assert zne_strategy.performs_noise_amplification
else:
assert not zne_strategy.performs_noise_amplification
@mark.parametrize("noise_factors", [(1,), (1, 3), (1.2,), (2.1, 4.5)])
def test_performs_zne(self, noise_factors):
"""Test if ZNEStrategy performs zero noise extrapolation."""
zne_strategy = ZNEStrategy(noise_factors=noise_factors)
truth_value = any(nf > 1 for nf in noise_factors) and len(noise_factors) > 1
if truth_value:
assert zne_strategy.performs_zne
else:
assert not zne_strategy.performs_zne
@mark.parametrize("noise_factors", [(1,), (1, 3), (1.2,), (2.1, 4.5)])
def test_is_noop(self, noise_factors):
"""Test if ZNEStrategy is no-op."""
zne_strategy = ZNEStrategy(noise_factors=noise_factors)
truth_value = tuple(noise_factors) == (1,)
if truth_value:
assert zne_strategy.is_noop
else:
assert not zne_strategy.is_noop
class TestNoiseAmplification:
"""Test ZNEStrategy noise amplification logic."""
def test_amplify_circuit_noise(self, amplifier_mock):
noise_factors = (1, 2, 3)
zne_strategy = ZNEStrategy(noise_factors=noise_factors, noise_amplifier=amplifier_mock)
circuit = QuantumCircuit(2)
assert zne_strategy.amplify_circuit_noise(circuit, 1) == 0
amplifier_mock.amplify_circuit_noise.assert_called_once_with(circuit, 1)
amplifier_mock.amplify_circuit_noise.reset_mock()
assert zne_strategy.amplify_circuit_noise(circuit, 1.2) == 1
amplifier_mock.amplify_circuit_noise.assert_called_once_with(circuit, 1.2)
circuit.h(0)
amplifier_mock.amplify_circuit_noise.reset_mock()
assert zne_strategy.amplify_circuit_noise(circuit, 2.4) == 2
amplifier_mock.amplify_circuit_noise.assert_called_once_with(circuit, 2.4)
@mark.parametrize(
"circuits, noise_factors",
cases := tuple(
product(
[
random_circuit(1, 1, seed=0),
[],
[random_circuit(2, 2, seed=5)],
[random_circuit(2, 2, seed=66), random_circuit(2, 2, seed=1081)],
],
[[1], [1, 3], [1, 3, 5]],
)
),
ids=[f"{type(c).__name__}<{len(c)}>-{nf}" for c, nf in cases],
)
def test_build_noisy_circuits(self, amplifier_mock, circuits, noise_factors):
zne_strategy = ZNEStrategy(noise_factors=noise_factors, noise_amplifier=amplifier_mock)
_ = zne_strategy.build_noisy_circuits(circuits)
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
assert amplifier_mock.amplify_circuit_noise.call_count == len(circuits) * len(noise_factors)
for circuit in circuits:
for noise_factor in noise_factors:
amplifier_mock.amplify_circuit_noise.assert_any_call(circuit, noise_factor)
@mark.parametrize(
"num_noise_factors, arg, expected",
cases := [
(1, None, None),
(1, 0, (0,)),
(1, [0], (0,)),
(1, [1], (1,)),
(1, [2], (2,)),
(1, [0, 1], (0, 1)),
(1, [0, 2], (0, 2)),
(1, [1, 2], (1, 2)),
(1, [0, 1, 2], (0, 1, 2)),
(2, None, None),
(2, 0, (0, 0)),
(2, [0], (0, 0)),
(2, [1], (1, 1)),
(2, [2], (2, 2)),
(2, [0, 1], (0, 0, 1, 1)),
(2, [0, 2], (0, 0, 2, 2)),
(2, [1, 2], (1, 1, 2, 2)),
(2, [0, 1, 2], (0, 0, 1, 1, 2, 2)),
(3, None, None),
(3, 0, (0, 0, 0)),
(3, [0], (0, 0, 0)),
(3, [1], (1, 1, 1)),
(3, [2], (2, 2, 2)),
(3, [0, 1], (0, 0, 0, 1, 1, 1)),
(3, [0, 2], (0, 0, 0, 2, 2, 2)),
(3, [1, 2], (1, 1, 1, 2, 2, 2)),
(3, [0, 1, 2], (0, 0, 0, 1, 1, 1, 2, 2, 2)),
],
ids=[f"noise<{nnf}>-{id}" for nnf, id, _ in cases],
)
def test_map_to_noisy_circuits(self, num_noise_factors, arg, expected):
zne_strategy = ZNEStrategy(noise_factors=[n for n in range(1, num_noise_factors + 1)])
assert zne_strategy.map_to_noisy_circuits(arg) == expected
class TestExtrapolation:
"""Test ZNEStrategy extrapolation logic."""
@mark.parametrize(
"noise_factors, values, variances, num_results, extrapolate_return",
[
([1, 2, 3], [1, 2, 3], [0, 0, 0], 1, [0, 1, {}]),
([1, 2, 3], [1, 2, 3], [0, 0, 0], 1, [0, 1, {"R2": 0.1}]),
([1, 2, 3], [1, 2, 3], [0, 0, 0], 2, [0, 1, {}]),
([1, 2, 3], [1, 2, 3], [0, 0, 0], 3, [0, 1, {"R2": 0.1, "P": 6.5}]),
],
)
def test_mitigate_noisy_result(
self, noise_factors, values, variances, num_results, extrapolate_return
):
val, err, meta = extrapolate_return
extrapolator = Mock(Extrapolator)
extrapolator.extrapolate_zero = Mock(return_value=tuple(extrapolate_return))
zne_strategy = ZNEStrategy(noise_factors=noise_factors)
zne_strategy.extrapolator = extrapolator
metadata = [{"variance": var, "shots": 1024} for var in variances]
noisy_result = EstimatorResult(
values=array(values * num_results), metadata=list(metadata * num_results)
)
result = zne_strategy.mitigate_noisy_result(noisy_result)
assert result.values.tolist() == [val] * num_results
metadatum = {
"noise_amplification": {
"noise_amplifier": zne_strategy.noise_amplifier,
"noise_factors": tuple(noise_factors),
"values": tuple(values),
"variance": tuple(variances),
"shots": tuple([md["shots"] for md in metadata]),
},
"extrapolation": {
"extrapolator": zne_strategy.extrapolator,
**meta,
},
}
assert result.metadata == [{"std_error": err, "zne": metadatum} for _ in range(num_results)]
@mark.parametrize(
"num_noise_factors, values, variances",
cases := [
(1, [0], [0]),
(1, [0, 1], [0, 1]),
(2, [0, 0], [0, 0]),
(2, [0, 0, 1, 1], [0, 0, 1, 1]),
(3, [0, 0, 0], [0, 0, 0]),
(3, [0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1]),
],
ids=[f"nf<{nnf}>-val<{len(val)}>" for nnf, val, _ in cases],
)
def test_generate_noisy_result_groups(self, num_noise_factors, values, variances):
zne_strategy = ZNEStrategy(noise_factors=range(1, num_noise_factors + 1))
metadata = [{"variance": var} for var in variances]
result = EstimatorResult(values=array(values), metadata=metadata)
assert (
len(tuple(zne_strategy._generate_noisy_result_groups(result)))
== len(values) / num_noise_factors
)
for i, group in enumerate(zne_strategy._generate_noisy_result_groups(result)):
lower = num_noise_factors * i
upper = num_noise_factors * (i + 1)
assert group.values.tolist() == values[lower:upper]
assert group.metadata == metadata[lower:upper]
@mark.parametrize(
"num_noise_factors, num_experiments",
cases := [(2, 1), (2, 3), (3, 2), (3, 4)],
ids=[f"nf{nnf}-val{ne}" for nnf, ne in cases],
)
def test_generate_noisy_result_groups_value_error(self, num_noise_factors, num_experiments):
zne_strategy = ZNEStrategy(noise_factors=range(1, num_noise_factors + 1))
values = array([0] * num_experiments)
metadata = [{"variance": 0.0}] * num_experiments
result = EstimatorResult(values=values, metadata=metadata)
with raises(ValueError):
generator = zne_strategy._generate_noisy_result_groups(result)
assert next(generator)
@mark.parametrize(
"noise_factors, values, std_errors",
[
([1, 2], [0, 1], [0, 0]),
([1, 2.0], [0.4, 1.2], [0, None]),
],
)
def test_regression_data_from_result_group(self, noise_factors, values, std_errors):
zne_strategy = ZNEStrategy(noise_factors=noise_factors)
metadatum = {"shots": 1024}
metadata = [
{"variance": err**2, **metadatum} if err is not None else metadatum
for err in std_errors
]
result_group = EstimatorResult(values=array(values), metadata=list(metadata))
data = zne_strategy._regression_data_from_result_group(result_group)
expected = (
noise_factors,
values,
[1 for _ in noise_factors],
[1 if err is None else err for err in std_errors],
)
for dat, exp in zip(data, expected):
assert dat == exp
@mark.parametrize(
"num_noise_factors, num_experiments",
cases := [(1, 2), (2, 1), (3, 1), (2, 3)],
ids=[f"nf<{nnf}>-experiments<{ne}>" for nnf, ne in cases],
)
def test_regression_data_from_result_group_value_error(
self, num_noise_factors, num_experiments
):
zne_strategy = ZNEStrategy(noise_factors=range(1, num_noise_factors + 1))
values = [1] * num_experiments
metadata = [{"variance": 0}] * num_experiments
result_group = EstimatorResult(values=array(values), metadata=list(metadata))
with raises(ValueError):
zne_strategy._regression_data_from_result_group(result_group)
@mark.parametrize(
"noise_factors, values, metadata, extrapolation, expected_na",
[
(
[1, 2],
[1, 1],
[{"variance": 0}, {"variance": 0}],
{},
{"noise_factors": (1, 2), "values": (1, 1), "variance": (0, 0)},
),
(
[1, 2],
[1, 0],
[{"variance": 0.1}, {"variance": 0.4}],
{"R2": 0.98},
{"noise_factors": (1, 2), "values": (1, 0), "variance": (0.1, 0.4)},
),
(
[1, 2, 3],
[0, 1.5, 2.4],
[
{"variance": 0.11, "shots": 2048},
{"variance": 0.1, "shots": 1024},
{"variance": 0.12, "shots": 4096},
],
{"R2": 0.44, "P": 6.5},
{
"noise_factors": (1, 2, 3),
"values": (0, 1.5, 2.4),
"variance": (0.11, 0.1, 0.12),
"shots": (2048, 1024, 4096),
},
),
(
[1, 2, 3],
[0, 1.5, 2.4],
[
{"variance": 0.11, "shots": 2048},
{"variance": 0.1, "shots": 1024, "backend": "ibmq-nugget"},
{"variance": 0.12, "shots": 4096, "seconds": 3600},
],
{"R2": 0.44, "P": 6.5},
{
"noise_factors": (1, 2, 3),
"values": (0, 1.5, 2.4),
"variance": (0.11, 0.1, 0.12),
"shots": (2048, 1024, 4096),
"backend": (None, "ibmq-nugget", None),
"seconds": (None, None, 3600),
},
),
],
)
def test_build_zne_metadata(self, noise_factors, values, metadata, extrapolation, expected_na):
zne_strategy = ZNEStrategy(noise_factors=noise_factors)
result_group = EstimatorResult(values=array(values), metadata=list(metadata))
computed = zne_strategy.build_zne_metadata(result_group, extrapolation)
expected_na = {
"noise_amplifier": zne_strategy.noise_amplifier,
**expected_na,
}
expected_ex = {
"extrapolator": zne_strategy.extrapolator,
**extrapolation,
}
assert computed.get("noise_amplification") == expected_na
assert computed.get("extrapolation") == expected_ex
@mark.parametrize(
"num_noise_factors, num_experiments",
cases := [(1, 2), (2, 1), (3, 1), (2, 3)],
ids=[f"nf<{nnf}>-experiments<{ne}>" for nnf, ne in cases],
)
def test_build_zne_metadata_value_error(self, num_noise_factors, num_experiments):
zne_strategy = ZNEStrategy(noise_factors=range(1, num_noise_factors + 1))
values = array([1] * num_experiments)
metadata = [{"variance": 0}] * num_experiments
result_group = EstimatorResult(values=values, metadata=metadata)
with raises(ValueError):
zne_strategy.build_zne_metadata(result_group)
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
# 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.
from test import NO_INTS, NO_REAL, TYPES
from unittest.mock import Mock, patch
from numpy.random import Generator, default_rng
from pytest import fixture, mark, raises, warns
from qiskit import QuantumCircuit
from zne.noise_amplification.folding_amplifier.global_folding_amplifier import (
GlobalFoldingAmplifier,
)
from zne.noise_amplification.folding_amplifier.local_folding_amplifier import (
LocalFoldingAmplifier,
)
MOCK_TARGET_PATH = "zne.noise_amplification.folding_amplifier.folding_amplifier.FoldingAmplifier"
@fixture(scope="module")
def patch_amplifier_with_multiple_mocks():
def factory_method(**kwargs):
return patch.multiple(MOCK_TARGET_PATH, **kwargs)
return factory_method
@mark.parametrize(
"NoiseAmplifier",
(GlobalFoldingAmplifier, LocalFoldingAmplifier),
ids=("GlobalFoldingAmplifier", "LocalFoldingAmplifier"),
)
class TestFoldingAmplifier:
@fixture(scope="function")
def setter_mocks(self):
mocks = {
"_set_sub_folding_option": Mock(),
"_set_barriers": Mock(),
"_prepare_rng": Mock(),
"_set_noise_factor_relative_tolerance": Mock(),
}
return mocks
################################################################################
## INIT TESTS
################################################################################
def test_init_default_kwargs(
self, NoiseAmplifier, patch_amplifier_with_multiple_mocks, setter_mocks
):
with patch_amplifier_with_multiple_mocks(**setter_mocks):
NoiseAmplifier()
setter_mocks["_set_sub_folding_option"].assert_called_once_with("from_first")
setter_mocks["_set_barriers"].assert_called_once_with(True)
setter_mocks["_prepare_rng"].assert_called_once_with(None)
setter_mocks["_set_noise_factor_relative_tolerance"].assert_called_once_with(1e-2)
def test_init_custom_kwargs(
self, NoiseAmplifier, patch_amplifier_with_multiple_mocks, setter_mocks
):
with patch_amplifier_with_multiple_mocks(**setter_mocks):
NoiseAmplifier(
sub_folding_option="random",
barriers=False,
random_seed=1,
noise_factor_relative_tolerance=1e-1,
)
setter_mocks["_set_sub_folding_option"].assert_called_once_with("random")
setter_mocks["_set_barriers"].assert_called_once_with(False)
setter_mocks["_prepare_rng"].assert_called_once_with(1)
setter_mocks["_set_noise_factor_relative_tolerance"].assert_called_once_with(1e-1)
################################################################################
## PROPERTIES and SETTER TESTS
################################################################################
@mark.parametrize(
"sub_folding_option",
cases := ["from_last", "from_first", "random"],
ids=[f"{c}" for c in cases],
)
def test_set_sub_folding_option(self, NoiseAmplifier, sub_folding_option):
noise_amplifier = NoiseAmplifier()
noise_amplifier._set_sub_folding_option(sub_folding_option)
assert noise_amplifier.sub_folding_option == sub_folding_option
@mark.parametrize(
"sub_folding_option", [(t,) for t in TYPES], ids=[str(type(i).__name__) for i in TYPES]
)
def test_set_sub_folding_option_value_error(self, NoiseAmplifier, sub_folding_option):
with raises(ValueError):
NoiseAmplifier()._set_sub_folding_option(sub_folding_option)
@mark.parametrize(
"random_seed",
cases := [1, 2],
ids=[f"{c}" for c in cases],
)
def test_prepare_rng(self, NoiseAmplifier, random_seed):
noise_amplifier = NoiseAmplifier()
noise_amplifier._prepare_rng(random_seed)
assert isinstance(noise_amplifier._rng, Generator)
rng = default_rng(random_seed)
assert noise_amplifier._rng.bit_generator.state == rng.bit_generator.state
@mark.parametrize(
"random_seed", [(t,) for t in NO_INTS], ids=[str(type(i).__name__) for i in NO_INTS]
)
def test_prepare_rng_type_error(self, NoiseAmplifier, random_seed):
with raises(TypeError):
NoiseAmplifier()._prepare_rng(random_seed)
@mark.parametrize(
"tolerance",
cases := [0.1, 0.01],
ids=[f"{c}" for c in cases],
)
def test_set_noise_factor_relative_tolerance(self, NoiseAmplifier, tolerance):
noise_amplifier = NoiseAmplifier()
noise_amplifier._set_noise_factor_relative_tolerance(tolerance)
assert noise_amplifier._noise_factor_relative_tolerance == tolerance
@mark.parametrize(
"tolerance", [(t,) for t in NO_REAL], ids=[str(type(i).__name__) for i in NO_REAL]
)
def test_set_noise_factor_relative_tolerance_type_error(self, NoiseAmplifier, tolerance):
with raises(TypeError):
NoiseAmplifier()._set_noise_factor_relative_tolerance(tolerance)
@mark.parametrize("warn_user", cases := [True, False], ids=[f"{c}" for c in cases])
def test_set_warn_user(self, NoiseAmplifier, warn_user):
noise_amplifier = NoiseAmplifier()
noise_amplifier.warn_user = warn_user
assert noise_amplifier.warn_user == warn_user
@mark.parametrize(
"warn_user",
cases := [t for t in TYPES if not isinstance(t, bool)],
ids=[str(type(c).__name__) for c in cases],
)
def test_set_warn_user_type_error(self, NoiseAmplifier, warn_user):
noise_amplifier = NoiseAmplifier()
with raises(TypeError):
noise_amplifier.warn_user = warn_user
@mark.parametrize(
"barriers", cases := [True, False, 1, 0, "", "|"], ids=[f"{c}" for c in cases]
)
def test_set_barriers(self, NoiseAmplifier, barriers):
noise_amplifier = NoiseAmplifier()
noise_amplifier._set_barriers(barriers)
assert noise_amplifier.barriers is bool(barriers)
################################################################################
## TESTS
################################################################################
@mark.parametrize(
"noise_factor",
cases := [1, 1.2, 2, 3.5],
ids=[f"{c}" for c in cases],
)
def test_validate_noise_factor(self, NoiseAmplifier, noise_factor):
NoiseAmplifier()._validate_noise_factor(noise_factor)
@mark.parametrize(
"noise_factor",
cases := [0, 0.5, -1, -2.5],
ids=[f"{c}" for c in cases],
)
def test_validate_noise_factor_value_error(self, NoiseAmplifier, noise_factor):
with raises(ValueError):
NoiseAmplifier()._validate_noise_factor(noise_factor)
@mark.parametrize(
"folding, expected",
cases := tuple(
zip(
[0, 1, 2],
[1, 3, 5],
)
),
ids=[f"{f}-{e}" for f, e in cases],
)
def test_folding_to_noise_factor(self, NoiseAmplifier, folding, expected):
assert NoiseAmplifier().folding_to_noise_factor(folding) == expected
def test_warn_user_true(self, NoiseAmplifier):
with warns(UserWarning):
NoiseAmplifier().warn("warning")
def test_warn_user_false(self, NoiseAmplifier):
NoiseAmplifier(warn_user=False).warn("no warning")
@mark.parametrize(
"num_instructions, noise_factor, expected",
cases := [
(9, 1.2, (0, 1)),
(9, 2, (0, 4)),
(9, 3.6, (1, 3)),
(9, 4, (1, 5)),
(9, 17 / 3.0, (2, 3)),
(9, 100, (49, 5)),
(17, 1.2, (0, 2)),
(17, 2, (0, 8)),
(17, 3.6, (1, 5)),
(17, 4, (1, 9)),
(17, 100, (49, 9)),
],
ids=[f"{ni}-{nf}-{cd}" for ni, nf, cd in cases],
)
@mark.filterwarnings("ignore::UserWarning")
def test_compute_folding_nums(self, NoiseAmplifier, num_instructions, noise_factor, expected):
assert NoiseAmplifier()._compute_folding_nums(noise_factor, num_instructions) == expected
@mark.parametrize(
"noise_factor",
cases := [1.5, 3.05],
ids=[f"{c}" for c in cases],
)
def test_compute_folding_nums_warning(self, NoiseAmplifier, noise_factor):
with warns(UserWarning):
assert NoiseAmplifier()._compute_folding_nums(noise_factor, 3)
def test_compute_folding_no_foldings(self, NoiseAmplifier):
with warns(UserWarning):
assert NoiseAmplifier()._compute_folding_nums(3, 0) == (0, 0)
@mark.parametrize("registers", [(), (0,), (1,), (0, 1)])
def test_apply_barrier_true(self, NoiseAmplifier, registers):
circuit = QuantumCircuit(2)
original = circuit.copy()
noise_amplifier = NoiseAmplifier(barriers=True)
circuit = noise_amplifier._apply_barrier(circuit, *registers)
last_instruction = circuit.data.pop()
assert last_instruction.operation.name == "barrier"
registers = [circuit.qubits[r] for r in registers] or circuit.qubits
assert last_instruction.qubits == tuple(registers)
assert circuit == original
@mark.parametrize("registers", [(), (0,), (1,), (0, 1)])
def test_apply_barrier_false(self, NoiseAmplifier, registers):
circuit = QuantumCircuit(2)
original = circuit.copy()
noise_amplifier = NoiseAmplifier(barriers=False)
circuit = noise_amplifier._apply_barrier(circuit, *registers)
assert circuit == original
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
# 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.
"""Type definitions for the Zero Noise Extrapolation (ZNE) Estimator class."""
from typing import Any, Dict, Sequence, Tuple, Union
from qiskit import QuantumCircuit
Metadata = Dict[str, Any]
EstimatorResultData = Dict[str, Union[float, Metadata]]
ParameterVector = Sequence[float] # TODO: qiskit.circuit::ParameterVector
CircuitKey = tuple
NoiseFactor = float
ZNECacheKey = Tuple[CircuitKey, NoiseFactor]
ZNECache = Dict[ZNECacheKey, QuantumCircuit]
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
# 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.
"""Zero Noise Extrapolation (ZNE) strategy configuration dataclass."""
from __future__ import annotations
from collections.abc import Iterable, Iterator, Sequence
from math import sqrt
from typing import Any
from warnings import warn
from numpy import array
from qiskit import QuantumCircuit
from qiskit.primitives import EstimatorResult
from .extrapolation import Extrapolator, LinearExtrapolator
from .noise_amplification import MultiQubitAmplifier, NoiseAmplifier
from .types import EstimatorResultData, Metadata # noqa: F401
from .utils.grouping import from_common_key, group_elements_gen, merge_dicts
from .utils.typing import isreal, normalize_array
from .utils.validation import quality
class ZNEStrategy:
"""Zero Noise Extrapolation strategy.
Args:
noise_factors: An list of real valued noise factors that determine by what amount the
circuits' noise is amplified.
noise_amplifier: A noise amplification strategy implementing the :class:`NoiseAmplifier`
interface. A dictionary of currently available options can be imported as
``NOISE_AMPLIFIER_LIBRARY``.
extrapolator: An extrapolation strategy implementing the :class:`Extrapolator`
interface. A dictionary of currently available options can be imported as
``EXTRAPOLATOR_LIBRARY``.
Raises:
TypeError: If input does not match the type specification.
ValueError: If noise factors are empty or less than one.
"""
_DEFINING_ATTRS = (
"noise_factors",
"noise_amplifier",
"extrapolator",
)
def __init__(
self,
noise_factors: Sequence[float] | None = None,
noise_amplifier: NoiseAmplifier | None = None,
extrapolator: Extrapolator | None = None,
) -> None:
self.noise_factors = noise_factors
self.noise_amplifier = noise_amplifier
self.extrapolator = extrapolator
def __repr__(self) -> str:
attrs_str = ", ".join(
f"{attr}={repr(getattr(self, attr))}" for attr in self._DEFINING_ATTRS
)
return f"ZNEStrategy({attrs_str})"
def __eq__(self, __o: object) -> bool:
if not isinstance(__o, self.__class__):
return False
return all(getattr(self, attr) == getattr(__o, attr) for attr in self._DEFINING_ATTRS)
def __bool__(self) -> bool:
return not self.is_noop
################################################################################
## CONSTRUCTORS
################################################################################
@classmethod
def noop(cls) -> ZNEStrategy:
"""Construct a no-op ZNE strategy object."""
return cls(noise_factors=(1,))
################################################################################
## PROPERTIES
################################################################################
@quality(default=(1,))
def noise_factors(self, noise_factors: Sequence[float]) -> tuple[float, ...]:
"""Noise factors for ZNE.
Validation logic defined as required by `quality`.
"""
if not isinstance(noise_factors, Sequence):
raise TypeError(
f"Expected `Sequence` noise factors, received `{type(noise_factors)}` instead."
)
noise_factors = tuple(noise_factors)
if not noise_factors:
raise ValueError("Noise factors must not be empty.")
if not all(isreal(nf) for nf in noise_factors):
raise TypeError("Noise factors must be real valued.")
if any(nf < 1 for nf in noise_factors):
raise ValueError("Noise factors must be greater than or equal to one.")
unsorted_noise_factors = noise_factors
noise_factors = tuple(sorted(noise_factors))
if noise_factors != unsorted_noise_factors:
warn("Unordered noise factors detected and rearranged.", UserWarning, stacklevel=3)
duplicate_noise_factors = noise_factors
noise_factors = tuple(sorted(set(noise_factors)))
if noise_factors != duplicate_noise_factors:
warn("Duplicate noise factors detected and erased.", UserWarning, stacklevel=3)
return noise_factors
@quality(default=MultiQubitAmplifier())
def noise_amplifier(self, noise_amplifier: NoiseAmplifier) -> NoiseAmplifier:
"""Noise amplifier strategy for ZNE.
Validation logic defined as required by `quality`.
"""
if not isinstance(noise_amplifier, NoiseAmplifier):
raise TypeError(
f"Expected `NoiseAmplifier` object, received `{type(noise_amplifier)}` instead."
)
return noise_amplifier
@quality(default=LinearExtrapolator())
def extrapolator(self, extrapolator: Extrapolator) -> Extrapolator:
"""Extrapoaltor strategy for ZNE.
Validation logic defined as required by `quality`.
"""
if not isinstance(extrapolator, Extrapolator):
raise TypeError(
f"Expected `Extrapolator` object, received `{type(extrapolator)}` instead."
)
return extrapolator
@property
def num_noise_factors(self) -> int:
"""Number of noise factors."""
return len(self.noise_factors)
@property
def performs_noise_amplification(self) -> bool:
"""Checks if noise amplification is performed."""
return any(nf > 1 for nf in self.noise_factors)
@property
def performs_zne(self) -> bool:
"""Checks if zero noise extrapolation is performed."""
return self.performs_noise_amplification and self.num_noise_factors > 1
@property
def is_noop(self) -> bool:
"""Checks if strategy is no-op."""
return not self.performs_noise_amplification and not self.performs_zne
################################################################################
## NOISE AMPLIFICATION
################################################################################
def amplify_circuit_noise(self, circuit: QuantumCircuit, noise_factor: float) -> QuantumCircuit:
"""Noise amplification from :class:`~.noise_amplification.NoiseAmplifier`.
Args:
circuit: The original quantum circuit.
noise_factor: The noise amplification factor by which to amplify the circuit noise.
Returns:
The noise amplified quantum circuit
"""
# TODO: caching
return self.noise_amplifier.amplify_circuit_noise(circuit, noise_factor)
# TODO: decouple indexing logic depending on this method
# TODO: add validation
def build_noisy_circuits(
self,
original_circuits: Iterable[QuantumCircuit] | QuantumCircuit,
) -> tuple[QuantumCircuit, ...]:
"""Construct noisy circuits for all noise factors from original circuits.
Args:
original_circuits: a :class:`~qiskit.circuit.QuantumCircuit` or a collection of
:class:`~qiskit.circuit.QuantumCircuit`.
Returns:
A tuple containing the noise amplified circuits.
"""
def generate_noisy_circuits(
original_circuits: Iterable[QuantumCircuit],
) -> Iterator[QuantumCircuit]:
for circuit in original_circuits: # type: QuantumCircuit
for noise_factor in self.noise_factors: # type: float
yield self.amplify_circuit_noise(circuit, noise_factor)
if isinstance(original_circuits, QuantumCircuit):
original_circuits = [original_circuits]
return tuple(generate_noisy_circuits(original_circuits))
# TODO: decouple indexing logic depending on this method
def map_to_noisy_circuits(self, arg: Any) -> tuple | None:
"""Map arguments for original circuits to the corresponding arguments for noisy circuits.
Args:
arg: Additional non-circuit arguments such as observables or parameter values.
Returns:
A tuple of args corresponding to the noise amplified circuits or None.
"""
if arg is None:
return arg
if not isinstance(arg, Iterable):
arg = [arg]
mapped_arg: list = []
for element in arg:
mapped_arg.extend(element for _ in range(self.num_noise_factors))
return tuple(mapped_arg)
################################################################################
## EXTRAPOLATION
################################################################################
# TODO: add validation
def mitigate_noisy_result(self, noisy_result: EstimatorResult) -> EstimatorResult:
"""Parse results from noisy circuits to error mitigated results.
Args:
noisy_result: The unmitigated results.
Returns:
The mitigated results after performing zero-noise-extrapolation.
"""
values: list[float] = []
metadata: list[Metadata] = []
for result_group in self._generate_noisy_result_groups(noisy_result):
data = self._regression_data_from_result_group(result_group)
val, err, meta = self.extrapolator.extrapolate_zero(*data)
common_metadata: Metadata = {"std_error": err} # TODO: extract other common metadata
zne_metadata: Metadata = self.build_zne_metadata(result_group, meta)
values.append(val)
metadata.append({**common_metadata, "zne": zne_metadata})
return EstimatorResult(values=array(values), metadata=list(metadata))
# TODO: decouple indexing logic depending on this method
def _generate_noisy_result_groups(
self, noisy_result: EstimatorResult
) -> Iterator[EstimatorResult]:
"""Generator function for grouping noisy results.
Iteratively constructs an estimator result for each group of experiments containing
the measurement results associated with every noise factor.
Args:
noisy_result: The estimator result with data from all the experiments performed.
Yields:
Estimator results grouping data for experiments with different noise factors,
but same circuit-observable combinations.
Raises:
ValueError: If the number of performed experiments is not an integer multiple of
the number of noise factors.
"""
if len(noisy_result.values) % self.num_noise_factors != 0:
raise ValueError("Inconsistent number of noisy experiments and noise factors.")
for group in group_elements_gen(
[
{"values": v, "metadata": m}
for v, m in zip(noisy_result.values, noisy_result.metadata)
],
group_size=self.num_noise_factors,
): # type: tuple[EstimatorResultData, ...]
values, metadata = zip(*[data.values() for data in group])
yield EstimatorResult(values=array(values), metadata=list(metadata))
def _regression_data_from_result_group(
self, result_group: EstimatorResult
) -> tuple[list[float], list[float], list[float], list[float]]:
"""Build regression data from noisy result group.
Args:
result_group: Estimator result grouping data for experiments with different
noise factors, but same circuit-observable combinations.
Returns:
Regression data
"""
if len(result_group.values) != self.num_noise_factors:
raise ValueError("Inconsistent number of noisy experiments and noise factors.")
x_data = list(self.noise_factors) # TODO: get actual noise factors achieved
y_data = result_group.values.tolist()
sigma_x = [1 for _ in x_data]
sigma_y = [sqrt(md.get("variance", 1)) for md in result_group.metadata]
return x_data, y_data, sigma_x, sigma_y # type: ignore
# TODO: add validation
def build_zne_metadata(
self, result_group: EstimatorResult, extrapolation: Metadata | None = None
) -> Metadata:
"""Build ZNE metadata from extrapolation data.
Args:
result_group: The grouped noisy results for a single mitigated result.
extrapolation: extrapolation metadata entries to include (e.g. extrapolation).
Returns:
Dictionary containing ZNE metadata.
Raises:
ValueError: If the number of experiments does not match the number of noise factors.
"""
if extrapolation is None:
extrapolation = {}
if len(result_group.values) != self.num_noise_factors:
raise ValueError("Inconsistent number of noisy experiments and noise factors.")
noise_amplification: Metadata = {
"noise_amplifier": self.noise_amplifier,
"noise_factors": self.noise_factors,
"values": normalize_array(result_group.values), # TODO: simplify when tuple
}
for key in merge_dicts(result_group.metadata):
value = from_common_key(result_group.metadata, key)
noise_amplification.update({key: value})
extrapolation = {
"extrapolator": self.extrapolator,
**extrapolation,
}
return {"noise_amplification": noise_amplification, "extrapolation": extrapolation}
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
# 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.
"""Noise amplification strategy via unitary/inverse repetition."""
from __future__ import annotations
from warnings import warn
from numpy.random import Generator, default_rng
from qiskit import QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from ...utils.typing import isreal
from ..noise_amplifier import NoiseAmplifier
class FoldingAmplifier(NoiseAmplifier):
"""Interface for folding amplifier strategies."""
def __init__( # pylint: disable=super-init-not-called, duplicate-code, too-many-arguments
self,
sub_folding_option: str = "from_first",
barriers: bool = True,
random_seed: int | None = None,
noise_factor_relative_tolerance: float = 1e-2,
warn_user: bool = True,
) -> None:
"""
Args:
sub_folding_option: Specifies which gates are used for sub folding when
``noise_factor`` is not an odd integer. Can either be "from_last", "from_first", or
"random".
barriers: If True applies barriers when folding (e.g. to avoid simplification).
random_seed: Random seed used for performing random sub-gate-folding.
noise_factor_relative_tolerance: Relative allowed tolerance interval between
``noise_factor`` input and actual noise factor that was used for the amplification.
If the discrepancy exceeds the tolerance, a warning is displayed.
warn_user: Specifies whether user warnings are displayed.
"""
self.warn_user: bool = warn_user
self._set_sub_folding_option(sub_folding_option)
self._set_barriers(barriers)
self._prepare_rng(random_seed)
self._set_noise_factor_relative_tolerance(noise_factor_relative_tolerance)
################################################################################
## PROPERTIES
################################################################################
@property
def options(self) -> dict:
"""Strategy options."""
options: dict = self._init_options
options.pop("warn_user", None)
return options
@property
def warn_user(self) -> bool:
"""Option whether warnings are displayed."""
return self._warn_user
@warn_user.setter
def warn_user(self, warn_user: bool) -> None:
if not isinstance(warn_user, bool):
raise TypeError(f"Expected boolean, received {type(warn_user)} instead.")
self._warn_user: bool = warn_user
@property
def sub_folding_option(self) -> str:
"""Option for sub-gate-folding.
Specifies which gates of the full circuit are used for sub folding when ``noise_factor`` is
is not an odd integer. Can either be "from_last", "from_first", or "random".
"""
return self._sub_folding_option
def _set_sub_folding_option(self, sub_folding_option: str) -> None:
if sub_folding_option not in ["from_last", "from_first", "random"]:
raise ValueError(
f"Sub-folding option must be a string of either 'from_last', 'from_first, or "
f"'random'. Received {sub_folding_option} instead."
)
self._sub_folding_option: str = sub_folding_option
@property
def barriers(self) -> bool:
"""Option for whether to apply barriers when folding."""
return self._barriers
def _set_barriers(self, barriers: bool) -> None:
self._barriers = bool(barriers)
def _prepare_rng(self, seed: int | None = None) -> None:
"""Sets random number generator with seed."""
if not isinstance(seed, (type(None), int)):
raise TypeError("Random seed must be an integer or None.")
self._rng: Generator = default_rng(seed)
# TODO: add property getter
def _set_noise_factor_relative_tolerance(self, tolerance: float) -> None:
"""Sets noise factor relative tolerance."""
if not isreal(tolerance):
raise TypeError("Noise factor relative tolerance must be real valued.")
self._noise_factor_relative_tolerance: float = tolerance
################################################################################
## FOLDING METHODS
################################################################################
@staticmethod
def folding_to_noise_factor(folding: float) -> float:
"""Converts number of foldings to noise factor.
Args:
folding: The number of foldings.
Returns:
The corresponding noise factor.
"""
return 2 * folding + 1
def warn(self, *args, **kwargs):
"""Throws user warning if enabled."""
if self.warn_user:
warn(*args, **kwargs)
def _validate_noise_factor(self, noise_factor):
"""Validates noise factor.
Args:
noise_factor: The noise amplification factor by which to amplify the circuit noise.
Raises:
ValueError: If the noise factor is smaller than 1.
"""
if noise_factor < 1:
raise ValueError(
f"{self.name} expects a positive float noise_factor >= 1."
f"Received {noise_factor} instead."
)
def _apply_barrier(self, circuit: QuantumCircuit, *registers) -> QuantumCircuit:
"""Apply barrier to specified registers if option is set."""
if self._barriers:
circuit.barrier(*registers)
return circuit
def _compute_folding_nums(self, noise_factor: float, num_instructions: int) -> tuple[int, int]:
"""Returns required number of full foldings and sub foldings.
Args:
noise_factor: The noise amplification factor by which to fold the circuit.
num_instructions: The number of instructions to fold.
Returns:
A tuple containing the number of full-and sub-foldings.
"""
if num_instructions == 0:
self.warn("Noise amplification is not performed since none of the gates are folded.")
return 0, 0
num_foldings = round(num_instructions * (noise_factor - 1) / 2.0)
closest_noise_factor: float = self.folding_to_noise_factor(num_foldings / num_instructions)
relative_error = abs(closest_noise_factor - noise_factor) / noise_factor
if relative_error > self._noise_factor_relative_tolerance:
warn(
"Rounding of noise factor: Foldings are performed with noise factor "
f"{closest_noise_factor:.2f} instead of specified noise factor "
f"{noise_factor:.2f} which amounts to a relative error of "
f"{relative_error * 100:.2f}%."
)
num_full_foldings, num_sub_foldings = divmod(num_foldings, num_instructions)
return num_full_foldings, num_sub_foldings
################################################################################
## IMPLEMENTATION
################################################################################
# pylint: disable=useless-parent-delegation
def amplify_dag_noise(
self, dag: DAGCircuit, noise_factor: float
) -> DAGCircuit: # pragma: no cover
return super().amplify_dag_noise(dag, noise_factor)
|
https://github.com/qonwaygameoflife/qonwaygameoflife
|
qonwaygameoflife
|
#!/usr/bin/env python3
import math
from neighbours import neighbours3
from qiskit import QuantumCircuit
from qiskit import Aer, execute
from qiskit.aqua.components.oracles import TruthTableOracle
from qiskit.circuit.reset import reset
from qiskit.extensions.standard import barrier, h, swap, x
def make_init_circuit(register, init_cells):
init_circuit = QuantumCircuit(register)
for i, v in enumerate(init_cells[::-1]):
if v == '0':
continue
if v == '1':
init_circuit.x(register[i])
else:
init_circuit.h(register[i])
return init_circuit
def make_barrier_circuit(regs):
circuit = QuantumCircuit(*regs)
for r in regs:
circuit.barrier(r)
return circuit
def make_swap_circuit(reg01, reg02):
circuit = QuantumCircuit(reg01, reg02)
circuit.swap(reg01, reg02)
return circuit
def make_reset_circuit(regs):
circuit = QuantumCircuit(*regs)
for r in regs:
circuit.reset(r)
return circuit
def make_oracle(qcount):
bitmaps = [''] * qcount
for raw_value in range(2**qcount):
value = format(raw_value, '0{}b'.format(qcount))[::-1]
for index in range(qcount):
n = neighbours3(index, value)
alive_count = 1 if n[0] == '1' else 0
alive_count += 1 if n[2] == '1' else 0
if n[1] == '0' and alive_count == 2:
bitmaps[index] += '1'
elif n[1] == '1' and alive_count == 1:
bitmaps[index] += '1'
else:
bitmaps[index] += '0'
return TruthTableOracle(bitmaps)
def vector_state_to_summary(state, extract_cells):
summary = {}
circuit_size = int(math.log(len(state), 2))
for index, value in enumerate(state):
if value == complex(0,0):
continue
f_index = format(index, '0{}b'.format(circuit_size))
cells = extract_cells(f_index)
if cells in summary:
summary[cells] += value
else:
summary[cells] = value
return summary
def print_summary(summary, min_prob):
for cells, value in summary.items():
prob = abs(value)
if prob >= min_prob:
print('{} <{}>'.format(format_cells(cells), prob))
def print_cells(cells):
print(format_cells(cells))
def format_cells(cells):
output = ''
for c in cells:
if c == '0':
output += '□'
elif c == '1':
output += '■'
else:
output += '☒'
return ' '.join(output)
init_cells = 'XXX'
print('Input:')
print_cells(init_cells)
qcount = len(init_cells)
oracle = make_oracle(qcount)
oracle_circuit = oracle.construct_circuit()
init_circuit = make_init_circuit(oracle.variable_register, init_cells)
circuit = init_circuit + oracle_circuit
backend_sim = Aer.get_backend('statevector_simulator')
result = execute(circuit, backend_sim).result()
state = result.get_statevector(circuit)
cell_range_start = oracle.ancillary_register.size
cell_range_end = cell_range_start + oracle.output_register.size
extract_cells = lambda index: index[cell_range_start:cell_range_end]
summary = vector_state_to_summary(state, extract_cells)
print('Output:')
min_prob = 0 #(1 / len(summary)) - 0.00001
print_summary(summary, min_prob)
oracle2 = make_oracle(qcount)
oracle2_circuit = oracle2.construct_circuit()
barrier_circuit = make_barrier_circuit(oracle2_circuit.qregs)
swap_circuit = make_swap_circuit(oracle.output_register,
oracle2.variable_register)
reset_circuit = make_reset_circuit([oracle2.output_register, oracle2.ancillary_register])
circuit2 = (init_circuit + oracle_circuit +
barrier_circuit + swap_circuit + reset_circuit + oracle2_circuit)
##print(circuit2)
result = execute(circuit2, backend_sim).result()
state = result.get_statevector(circuit2)
cell_range_start = oracle2.ancillary_register.size
cell_range_end = cell_range_start + oracle2.output_register.size
extract_cells = lambda index: index[cell_range_start:cell_range_end]
summary = vector_state_to_summary(state, extract_cells)
print('Output:')
min_prob = 0 #(1 / len(summary)) - 0.00001
print_summary(summary, min_prob)
|
https://github.com/qonwaygameoflife/qonwaygameoflife
|
qonwaygameoflife
|
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import Aer, execute
from qiskit.tools.qi.qi import partial_trace
def liveliness(nhood):
v=nhood
a = v[0][0][0]+v[0][1][0]+v[0][2][0]+v[1][0][0]+v[1][2][0]+v[2][0][0]+v[2][1][0]+v[2][2][0]
return a
def SQGOL(nhood):
a = liveliness(nhood)
value = nhood[1][1]
alive = np.array([1.0,0.0])
dead = np.array([0.0,1.0])
B = np.array([[0,0],[1,1]])
D = np.array([[1,1],[0,0]])
S = np.array([[1,0],[0,1]])
if a <= 1:
value = dead
elif (a > 1 and a <= 2):
value = ((np.sqrt(2)+1)*2-(np.sqrt(2)+1)*a)*dead+(a-1)*value#(((np.sqrt(2)+1)*(2-a))**2+(a-1)**2)
elif (a > 2 and a <= 3):
value = (((np.sqrt(2)+1)*3)-(np.sqrt(2)+1)*a)*value+(a-2)*alive#(((np.sqrt(2)+1)*(3-a))**2+(a-2)**2)
elif (a > 3 and a < 4):
value = ((np.sqrt(2)+1)*4-(np.sqrt(2)+1)*a)*alive+(a-3)*dead#(((np.sqrt(2)+1)*(4-a))**2+(a-3)**2)
elif a >= 4:
value = dead
value = value/np.linalg.norm(value)
return value
def init_quantum(nhood):
v=nhood
a = (v[0][0]+v[0][1]+v[0][2]+v[1][0]+v[1][2]+v[2][0]+v[2][1]+v[2][2])/8
a = a/np.linalg.norm(a)
qr = QuantumRegister(3,'qr')
qc = QuantumCircuit(qr,name='conway')
counter = 0
initial_state = (1/np.sqrt(6))*np.array([2,1,0,1])
qc.initialize(initial_state,[qr[1],qr[2]])
qc.initialize(a,[qr[0]])
qc.cx(qr[0],qr[1])
qc.initialize(a,[qr[0]])
qc.cx(qr[0],qr[1])
qc.cx(qr[0],qr[2])
qc.cx(qr[1],qr[0])
qc.cx(qr[2],qr[0])
job = execute(qc,Aer.get_backend('statevector_simulator'))
results = job.result().get_statevector()
del qr
del qc
del job
value = partial_trace(results,[1,2])[0]
value = np.real(value)
return value
def DSQGOL(nhood):
a = liveliness(nhood)
value = nhood[1][1][0]
value = nhood[1][1]
alive = [1,0]
dead = [0,1]
if value[0] > 0.98:
if (a <= 1.5 ):
value = dead
elif (a > 1.5 and a <= 2.5):
value = init_quantum(nhood)
# qci, qri = init_quantum(nhood)
# for i in range(9):
# if i !=5:
# qci.cx(qri[5],qri[i])
# job = execute(qci,Aer.get_backend('statevector_simulator'))
# results = job.result().get_statevector()
# value = partial_trace(results,[0,1,2,3,4,6,7,8])
elif (a > 2.5 and a <= 3.5):
value = alive
elif (a > 3.5):
value = dead
elif a < 0.02:
if (a < 1 ):
value = dead
elif (a > 1 and a <= 1.5):
value = dead
elif (a > 1.5 and a <= 2.5):
value = init_quantum(nhood)
# qc, qr = init_quantum(nhood)
# for i in range(9):
# if i !=5:
# qci.cx(qri[5],qri[i])
# job = execute(qc,Aer.get_backend('statevector_simulator'))
# results = job.result().get_statevector()
# value = partial_trace(results,[0,1,2,3,4,6,7,8])
elif (a > 2.5 and a <= 3.5):
value = alive
elif (a > 3.5):
value = dead
else:
if (a < 1 ):
value = dead
elif (a > 1 and a <= 1.5):
value = dead
elif (a > 1.5 and a <= 2.5):
value = init_quantum(nhood)
# qci, qri = init_quantum(nhood)
# for i in range(9):
# if i !=5:
# qci.cx(qri[5],qri[i])
# job = execute(qc,Aer.get_backend('statevector_simulator'))
# results = job.result().get_statevector()
# value = partial_trace(results,[0,1,2,3,4,6,7,8])
elif (a > 2.5 and a <= 3.5):
value = init_quantum(nhood)
# qri = QuantumRegister(1,'qr')
# qci = QuantumCircuit(qc,name='conway')
# qci.initialize(value,qri[i])
# qci.measure(qr(5))
# job = execute(qci,Aer.get_backend('statevector_simulator'))
# value = job.result().get_statevector()
elif (a > 3.5):
value=dead
return value
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
from qiskit import (
QuantumCircuit,
QuantumRegister,
ClassicalRegister,
execute
)
from qiskit_rigetti import RigettiQCSProvider
provider = RigettiQCSProvider()
backend = provider.get_simulator(num_qubits=2, noisy=True) # or provider.get_backend(name="Aspen-9") when running via QCS
circuit = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "ro"))
circuit.h(0)
circuit.cx(0, 1)
circuit.measure([0, 1], [0, 1])
circuit.draw()
job = execute(circuit, backend, shots=1000)
result = job.result()
counts = result.get_counts()
print("Counts for experiment:", counts)
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
#In case you don't have qiskit, install it now
%pip install qiskit --quiet
#Installing/upgrading pylatexenc seems to have fixed my mpl issue
#If you try this and it doesn't work, try also restarting the runtime/kernel
%pip install pylatexenc --quiet
!pip install -Uqq ipdb
!pip install qiskit_optimization
import networkx as nx
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer
from qiskit.compiler import transpile
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit.quantum_info import process_fidelity
from qiskit.extensions.hamiltonian_gate import HamiltonianGate
from qiskit.extensions import RXGate, XGate, CXGate
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute
import numpy as np
from qiskit.visualization import plot_histogram
import ipdb
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
#quadratic optimization
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.converters import QuadraticProgramToQubo
%pdb on
# def ApplyCost(qc, gamma):
# Ix = np.array([[1,0],[0,1]])
# Zx= np.array([[1,0],[0,-1]])
# Xx = np.array([[0,1],[1,0]])
# Temp = (Ix-Zx)/2
# T = Operator(Temp)
# I = Operator(Ix)
# Z = Operator(Zx)
# X = Operator(Xx)
# FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T)
# ham = HamiltonianGate(FinalOp,gamma)
# qc.append(ham,[0,1,2])
task = QuadraticProgram(name = 'QUBO on QC')
task.binary_var(name = 'x')
task.binary_var(name = 'y')
task.binary_var(name = 'z')
task.minimize(linear = {"x":-1,"y":2,"z":-3}, quadratic = {("x", "z"): -2, ("y", "z"): -1})
qubo = QuadraticProgramToQubo().convert(task) #convert to QUBO
operator, offset = qubo.to_ising()
print(operator)
# ham = HamiltonianGate(operator,0)
# print(ham)
Ix = np.array([[1,0],[0,1]])
Zx= np.array([[1,0],[0,-1]])
Xx = np.array([[0,1],[1,0]])
Temp = (Ix-Zx)/2
T = Operator(Temp)
I = Operator(Ix)
Z = Operator(Zx)
X = Operator(Xx)
FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T)
ham = HamiltonianGate(FinalOp,0)
print(ham)
#define PYBIND11_DETAILED_ERROR_MESSAGES
def compute_expectation(counts):
"""
Computes expectation value based on measurement results
Args:
counts: dict
key as bitstring, val as count
G: networkx graph
Returns:
avg: float
expectation value
"""
avg = 0
sum_count = 0
for bitstring, count in counts.items():
x = int(bitstring[2])
y = int(bitstring[1])
z = int(bitstring[0])
obj = -2*x*z-y*z-x+2*y-3*z
avg += obj * count
sum_count += count
return avg/sum_count
# We will also bring the different circuit components that
# build the qaoa circuit under a single function
def create_qaoa_circ(theta):
"""
Creates a parametrized qaoa circuit
Args:
G: networkx graph
theta: list
unitary parameters
Returns:
qc: qiskit circuit
"""
nqubits = 3
n,m=3,3
p = len(theta)//2 # number of alternating unitaries
qc = QuantumCircuit(nqubits,nqubits)
Ix = np.array([[1,0],[0,1]])
Zx= np.array([[1,0],[0,-1]])
Xx = np.array([[0,1],[1,0]])
Temp = (Ix-Zx)/2
T = Operator(Temp)
I = Operator(Ix)
Z = Operator(Zx)
X = Operator(Xx)
FinalOp=-2*(Z^I^Z)-(I^Z^Z)-(Z^I^I)+2*(I^Z^I)-3*(I^I^Z)
beta = theta[:p]
gamma = theta[p:]
# initial_state
for i in range(0, nqubits):
qc.h(i)
for irep in range(0, p):
#ipdb.set_trace(context=6)
# problem unitary
# for pair in list(G.edges()):
# qc.rzz(2 * gamma[irep], pair[0], pair[1])
#ApplyCost(qc,2*0)
ham = HamiltonianGate(operator,2 * gamma[irep])
qc.append(ham,[0,1,2])
# mixer unitary
for i in range(0, nqubits):
qc.rx(2 * beta[irep], i)
qc.measure(qc.qubits[:n],qc.clbits[:m])
return qc
# Finally we write a function that executes the circuit on the chosen backend
def get_expectation(shots=512):
"""
Runs parametrized circuit
Args:
G: networkx graph
p: int,
Number of repetitions of unitaries
"""
backend = Aer.get_backend('qasm_simulator')
backend.shots = shots
def execute_circ(theta):
qc = create_qaoa_circ(theta)
# ipdb.set_trace(context=6)
counts = {}
job = execute(qc, backend, shots=1024)
result = job.result()
counts=result.get_counts(qc)
return compute_expectation(counts)
return execute_circ
from scipy.optimize import minimize
expectation = get_expectation()
res = minimize(expectation, [1, 1], method='COBYLA')
expectation = get_expectation()
res = minimize(expectation, res.x, method='COBYLA')
res
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('aer_simulator')
backend.shots = 512
qc_res = create_qaoa_circ(res.x)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc_res, backend, shots=1024)
result = job.result()
counts=result.get_counts(qc_res)
plot_histogram(counts)
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
##############################################################################
# Copyright 2021 Rigetti Computing
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
from typing import Iterable, Optional, Any, Union, List, cast, Tuple
from uuid import uuid4
from pyquil import get_qc
from pyquil.api import QuantumComputer, QCSClient
from qiskit import QuantumCircuit, ClassicalRegister
from qiskit.circuit import Measure, CircuitInstruction, Clbit
from qiskit.providers import BackendV1, Options, Provider
from qiskit.providers.models import QasmBackendConfiguration
from qiskit.transpiler import CouplingMap
from ._qcs_job import RigettiQCSJob
def _prepare_readouts(circuit: QuantumCircuit) -> None:
"""
Errors if measuring into more than one readout. If only measuring one, ensures its name is 'ro'. Mutates the input
circuit.
"""
measures: List[CircuitInstruction] = [d for d in circuit.data if isinstance(d[0], Measure)]
readout_names: List[str] = list({clbit.register.name for m in measures for clbit in m.clbits})
num_readouts = len(readout_names)
if num_readouts == 0:
raise RuntimeError("Circuit has no measurements")
if num_readouts > 1:
readout_names.sort()
raise RuntimeError(
f"Multiple readout registers are unsupported on QCSBackend; found {', '.join(readout_names)}"
)
orig_readout_name = readout_names[0]
if orig_readout_name == "ro":
return
for i, reg in enumerate(circuit.cregs):
if reg.name != orig_readout_name:
continue
# rename register to "ro"
ro_reg = ClassicalRegister(size=reg.size, name="ro")
circuit.cregs[i] = ro_reg
def map_ro_reg(clbits: Iterable[Clbit]) -> List[Clbit]:
return [Clbit(ro_reg, clbit.index) for clbit in clbits if clbit.register.name == orig_readout_name]
circuit._clbits = map_ro_reg(circuit.clbits)
circuit._clbit_indices = {
Clbit(ro_reg, clbit.index): loc._replace(registers=[ro_reg])
for clbit, loc in circuit._clbit_indices.items()
if clbit.register.name == orig_readout_name
}
for instruction in circuit._data:
instruction.clbits = map_ro_reg(instruction.clbits)
break
def _prepare_circuit(circuit: QuantumCircuit) -> QuantumCircuit:
"""
Returns a prepared copy of the circuit for execution on the QCS Backend.
"""
circuit = circuit.copy()
_prepare_readouts(circuit)
return circuit
class GetQuantumProcessorException(Exception):
pass
class RigettiQCSBackend(BackendV1):
"""
Class for representing a Rigetti backend, which may target a real QPU or a simulator.
"""
def __init__(
self,
*,
compiler_timeout: float,
execution_timeout: float,
client_configuration: QCSClient,
backend_configuration: QasmBackendConfiguration,
provider: Optional[Provider],
auto_set_coupling_map: bool = True,
qc: Optional[QuantumComputer] = None,
**fields: Any,
) -> None:
"""
Args:
execution_timeout: Time limit for execution requests, in seconds.
compiler_timeout: Time limit for compiler requests, in seconds.
client_configuration: QCS client configuration.
backend_configuration: Backend configuration.
provider: Parent provider.
qc: The `QuantumComputer` this backend represents to Qiskit.
auto_set_coupling_map: When `True`, this will set the `QasmBackendConfiguration`
`coupling_map` based on the `QuantumComputer` topology if the existing
`coupling_map` is empty.
fields: Keyword arguments for the values to use to override the default options.
"""
super().__init__(backend_configuration, provider, **fields)
self._compiler_timeout = compiler_timeout
self._execution_timeout = execution_timeout
self._client_configuration = client_configuration
self._qc = qc
self._auto_set_coupling_map = auto_set_coupling_map
@classmethod
def _default_options(cls) -> Options:
return Options(shots=None)
@property
def qc(self) -> QuantumComputer:
self._load_qc_if_necessary()
return cast(QuantumComputer, self._qc)
@property
def coupling_map(self) -> CouplingMap:
self._set_coupling_map_based_on_qc_topology_if_necessary()
return CouplingMap(self.configuration().coupling_map)
def _load_qc_if_necessary(self) -> None:
configuration: QasmBackendConfiguration = self.configuration()
if self._qc is None:
try:
self._qc = get_qc(
configuration.backend_name,
compiler_timeout=self._compiler_timeout,
execution_timeout=self._execution_timeout,
client_configuration=self._client_configuration,
)
except Exception as e:
raise GetQuantumProcessorException(
f"failed to retrieve quantum processor {configuration.backend_name}"
) from e
def _set_coupling_map_based_on_qc_topology_if_necessary(self) -> None:
configuration: QasmBackendConfiguration = self.configuration()
if not configuration.coupling_map and self._auto_set_coupling_map:
configuration.coupling_map = get_coupling_map_from_qc_topology(self.qc)
def run(
self,
run_input: Union[QuantumCircuit, List[QuantumCircuit]],
**options: Any,
) -> RigettiQCSJob:
"""
Run the quantum circuit(s) using this backend.
Args:
run_input: Either a single :class:`QuantumCircuit` to run or a list of them to run in parallel.
**options: Execution options to forward to :class:`RigettiQCSJob`.
Returns:
RigettiQCSJob: The job that has been started. Wait for it by calling :func:`RigettiQCSJob.result`
"""
if not isinstance(run_input, list):
run_input = [run_input]
bindings = options.get("parameter_binds") or []
if len(bindings) > 0:
run_input = [circuit.bind_parameters(binding) for circuit in run_input for binding in bindings]
run_input = [_prepare_circuit(circuit) for circuit in run_input]
self._set_coupling_map_based_on_qc_topology_if_necessary()
return RigettiQCSJob(
job_id=str(uuid4()),
circuits=run_input,
options=options,
qc=self.qc,
backend=self,
configuration=self.configuration(),
)
def get_coupling_map_from_qc_topology(qc: QuantumComputer) -> List[Tuple[int, int]]:
return cast(List[Tuple[int, int]], qc.quantum_processor.qubit_topology().to_directed().edges())
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
##############################################################################
# Copyright 2021 Rigetti Computing
#
# 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 warnings
from collections import Counter
from datetime import datetime
from typing import Optional, Dict, Any, List, Union, Iterator, cast
import numpy as np
from dateutil.tz import tzutc
from pyquil.api import QuantumComputer
from pyquil.api._qpu import QPUExecuteResponse
from pyquil.api._qvm import QVMExecuteResponse
from qiskit import QuantumCircuit
from qiskit.providers import JobStatus, JobV1, Backend
from qiskit.providers.models import QasmBackendConfiguration
from qiskit.qobj import QobjExperimentHeader
from qiskit.result import Result
from qiskit.result.models import ExperimentResult, ExperimentResultData
from .hooks.pre_compilation import PreCompilationHook
from .hooks.pre_execution import PreExecutionHook
Response = Union[QVMExecuteResponse, QPUExecuteResponse]
class RigettiQCSJob(JobV1):
"""
Class for representing execution jobs sent to Rigetti backends.
"""
def __init__(
self,
*,
job_id: str,
circuits: List[QuantumCircuit],
options: Dict[str, Any],
qc: QuantumComputer,
backend: Backend,
configuration: QasmBackendConfiguration,
) -> None:
"""
Args:
job_id: Unique identifier for this job
circuits: List of circuits to execute
options: Execution options (e.g. "shots")
qc: Quantum computer to run against
backend: :class:`RigettiQCSBackend` that created this job
configuration: Configuration from parent backend
"""
super().__init__(backend, job_id)
self._status = JobStatus.INITIALIZING
self._circuits = circuits
self._options = options
self._qc = qc
self._configuration = configuration
self._result: Optional[Result] = None
self._responses: List[Response] = []
self._start()
def submit(self) -> None:
"""
Raises:
NotImplementedError: This class uses the asynchronous pattern, so this method should not be called.
"""
raise NotImplementedError("'submit' is not implemented as this class uses the asynchronous pattern")
def _start(self) -> None:
self._responses = [self._start_circuit(circuit) for circuit in self._circuits]
self._status = JobStatus.RUNNING
def _start_circuit(self, circuit: QuantumCircuit) -> Response:
shots = self._options["shots"]
qasm = circuit.qasm()
qasm = self._handle_barriers(qasm, circuit.num_qubits)
before_compile: List[PreCompilationHook] = self._options.get("before_compile", [])
for fn in before_compile:
qasm = fn(qasm)
program = self._qc.compiler.transpile_qasm_2(qasm)
program = program.wrap_in_numshots_loop(shots)
before_execute: List[PreExecutionHook] = self._options.get("before_execute", [])
for fn in before_execute:
program = fn(program)
if self._options.get("ensure_native_quil") and len(before_execute) > 0:
program = self._qc.compiler.quil_to_native_quil(program)
executable = self._qc.compiler.native_quil_to_executable(program)
# typing: QuantumComputer's inner QAM is generic, so we set the expected type here
return cast(Response, self._qc.qam.execute(executable))
@staticmethod
def _handle_barriers(qasm: str, num_circuit_qubits: int) -> str:
lines = []
for line in qasm.splitlines():
if line.startswith("barrier"):
warnings.warn("barriers are currently omitted during execution on a RigettiQCSBackend")
continue
lines.append(line)
return "\n".join(lines)
def result(self) -> Result:
"""
Wait until the job is complete, then return a result.
Raises:
JobError: If there was a problem running the Job or retrieving the result
"""
if self._result is not None:
return self._result
now = datetime.now(tzutc())
results = []
success = True
for r in self._get_experiment_results():
results.append(r)
success &= r.success
self._result = Result(
backend_name=self._configuration.backend_name,
backend_version=self._configuration.backend_version,
qobj_id="",
job_id=self.job_id(),
success=success,
results=results,
date=now,
execution_duration_microseconds=[r.execution_duration_microseconds for r in results],
)
self._status = JobStatus.DONE if success else JobStatus.ERROR
return self._result
def _get_experiment_results(self) -> Iterator[ExperimentResult]:
shots = self._options["shots"]
for circuit_idx, response in enumerate(self._responses):
execution_result = self._qc.qam.get_result(response)
states = execution_result.readout_data["ro"]
memory = list(map(_to_binary_str, np.array(states)))
success = True
status = "Completed successfully"
circuit = self._circuits[circuit_idx]
yield ExperimentResult(
header=QobjExperimentHeader(name=circuit.name),
shots=shots,
success=success,
status=status,
data=ExperimentResultData(counts=Counter(memory), memory=memory),
execution_duration_microseconds=execution_result.execution_duration_microseconds,
)
def cancel(self) -> None:
"""
Raises:
NotImplementedError: There is currently no way to cancel this job.
"""
raise NotImplementedError("Cancelling jobs is not supported")
def status(self) -> JobStatus:
"""Get the current status of this Job
If this job was RUNNING when you called it, this function will block until the job is complete.
"""
if self._status == JobStatus.RUNNING:
# Wait for results _now_ to finish running, otherwise consuming code might wait forever.
self.result()
return self._status
def _to_binary_str(state: List[int]) -> str:
# NOTE: According to https://arxiv.org/pdf/1809.03452.pdf, this should be a hex string
# but it results in missing leading zeros in the displayed output, and binary strings
# seem to work too. Hex string could be accomplished with:
# hex(int(binary_str, 2))
binary_str = "".join(map(str, state[::-1]))
return binary_str
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
##############################################################################
# Copyright 2021 Rigetti Computing
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
from typing import Any
from qiskit import QuantumCircuit
from qiskit.circuit import InstructionSet
from .gates import (
CanonicalGate,
CPhase00Gate,
CPhase01Gate,
CPhase10Gate,
PSwapGate,
XYGate,
)
class QuilCircuit(QuantumCircuit):
"""
A :class:`qiskit.circuit.QuantumCircuit` extension with added support for standard Quil gates:
https://github.com/rigetti/quilc/blob/master/src/quil/stdgates.quil
"""
def xy(self, theta: float, qubit1: Any, qubit2: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.xy.XYGate`."""
return self.append(XYGate(theta), [qubit1, qubit2], [])
def piswap(self, theta: float, qubit1: Any, qubit2: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.xy.XYGate`."""
return self.xy(theta, qubit1, qubit2)
def pswap(self, theta: float, qubit1: Any, qubit2: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.pswap.PSwapGate`."""
return self.append(PSwapGate(theta), [qubit1, qubit2], [])
def cphase00(self, theta: float, control_qubit: Any, target_qubit: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.cphase.CPhase00`."""
return self.append(CPhase00Gate(theta), [control_qubit, target_qubit], [])
def cphase01(self, theta: float, control_qubit: Any, target_qubit: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.cphase.CPhase01`."""
return self.append(CPhase01Gate(theta), [control_qubit, target_qubit], [])
def cphase10(self, theta: float, control_qubit: Any, target_qubit: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.cphase.CPhase10`."""
return self.append(CPhase10Gate(theta), [control_qubit, target_qubit], [])
def can(self, alpha: float, beta: float, gamma: float, qubit1: Any, qubit2: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.can.CanonicalGate`."""
return self.append(CanonicalGate(alpha, beta, gamma), [qubit1, qubit2], [])
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
from typing import Callable
PreCompilationHook = Callable[[str], str]
"""Represents a function that can transform a QASM program string just before compilation."""
def set_rewiring(rewiring: str) -> PreCompilationHook:
"""
Create a hook which will apply rewiring before compilation.
See: https://pyquil-docs.rigetti.com/en/stable/compiler.html#initial-rewiring for more information.
Args:
rewiring: Rewiring directive to apply.
Returns:
PreCompilationHook: A hook to apply rewiring.
Examples:
Applying rewiring to a program::
>>> from qiskit import execute
>>> from qiskit_rigetti import RigettiQCSProvider, QuilCircuit
>>> from qiskit_rigetti.hooks.pre_compilation import set_rewiring
>>> p = RigettiQCSProvider()
>>> backend = p.get_simulator(num_qubits=2, noisy=True)
>>> circuit = QuilCircuit(2, 2)
>>> _ = circuit.measure([0, 1], [0, 1])
>>> job = execute(circuit, backend, shots=10, before_compile=[set_rewiring("NAIVE")])
"""
def fn(qasm: str) -> str:
return qasm.replace("OPENQASM 2.0;", f'OPENQASM 2.0;\n#pragma INITIAL_REWIRING "{rewiring}";')
return fn
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
##############################################################################
# Copyright 2021 Rigetti Computing
#
# 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 pytest
from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.providers import JobStatus
from qiskit.circuit import Parameter, Qubit
from qiskit.circuit.library import CZGate
from qiskit_rigetti import RigettiQCSProvider, RigettiQCSBackend, QuilCircuit
from qiskit_rigetti.gates import XYGate
def test_run(backend: RigettiQCSBackend):
circuit = make_circuit()
job = execute(circuit, backend, shots=10)
assert job.backend() is backend
result = job.result()
assert job.status() == JobStatus.DONE
assert result.backend_name == backend.configuration().backend_name
assert result.results[0].header.name == circuit.name
assert result.results[0].shots == 10
assert result.get_counts().keys() == {"00"}
def test_run__multiple_circuits(backend: RigettiQCSBackend):
circuit1 = make_circuit(num_qubits=2)
circuit2 = make_circuit(num_qubits=3)
job = execute([circuit1, circuit2], backend, shots=10)
assert job.backend() is backend
result = job.result()
assert job.status() == JobStatus.DONE
assert result.backend_name == backend.configuration().backend_name
assert len(result.results) == 2
assert result.results[0].header.name == circuit1.name
assert result.results[0].shots == 10
assert result.get_counts(0).keys() == {"00"}
assert result.results[1].header.name == circuit2.name
assert result.results[1].shots == 10
assert result.get_counts(1).keys() == {"000"}
def test_run__parametric_circuits(backend: RigettiQCSBackend):
t = Parameter("t")
circuit1 = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "ro"))
circuit1.rx(t, 0)
circuit1.measure([0], [0])
circuit2 = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "ro"))
circuit2.ry(t, 0)
circuit2.measure([0], [0])
job = execute(
[circuit1, circuit2],
backend,
shots=1000,
parameter_binds=[
{t: 1.0},
{t: 2.0},
],
)
assert job.backend() is backend
result = job.result()
assert job.status() == JobStatus.DONE
assert result.backend_name == backend.configuration().backend_name
assert len(result.results) == 4
assert result.results[0].shots == 1000
assert result.get_counts(0).keys() == {"0", "1"}
assert result.results[1].shots == 1000
assert result.get_counts(1).keys() == {"0", "1"}
assert result.results[2].shots == 1000
assert result.get_counts(2).keys() == {"0", "1"}
assert result.results[3].shots == 1000
assert result.get_counts(3).keys() == {"0", "1"}
def test_run__readout_register_not_named_ro(backend: RigettiQCSBackend):
circuit = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "not_ro"))
circuit.measure([0, 1], [0, 1])
qasm_before = circuit.qasm()
job = execute(circuit, backend, shots=10)
assert circuit.qasm() == qasm_before, "should not modify original circuit"
assert job.backend() is backend
result = job.result()
assert job.status() == JobStatus.DONE
assert result.backend_name == backend.configuration().backend_name
assert result.results[0].header.name == circuit.name
assert result.results[0].shots == 10
assert result.get_counts().keys() == {"00"}
def test_run__multiple_registers__single_readout(backend: RigettiQCSBackend):
readout_reg = ClassicalRegister(2, "not_ro")
circuit = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"), readout_reg)
circuit.measure([0, 1], [readout_reg[0], readout_reg[1]])
qasm_before = circuit.qasm()
job = execute(circuit, backend, shots=10)
assert circuit.qasm() == qasm_before, "should not modify original circuit"
assert job.backend() is backend
result = job.result()
assert job.status() == JobStatus.DONE
assert result.backend_name == backend.configuration().backend_name
assert result.results[0].header.name == circuit.name
assert result.results[0].shots == 10
assert result.get_counts().keys() == {"00"}
def test_run__multiple_readout_registers(backend: RigettiQCSBackend):
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
cr2 = ClassicalRegister(1, "c2")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.measure([qr[0], qr[1]], [cr[0], cr2[0]])
with pytest.raises(RuntimeError, match="Multiple readout registers are unsupported on QCSBackend; found c, c2"):
execute(circuit, backend, shots=10)
def test_run__no_measurments(backend: RigettiQCSBackend):
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
with pytest.raises(RuntimeError, match="Circuit has no measurements"):
execute(circuit, backend, shots=10)
def test_run__backend_coupling_map():
backend = RigettiQCSProvider().get_simulator(num_qubits=3)
assert backend.configuration().coupling_map
assert [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] == sorted(backend.configuration().coupling_map)
assert [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] == sorted(backend.coupling_map.get_edges())
def test_decomposition(backend: RigettiQCSBackend):
"""Test that CZGate remains after the transpile."""
circuit = QuilCircuit(2, 2)
circuit.cz(0, 1)
circuit.measure_all()
circuit = transpile(circuit, backend=backend)
job = execute(circuit, backend, shots=1)
job.result() # Just make sure nothing throws an exception so the circuit is valid
assert job.status() == JobStatus.DONE
assert len(circuit.data) == 4 # CZ, BARRIER, MEASURE, MEASURE
assert circuit.data[0][0] == CZGate()
@pytest.fixture
def backend():
return RigettiQCSProvider().get_simulator(num_qubits=3)
def make_circuit(*, num_qubits: int = 2):
circuit = QuantumCircuit(QuantumRegister(num_qubits, "q"), ClassicalRegister(num_qubits, "ro"))
circuit.measure(list(range(num_qubits)), list(range(num_qubits)))
return circuit
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
##############################################################################
# Copyright 2021 Rigetti Computing
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
from typing import Optional, Any
import pytest
from pyquil import get_qc, Program
from pyquil.api import QuantumComputer
from pytest_mock import MockerFixture
from qiskit import QuantumRegister, ClassicalRegister
from qiskit.providers import JobStatus
from qiskit_rigetti import RigettiQCSJob, RigettiQCSProvider, RigettiQCSBackend, QuilCircuit
from qiskit_rigetti.hooks.pre_execution import enable_active_reset
def test_init__start_circuit_unsuccessful(backend: RigettiQCSBackend):
circuit = make_circuit(num_qubits=backend.configuration().num_qubits + 1) # Use too many qubits
with pytest.raises(Exception):
make_job(backend, circuit)
def test_init__before_compile_hook(backend: RigettiQCSBackend, mocker: MockerFixture):
circuit = make_circuit(num_qubits=2)
qc = get_qc(backend.configuration().backend_name)
transpile_qasm_2_spy = mocker.spy(qc.compiler, "transpile_qasm_2")
orig_qasm = "\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"qreg q[2];",
"creg ro[2];",
"h q[0];",
"measure q[0] -> ro[0];",
"measure q[1] -> ro[1];",
]
)
new_qasm = "\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"qreg q[2];",
"creg ro[2];",
"measure q[0] -> ro[0];",
"measure q[1] -> ro[1];",
]
)
def before_compile_hook(qasm: str) -> str:
assert qasm.rstrip() == orig_qasm
return new_qasm
make_job(backend, circuit, qc, before_compile=[before_compile_hook])
assert transpile_qasm_2_spy.call_args[0][0] == new_qasm
def test_init__before_execute_hook(backend: RigettiQCSBackend, mocker: MockerFixture):
circuit = make_circuit(num_qubits=2)
qc = get_qc(backend.configuration().backend_name)
native_quil_to_executable_spy = mocker.spy(qc.compiler, "native_quil_to_executable")
orig_quil = Program(
"DECLARE ro BIT[2]",
"RZ(pi) 0",
"RX(pi/2) 0",
"RZ(pi/2) 0",
"RX(-pi/2) 0",
"MEASURE 0 ro[0]",
"MEASURE 1 ro[1]",
)
new_quil = Program(
"DECLARE x BIT[1]",
)
def before_execute_hook(quil: Program) -> Program:
assert str(quil) == str(orig_quil)
return new_quil
make_job(backend, circuit, qc, before_execute=[before_execute_hook])
program: Program = native_quil_to_executable_spy.call_args[0][0]
assert str(program) == str(new_quil)
def test_init__ensure_native_quil__true(backend: RigettiQCSBackend, mocker: MockerFixture):
circuit = make_circuit(num_qubits=2)
qc = get_qc(backend.configuration().backend_name)
quil_to_native_quil_spy = mocker.spy(qc.compiler, "quil_to_native_quil")
transpile_qasm_2_spy = mocker.spy(qc.compiler, "transpile_qasm_2")
make_job(backend, circuit, qc, before_execute=[enable_active_reset], ensure_native_quil=True)
assert quil_to_native_quil_spy.call_count == 1, "compile not performed correct number of times"
assert transpile_qasm_2_spy.call_count == 1, "transpile not performed correct number of times"
def test_init__ensure_native_quil__ignored_if_no_pre_execution_hooks(backend: RigettiQCSBackend, mocker: MockerFixture):
circuit = make_circuit(num_qubits=2)
qc = get_qc(backend.configuration().backend_name)
quil_to_native_quil_spy = mocker.spy(qc.compiler, "quil_to_native_quil")
transpile_qasm_2_spy = mocker.spy(qc.compiler, "transpile_qasm_2")
make_job(backend, circuit, qc, ensure_native_quil=True)
assert quil_to_native_quil_spy.call_count == 0, "compile not performed correct number of times"
assert transpile_qasm_2_spy.call_count == 1, "transpile not performed correct number of times"
def test_init__ensure_native_quil__false(backend: RigettiQCSBackend, mocker: MockerFixture):
circuit = make_circuit(num_qubits=2)
qc = get_qc(backend.configuration().backend_name)
quil_to_native_quil_spy = mocker.spy(qc.compiler, "quil_to_native_quil")
transpile_qasm_2_spy = mocker.spy(qc.compiler, "transpile_qasm_2")
make_job(backend, circuit, qc, ensure_native_quil=False)
assert quil_to_native_quil_spy.call_count == 0, "compile not performed correct number of times"
assert transpile_qasm_2_spy.call_count == 1, "transpile not performed correct number of times"
def test_init__ensure_native_quil__missing(backend: RigettiQCSBackend, mocker: MockerFixture):
circuit = make_circuit(num_qubits=2)
qc = get_qc(backend.configuration().backend_name)
quil_to_native_quil_spy = mocker.spy(qc.compiler, "quil_to_native_quil")
transpile_qasm_2_spy = mocker.spy(qc.compiler, "transpile_qasm_2")
make_job(backend, circuit, qc)
assert quil_to_native_quil_spy.call_count == 0, "compile not performed correct number of times"
assert transpile_qasm_2_spy.call_count == 1, "transpile not performed correct number of times"
def test_init__circuit_with_barrier(backend: RigettiQCSBackend, mocker: MockerFixture):
circuit = QuilCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "ro"))
circuit.h(0)
circuit.barrier()
circuit.h(0)
circuit.measure([0, 1], [0, 1])
qc = get_qc(backend.configuration().backend_name)
transpile_qasm_2_spy = mocker.spy(qc.compiler, "transpile_qasm_2")
expected_qasm = "\n".join(
[
"OPENQASM 2.0;",
'include "qelib1.inc";',
"qreg q[2];",
"creg ro[2];",
"h q[0];",
"h q[0];",
"measure q[0] -> ro[0];",
"measure q[1] -> ro[1];",
]
)
with pytest.warns(UserWarning, match="barriers are currently omitted during execution on a RigettiQCSBackend"):
make_job(backend, circuit, qc)
assert transpile_qasm_2_spy.call_args[0][0] == expected_qasm
def test_result(job: RigettiQCSJob):
assert job._status == JobStatus.RUNNING
assert job.status() == JobStatus.DONE, "Checking status did not wait for completion"
assert job._status == JobStatus.DONE
result = job.result()
assert result.date == job.result().date, "Result not cached"
assert result.backend_name == "3q-qvm"
assert result.job_id == job.job_id()
assert result.success is True
result_0 = result.results[0]
assert result_0.success is True
assert result_0.status == "Completed successfully"
assert result_0.shots == 1000
assert len(result_0.data.memory) == 1000
assert result_0.execution_duration_microseconds == None
# Note: this can flake if number of shots is not large enough -- 1000 should be enough
assert result_0.data.counts.keys() == {"00", "01"}
def test_cancel(job: RigettiQCSJob):
with pytest.raises(NotImplementedError, match="Cancelling jobs is not supported"):
job.cancel()
def test_submit(job: RigettiQCSJob):
with pytest.raises(
NotImplementedError,
match="'submit' is not implemented as this class uses the asynchronous pattern",
):
job.submit()
@pytest.fixture
def backend():
return RigettiQCSProvider().get_simulator(num_qubits=3)
@pytest.fixture
def job(backend):
circuit = make_circuit(num_qubits=2)
return make_job(backend, circuit)
def make_circuit(*, num_qubits) -> QuilCircuit:
circuit = QuilCircuit(QuantumRegister(num_qubits, "q"), ClassicalRegister(num_qubits, "ro"))
circuit.h(0)
circuit.measure(range(num_qubits), range(num_qubits))
return circuit
def make_job(
backend,
circuit,
qc: Optional[QuantumComputer] = None,
**options: Any,
):
qc = qc or get_qc(backend.configuration().backend_name)
job = RigettiQCSJob(
job_id="some_job",
circuits=[circuit],
options={**{"shots": 1000}, **options},
qc=qc,
backend=backend,
configuration=backend.configuration(),
)
return job
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
##############################################################################
# Copyright 2021 Rigetti Computing
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
from qiskit import QuantumRegister
from qiskit.circuit import Qubit
from qiskit_rigetti.gates import (
CanonicalGate,
CPhase00Gate,
CPhase01Gate,
CPhase10Gate,
PSwapGate,
XYGate,
)
from qiskit_rigetti import QuilCircuit
def test_xy():
circuit = QuilCircuit(2, 2)
circuit.xy(3.14, 0, 1)
assert len(circuit.data) == 1
assert circuit.data[0] == (
XYGate(3.14),
[Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)],
[],
)
def test_piswap():
circuit = QuilCircuit(2, 2)
circuit.piswap(3.14, 0, 1)
assert len(circuit.data) == 1
assert circuit.data[0] == (
XYGate(3.14),
[Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)],
[],
)
def test_pswap():
circuit = QuilCircuit(2, 2)
circuit.pswap(3.14, 0, 1)
assert len(circuit.data) == 1
assert circuit.data[0] == (
PSwapGate(3.14),
[Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)],
[],
)
def test_cphase00():
circuit = QuilCircuit(2, 2)
circuit.cphase00(3.14, 0, 1)
assert len(circuit.data) == 1
assert circuit.data[0] == (
CPhase00Gate(3.14),
[Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)],
[],
)
def test_cphase01():
circuit = QuilCircuit(2, 2)
circuit.cphase01(3.14, 0, 1)
assert len(circuit.data) == 1
assert circuit.data[0] == (
CPhase01Gate(3.14),
[Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)],
[],
)
def test_cphase10():
circuit = QuilCircuit(2, 2)
circuit.cphase10(3.14, 0, 1)
assert len(circuit.data) == 1
assert circuit.data[0] == (
CPhase10Gate(3.14),
[Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)],
[],
)
def test_can():
circuit = QuilCircuit(2, 2)
circuit.can(3.14, 42.0, 1.62, 0, 1)
assert len(circuit.data) == 1
assert circuit.data[0] == (
CanonicalGate(3.14, 42.0, 1.62),
[Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)],
[],
)
|
https://github.com/QPower-Research/QPowerAlgo
|
QPower-Research
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import QuantumCircuit, transpile
from qiskit.primitives import Sampler, Estimator
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw('mpl')
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw('mpl')
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw('mpl')
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw('mpl')
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw('mpl')
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
dj_circuit.draw('mpl')
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw('mpl')
# use local simulator
sampler = Sampler()
result = sampler.run(dj_circuit).result()
answer = result.quasi_dists[0]
plot_histogram(answer)
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# 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
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw('mpl')
result = sampler.run(dj_circuit).result()
answer = result.quasi_dists[0]
plot_histogram(answer)
# from qiskit_ibm_runtime import QiskitRuntimeService
# # Save an IBM Quantum account and set it as your default account.
# QiskitRuntimeService.save_account(channel="ibm_quantum", token="<Enter Your Token Here>", overwrite=True)
# # Load saved credentials
# service = QiskitRuntimeService()
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
service.backends()
service = QiskitRuntimeService()
backend = service.least_busy(operational=True,min_num_qubits=5)
print(backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
pm = generate_preset_pass_manager(optimization_level=3, backend=backend,seed_transpiler=11)
qc = pm.run(dj_circuit)
qc.draw('mpl',idle_wires=False)
# Get the results of the computation
from qiskit.primitives import BackendSampler
sampler = BackendSampler(backend)
result = sampler.run(qc).result()
answer = result.quasi_dists[0]
plot_histogram(answer)
|
https://github.com/QPower-Research/QPowerAlgo
|
QPower-Research
|
import cirq
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (15,10)
q0, q1, q2 = [cirq.LineQubit(i) for i in range(3)]
circuit = cirq.Circuit()
#entagling the 2 quibits in different laboratories
#and preparing the qubit to send
circuit.append(cirq.H(q0))
circuit.append(cirq.H(q1))
circuit.append(cirq.CNOT(q1, q2))
#entangling the qubit we want to send to the one in the first laboratory
circuit.append(cirq.CNOT(q0, q1))
circuit.append(cirq.H(q0))
#measurements
circuit.append(cirq.measure(q0, q1))
#last transformations to obtain the qubit information
circuit.append(cirq.CNOT(q1, q2))
circuit.append(cirq.CZ(q0, q2))
#measure of the qubit in the receiving laboratory along z axis
circuit.append(cirq.measure(q2, key = 'Z'))
circuit
#starting simulation
sim = cirq.Simulator()
results = sim.run(circuit, repetitions=100)
sns.histplot(results.measurements['Z'], discrete = True)
100 - np.count_nonzero(results.measurements['Z']), np.count_nonzero(results.measurements['Z'])
#in qiskit the qubits are integrated in the circuit
qc = QuantumCircuit(3, 1)
#entangling
qc.h(0)
qc.h(1)
qc.cx(1, 2)
qc.cx(0, 1)
#setting for measurment
qc.h(0)
qc.measure([0,1], [0,0])
#transformation to obtain qubit sent
qc.cx(1, 2)
qc.cz(0, 2)
qc.measure(2, 0)
print(qc)
#simulation
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=100)
res = job.result().get_counts(qc)
plt.bar(res.keys(), res.values())
res
|
https://github.com/QPower-Research/QPowerAlgo
|
QPower-Research
|
my_list = [1, 3, 5, 2, 4, 9, 5, 8, 0, 7, 6]
def the_oracle(my_input):
winner = 7
return my_input == winner
for index, trial_number in enumerate(my_list):
if the_oracle(trial_number):
print(f"Found the winner at index {index}!")
print(f"{index+1} calls made")
break
from qiskit import *
from qiskit.visualization import plot_histogram, array_to_latex
from qiskit.providers.ibmq import least_busy
import matplotlib.pyplot as plt
import numpy as np
grover_circuit = QuantumCircuit(2)
def init_state(qc, qubits):
for q in qubits:
qc.h(q)
return qc
grover_circuit = init_state(grover_circuit, [0, 1])
grover_circuit.draw("mpl")
#define the oracle circuit
def oracle(qc, qubits):
qc.cz(qubits[0], qubits[1])
qc = QuantumCircuit(2)
oracle(qc, [0, 1])
qc.draw("mpl")
usim = Aer.get_backend('aer_simulator')
qc.save_unitary()
qobj = assemble(qc)
unitary = usim.run(qobj).result().get_unitary()
array_to_latex(unitary, prefix="\\text{One can see that only the state }\ket{11}\\text{ has been flipped: }\n")
def diffusion(qc, qubits):
qc.h([0, 1])
qc.z([0, 1])
qc.cz(0, 1)
qc.h([0, 1])
grover_circuit.barrier()
oracle(grover_circuit, [0, 1])
grover_circuit.barrier()
diffusion(grover_circuit, [0, 1])
grover_circuit.measure_all()
grover_circuit.draw("mpl")
# Let's see if the final statevector matches our expectations
sv_sim = Aer.get_backend('statevector_simulator')
result = sv_sim.run(grover_circuit).result()
statevec = result.get_statevector()
statevec
aer_sim = Aer.get_backend('aer_simulator')
result = execute(grover_circuit, aer_sim, shots=1024).result()
result.get_counts()
# Load IBM Q account and get the least busy backend device
# Run the following line with your API token to use IBM's own quantum computers
#IBMQ.save_account('')
provider = IBMQ.load_account()
provider = IBMQ.get_provider("ibm-q")
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_grover_circuit = transpile(grover_circuit, device, optimization_level=3)
job = device.run(transpiled_grover_circuit)
job_monitor(job, interval=2)
# Get the results from the computation
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)
grover_circuit = QuantumCircuit(3)
grover_circuit = init_state(grover_circuit, [0, 1, 2])
grover_circuit.draw("mpl")
oracle_qc = QuantumCircuit(3)
oracle_qc.cz(0, 1)
oracle_qc.cz(0, 2)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "U$_\omega$"
def diffuser(nqubits):
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> -> |11..1>
for qubit in range(nqubits):
qc.h(qubit)
qc.x(qubit)
# When these are combined, they function as a multi-controlled Z gate
# A negative phase is added to |11..1> to flip the state
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc.h(nqubits-1)
# Apply transformation |11..1> -> |00..0> -> |s>
for qubit in range(nqubits):
qc.x(qubit)
qc.h(qubit)
# We will return the diffuser as a gate
U_s = qc.to_gate()
U_s.name = "U$_s$"
return U_s
num_qubits = 3
grover_circuit = QuantumCircuit(num_qubits)
grover_circuit = init_state(grover_circuit, [0, 1, 2])
grover_circuit.barrier()
grover_circuit.append(oracle_gate, [0, 1, 2])
grover_circuit.barrier()
grover_circuit.append(diffuser(num_qubits), [0, 1, 2])
grover_circuit.measure_all()
grover_circuit.draw("mpl")
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_grover_circuit = transpile(grover_circuit, qasm_sim)
results = qasm_sim.run(transpiled_grover_circuit).result()
counts = results.get_counts()
plot_histogram(counts)
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_grover_circuit = transpile(grover_circuit, device, optimization_level=3)
job = device.run(transpiled_grover_circuit)
job_monitor(job, interval=2)
# Get the results from the computation
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)
|
https://github.com/QPower-Research/QPowerAlgo
|
QPower-Research
|
#In case you don't have qiskit, install it now
%pip install qiskit --quiet
#Installing/upgrading pylatexenc seems to have fixed my mpl issue
#If you try this and it doesn't work, try also restarting the runtime/kernel
%pip install pylatexenc --quiet
!pip install -Uqq ipdb
!pip install qiskit_optimization
import networkx as nx
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer
from qiskit.compiler import transpile
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit.quantum_info import process_fidelity
from qiskit.extensions.hamiltonian_gate import HamiltonianGate
from qiskit.extensions import RXGate, XGate, CXGate
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute
import numpy as np
from qiskit.visualization import plot_histogram
import ipdb
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
#quadratic optimization
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.converters import QuadraticProgramToQubo
%pdb on
# def ApplyCost(qc, gamma):
# Ix = np.array([[1,0],[0,1]])
# Zx= np.array([[1,0],[0,-1]])
# Xx = np.array([[0,1],[1,0]])
# Temp = (Ix-Zx)/2
# T = Operator(Temp)
# I = Operator(Ix)
# Z = Operator(Zx)
# X = Operator(Xx)
# FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T)
# ham = HamiltonianGate(FinalOp,gamma)
# qc.append(ham,[0,1,2])
task = QuadraticProgram(name = 'QUBO on QC')
task.binary_var(name = 'x')
task.binary_var(name = 'y')
task.binary_var(name = 'z')
task.minimize(linear = {"x":-1,"y":2,"z":-3}, quadratic = {("x", "z"): -2, ("y", "z"): -1})
qubo = QuadraticProgramToQubo().convert(task) #convert to QUBO
operator, offset = qubo.to_ising()
print(operator)
# ham = HamiltonianGate(operator,0)
# print(ham)
Ix = np.array([[1,0],[0,1]])
Zx= np.array([[1,0],[0,-1]])
Xx = np.array([[0,1],[1,0]])
Temp = (Ix-Zx)/2
T = Operator(Temp)
I = Operator(Ix)
Z = Operator(Zx)
X = Operator(Xx)
FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T)
ham = HamiltonianGate(FinalOp,0)
print(ham)
#define PYBIND11_DETAILED_ERROR_MESSAGES
def compute_expectation(counts):
"""
Computes expectation value based on measurement results
Args:
counts: dict
key as bitstring, val as count
G: networkx graph
Returns:
avg: float
expectation value
"""
avg = 0
sum_count = 0
for bitstring, count in counts.items():
x = int(bitstring[2])
y = int(bitstring[1])
z = int(bitstring[0])
obj = -2*x*z-y*z-x+2*y-3*z
avg += obj * count
sum_count += count
return avg/sum_count
# We will also bring the different circuit components that
# build the qaoa circuit under a single function
def create_qaoa_circ(theta):
"""
Creates a parametrized qaoa circuit
Args:
G: networkx graph
theta: list
unitary parameters
Returns:
qc: qiskit circuit
"""
nqubits = 3
n,m=3,3
p = len(theta)//2 # number of alternating unitaries
qc = QuantumCircuit(nqubits,nqubits)
Ix = np.array([[1,0],[0,1]])
Zx= np.array([[1,0],[0,-1]])
Xx = np.array([[0,1],[1,0]])
Temp = (Ix-Zx)/2
T = Operator(Temp)
I = Operator(Ix)
Z = Operator(Zx)
X = Operator(Xx)
FinalOp=-2*(Z^I^Z)-(I^Z^Z)-(Z^I^I)+2*(I^Z^I)-3*(I^I^Z)
beta = theta[:p]
gamma = theta[p:]
# initial_state
for i in range(0, nqubits):
qc.h(i)
for irep in range(0, p):
#ipdb.set_trace(context=6)
# problem unitary
# for pair in list(G.edges()):
# qc.rzz(2 * gamma[irep], pair[0], pair[1])
#ApplyCost(qc,2*0)
ham = HamiltonianGate(operator,2 * gamma[irep])
qc.append(ham,[0,1,2])
# mixer unitary
for i in range(0, nqubits):
qc.rx(2 * beta[irep], i)
qc.measure(qc.qubits[:n],qc.clbits[:m])
return qc
# Finally we write a function that executes the circuit on the chosen backend
def get_expectation(shots=512):
"""
Runs parametrized circuit
Args:
G: networkx graph
p: int,
Number of repetitions of unitaries
"""
backend = Aer.get_backend('qasm_simulator')
backend.shots = shots
def execute_circ(theta):
qc = create_qaoa_circ(theta)
# ipdb.set_trace(context=6)
counts = {}
job = execute(qc, backend, shots=1024)
result = job.result()
counts=result.get_counts(qc)
return compute_expectation(counts)
return execute_circ
from scipy.optimize import minimize
expectation = get_expectation()
res = minimize(expectation, [1, 1], method='COBYLA')
expectation = get_expectation()
res = minimize(expectation, res.x, method='COBYLA')
res
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('aer_simulator')
backend.shots = 512
qc_res = create_qaoa_circ(res.x)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc_res, backend, shots=1024)
result = job.result()
counts=result.get_counts(qc_res)
plot_histogram(counts)
|
https://github.com/QPower-Research/QPowerAlgo
|
QPower-Research
|
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/QPower-Research/QPowerAlgo
|
QPower-Research
|
from qiskit import *
from qiskit.visualization import *
import matplotlib.pyplot as plt
import numpy as np
import math
simulator = BasicAer.get_backend('qasm_simulator')
prob_distr = [8, 40, 35, 20, 15, 10, 5, 5]
#normalization
prob_distr = [k/sum(prob_distr) for k in prob_distr]
plt.bar(range(len(prob_distr)),prob_distr)
def ansatz(param, num_layers):
num_q = 3
qc = QuantumCircuit(num_q, num_q)
for j in range(num_layers):
for i in range(num_q):
qc.ry(param[i + j*num_q], i)
if j < num_layers-1:
qc.cx(0,1)
qc.cx(1,2)
qc.cx(2,0)
qc.barrier()
qc.measure(range(num_q), range(num_q))
return qc
ansatz(param = np.random.uniform(0, np.pi, 9), num_layers=3).draw('mpl',fold=-1)
num_layers = 5
def loss_function(params):
num_shots=1024
circ = ansatz(param=params, num_layers=num_layers)
counts = execute(circ, backend=simulator, shots=num_shots).result().get_counts(circ)
strings = ['000','001','010','011','100','101','110','111']
for i in strings:
if i not in counts:
counts[i] = 0
p = [counts[string]/num_shots for string in strings]
"""
cross_entropy = 0
for i in range(len(p)):
if p[i]>0:
cross_entropy -= prob_distr[i]*math.log2(p[i])
return cross_entropy
"""
return sum([(p[i] - prob_distr[i])**2 for i in range(len(prob_distr))])
#return sum([abs(p[i] - prob_distr[i]) for i in range(len(prob_distr))])
#return sum([ prob_distr[i]*math.log2(p[i]) for i in range(len(prob_distr))])
from qiskit.algorithms.optimizers import COBYLA,SLSQP,SPSA
optimizer = COBYLA(250)
ret = optimizer.optimize(num_vars=num_params, objective_function=loss_function, initial_point=np.ones(num_params))
num_shots = 1024
trained_circ = ansatz(param=ret[0], num_layers=num_layers)
counts = execute(trained_circ, backend=simulator, shots=num_shots).result().get_counts(trained_circ)
strings = ['000','001','010','011','100','101','110','111']
for k in strings:
if k not in counts:
counts[k]=0
counts = [counts[i]/1024 for i in strings]
plt.plot(range(len(counts)),counts, color='r')
plt.bar(range(len(prob_distr)), prob_distr)
plt.legend(["qGAN approx.", "Reference"])
plt.title("Probability distributions")
plt.grid()
|
https://github.com/QPower-Research/QPowerAlgo
|
QPower-Research
|
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
from qiskit.aqua.utils import split_dataset_to_data_and_labels
from sklearn import svm
from utility import breast_cancer_pca
from matplotlib import pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
n = 2 # number of principal components kept
training_dataset_size = 20
testing_dataset_size = 10
sample_Total, training_input, test_input, class_labels = breast_cancer_pca(training_dataset_size, testing_dataset_size, n)
data_train, _ = split_dataset_to_data_and_labels(training_input)
data_test, _ = split_dataset_to_data_and_labels(test_input)
print (f"data_train[0].shape: {data_train[0].shape}" )
print (f"data_train[1].shape: {data_train[1].shape}" )
# We use the function of scikit learn to generate linearly separable blobs
centers = [(2.5,0),(0,2.5)]
x, y = make_blobs(n_samples=100, centers=centers, n_features=2,random_state=0,cluster_std=0.5)
fig,ax=plt.subplots(1,2,figsize=(12,4))
ax[0].scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1])
ax[0].set_title('Breast Cancer dataset');
ax[1].scatter(x[:,0],x[:,1],c=y)
ax[1].set_title('Blobs linearly separable');
plt.scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1])
plt.title('Breast Cancer dataset');
model= svm.LinearSVC()
model.fit(data_train[0], data_train[1])
#small utility function
# some utility functions
def make_meshgrid(x, y, h=.02):
x_min, x_max = x.min() - 1, x.max() + 1
y_min, y_max = y.min() - 1, y.max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
return xx, yy
def plot_contours(ax, clf, xx, yy, **params):
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
out = ax.contourf(xx, yy, Z, **params)
return out
accuracy_train = model.score(data_train[0], data_train[1])
accuracy_test = model.score(data_test[0], data_test[1])
X0, X1 = data_train[0][:, 0], data_train[0][:, 1]
xx, yy = make_meshgrid(X0, X1)
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
fig,ax=plt.subplots(1,2,figsize=(15,5))
ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1])
ax[0].set_title('Accuracy on the training set: '+str(accuracy_train));
ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1])
ax[1].set_title('Accuracy on the test set: '+str(accuracy_test));
clf = svm.SVC(gamma = 'scale')
clf.fit(data_train[0], data_train[1]);
accuracy_train = clf.score(data_train[0], data_train[1])
accuracy_test = clf.score(data_test[0], data_test[1])
X0, X1 = data_train[0][:, 0], data_train[0][:, 1]
xx, yy = make_meshgrid(X0, X1)
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
fig,ax=plt.subplots(1,2,figsize=(15,5))
ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1])
ax[0].set_title('Accuracy on the training set: '+str(accuracy_train));
ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1])
ax[1].set_title('Accuracy on the test set: '+str(accuracy_test));
import qiskit as qk
# Creating Qubits
q = qk.QuantumRegister(2)
# Creating Classical Bits
c = qk.ClassicalRegister(2)
circuit = qk.QuantumCircuit(q, c)
circuit.draw('mpl')
# Initialize empty circuit
circuit = qk.QuantumCircuit(q, c)
# Hadamard Gate on the first Qubit
circuit.h(q[0])
# CNOT Gate on the first and second Qubits
circuit.cx(q[0], q[1])
# Measuring the Qubits
circuit.measure(q, c)
circuit.draw('mpl')
# Using Qiskit Aer's Qasm Simulator: Define where do you want to run the simulation.
simulator = qk.BasicAer.get_backend('qasm_simulator')
# Simulating the circuit using the simulator to get the result
job = qk.execute(circuit, simulator, shots=100)
result = job.result()
# Getting the aggregated binary outcomes of the circuit.
counts = result.get_counts(circuit)
print (counts)
from qiskit.aqua.components.feature_maps import SecondOrderExpansion
feature_map = SecondOrderExpansion(feature_dimension=2, depth=1)
x = np.array([0.6, 0.3])
#feature_map.construct_circuit(x)
print(feature_map.construct_circuit(x))
from qiskit.aqua.algorithms import QSVM
qsvm = QSVM(feature_map, training_input, test_input)
#from qiskit.aqua import run_algorithm, QuantumInstance
from qiskit.aqua import algorithm, QuantumInstance
from qiskit import BasicAer
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=10598, seed_transpiler=10598)
result = qsvm.run(quantum_instance)
plt.scatter(training_input['Benign'][:,0], training_input['Benign'][:,1])
plt.scatter(training_input['Malignant'][:,0], training_input['Malignant'][:,1])
length_data = len(training_input['Benign']) + len(training_input['Malignant'])
print("size training set: {}".format(length_data))
#print("Matrix dimension: {}".format(result['kernel_matrix_training'].shape))
print("testing success ratio: ", result['testing_accuracy'])
test_set = np.concatenate((test_input['Benign'], test_input['Malignant']))
y_test = qsvm.predict(test_set, quantum_instance)
plt.scatter(test_set[:, 0], test_set[:,1], c=y_test)
plt.show()
plt.scatter(test_input['Benign'][:,0], test_input['Benign'][:,1])
plt.scatter(test_input['Malignant'][:,0], test_input['Malignant'][:,1])
plt.show()
|
https://github.com/QPower-Research/QPowerAlgo
|
QPower-Research
|
import numpy as np
from numpy import linalg as LA
from scipy.linalg import expm, sinm, cosm
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import math
from scipy import stats
%matplotlib inline
from IPython.display import Image, display, Math, Latex
sns.set(color_codes=True)
#number of vertices
n = 4
#Define adjacency matrix A_Cn
A = np.zeros((n, n))
for i in range(n):
j1 = (i - 1)%n
j2 = (i + 1)%n
A[i][j1] = 1
A[i][j2] = 1
#Define our initial state Psi_a
psi_a = np.zeros(n)
psi_a[3] = 1
#Define the time t >= 0
t = math.pi/2
#Exponentiate or hamiltonian
U_t = expm(1j*t*A)
U_mt = expm(1j*(-t)*A)
#Compute Psi_t
psi_t = U_t @ psi_a
#Compute the probabilities
prob_t = abs(psi_t)**2
M_t = U_t*U_mt
M_t = np.around(M_t, decimals = 3)
M_t
x = M_t[:, 0].real
plt.bar(range(len(x)), x, tick_label=[0, 1, 2, 3])
plt.xlabel('Vertices')
plt.ylabel('Probability')
|
https://github.com/QPower-Research/QPowerAlgo
|
QPower-Research
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import *
from qiskit.providers.ibmq import least_busy
from qiskit.tools.visualization import plot_histogram
from IPython.display import display, Math, Latex
def Increment(size):
U = QuantumCircuit(size)
control = [x for x in range(size-1)]
for k in range(size-1):
U.mcx(control, control[-1]+1)
control.pop()
U.x(0)
U = U.to_gate()
U.name = '--->'
ctl_U = U.control()
return ctl_U
def Decrement(size):
U = QuantumCircuit(size)
control = [x for x in range(size-1)]
for k in range(size-1):
U.x(control)
U.mcx(control, control[-1]+1)
U.x(control)
control.pop()
U.x(0)
U = U.to_gate()
U.name = '<---'
ctl_U = U.control()
return ctl_U
n = 2
steps = 2
graph = QuantumRegister(n+1)
mes = ClassicalRegister(n)
mcq = QuantumCircuit(graph, mes)
#define U(t)
for i in range(steps):
mcq.h(n)
mcq.append(Increment(n), [n]+list(range(0, n)))
mcq.x(n)
mcq.append(Decrement(n), [n]+list(range(0, n)))
mcq.x(n)
mcq.measure(range(n), range(n))
#mcq = transpile(mcq, basis_gates=['cx','u3'],optimization_level=3)
mcq.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
atp = 1024
res = execute(mcq, backend=backend, shots=atp).result()
ans = res.get_counts()
plot_histogram(ans)
IBMQ.load_account()
provider = IBMQ.get_provider(group='open', project='main')
backend = provider.get_backend('ibmq_16_melbourne')
job = execute(mcq, backend=backend)
ans_quantum = job.result().get_counts()
legend = ['QASM','ibmq_16_melbourne']
plot_histogram([ans,ans_quantum], legend=legend)
|
https://github.com/QPower-Research/QPowerAlgo
|
QPower-Research
|
#!pip install qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute, dagcircuit
import numpy as np
from qiskit.visualization import plot_histogram
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
"""
we need to input how many steps the quantum system will take in total similar to CRW
if no of qubits is n then then the graph will have 2^(n-1) nodes or points to shift. here the first qubit will play the role of coin as in CRW.
"""
n_steps = 1 #Number of iterations
qubits= QuantumRegister(4, name = 'qubits')
cbits= ClassicalRegister(4, name= 'cbits')
#increment gate
print(len(qubits))
inc = QuantumCircuit (qubits,name='inc') #Circuit for inc operator
inc.rcccx( qubits[0],qubits[1],qubits[2],qubits[3])
inc.ccx(qubits[0],qubits[1],qubits[2])
inc.cx(qubits[0],qubits[1])
inc.draw()
inc= inc.to_instruction()
#decrement gate
dec= QuantumCircuit (qubits,name='dec') #Circuit for dec operator
dec.x(qubits[0])
dec.x(qubits[1])
dec.x(qubits[2])
dec.rcccx( qubits[0],qubits[1],qubits[2],qubits[3])
dec.x(qubits[2])
dec.ccx(qubits[0],qubits[1],qubits[2])
dec.x(qubits[1])
dec.cx(qubits[0],qubits[1])
dec.x(qubits[0])
dec.draw()
dec= dec.to_instruction()
#Main Circuit
circ = QuantumCircuit (qubits, cbits) #Main circuit
#Fixing the coin spin either 0 or 1
#circ.x(qubits[0])
for i in range(n_steps):
circ.h (qubits[0]) #Coin step
circ.append (inc, [qubits[0],qubits[1],qubits[2],qubits[3]]) #Shift step
circ.append (dec, [qubits[0],qubits[1],qubits[2],qubits[3]]) #Shift step
circ.measure ([qubits[0],qubits[1],qubits[2],qubits[3]], [cbits[0],cbits[1],cbits[2],cbits[3]])
# Draw the circuit
circ.draw()
simulator = Aer.get_backend('qasm_simulator')
job = execute(circ, simulator, shots=1000)
result = job.result()
counts = result.get_counts(circ)
print("\nTotal counts are:",counts)
# Plot a histogram
plot_histogram(counts)
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
# !pip install qiskit==0.7.1
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# Create a Quantum Register with 2 qubits
qr = QuantumRegister(2)
# Create a Classical Register with 2 bits
cr = ClassicalRegister(2)
# Create a Quantum Circuit from the quantum and classical registers
circ = QuantumCircuit(qr, cr)
# Place Hadamard gate on the top wire, putting this qubit in a superposition.
circ.h(qr[0])
# Add a CX (CNOT) gate across the top two wires, entangling the qubits.
circ.cx(qr[0], qr[1])
# Create a barrier that separates the gates from the measurements
circ.barrier(qr)
# Measure the qubits into the classical registers
circ.measure(qr, cr)
# Draw the new circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
# Execute the circuit on the state vector simulator
job_sim = execute(circ, backend_sv_sim)
# Grab the results from the job.
result_sim = job_sim.result()
# Obtain the state vector for the quantum circuit
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector in a manner that contains a comma-delimited string.
quantum_state
# Plot the state vector on a Q-sphere
from qiskit.tools.visualization import plot_state_qsphere
plot_state_qsphere(quantum_state)
# Use the BasicAer qasm_simulator backend
from qiskit import BasicAer
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 1000 times.
job_sim = execute(circ, backend_sim, shots=1000)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(circ)
print(counts)
# Plot the results on a histogram
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 2 qubits
# Create a Classical Register with 2 bits
# Create a Quantum Circuit from the quantum and classical registers
# Place appropriate gates on the wires to achieve the desired Bell state
# Create a barrier that separates the gates from the measurements
# Measure the qubits into the classical registers
# Draw the circuit
# Use the BasicAer statevector_simulator backend
# Execute the circuit on the state vector simulator
# Grab the results from the job.
# Obtain the state vector for the quantum circuit
# Output the quantum state vector in a manner that contains a comma-delimited string.
# Plot the state vector on a Q-sphere
# Use the BasicAer qasm_simulator backend
# Execute the circuit on the qasm simulator, running it 1000 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a histogram
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
# Do the necessary import for our program
#!pip install qiskit-aqua
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 = '((A & B) | (C & D)) & ~(A & D)'
algorithm = Grover(LogicalExpressionOracle(log_expr))
# Run the algorithm on a simulator, printing the most frequently occurring result
backend = BasicAer.get_backend('qasm_simulator')
result = algorithm.run(backend)
print(result['top_measurement'])
plot_histogram(result['measurement'])
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
#!pip install qiskit
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Create a Quantum Register with 3 qubits
qr = QuantumRegister(3)
# Create a Quantum Circuit from the quantum register. Because we're going to use
# the statevector_simulator, we won't measure the circuit or need classical registers.
circ = QuantumCircuit(qr)
# Place an X gate on the 2nd and 3rd wires. The topmost wire is index 0.
circ.x(qr[1])
circ.x(qr[2])
# Draw the circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
# Execute the circuit on the state vector simulator
job_sim = execute(circ, backend_sv_sim)
# Grab the results from the job.
result_sim = job_sim.result()
# Obtain the state vector for the quantum circuit
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector in a manner that contains a comma-delimited string.
quantum_state
# Plot the state vector on a Q-sphere
from qiskit.tools.visualization import plot_state_qsphere
plot_state_qsphere(quantum_state)
# Create a Classical Register with 3 bits
cr = ClassicalRegister(3)
# Create the measurement portion of a quantum circuit
meas_circ = QuantumCircuit(qr, cr)
# Create a barrier that separates the gates from the measurements
meas_circ.barrier(qr)
# Measure the qubits into the classical registers
meas_circ.measure(qr, cr)
# Add the measument circuit to the original circuit
complete_circuit = circ + meas_circ
# Draw the new circuit
complete_circuit.draw(output='mpl')
# Use the BasicAer qasm_simulator backend
from qiskit import BasicAer
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 1000 times.
job_sim = execute(complete_circuit, backend_sim, shots=1000)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(complete_circuit)
print(counts)
# Plot the results on a histogram
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 3 qubits
# Create a Quantum Circuit from the quantum register. Because we're going to use
# the statevector_simulator, we won't measure the circuit or need classical registers.
# Place Hadamard gate on each of the wires.
# Draw the circuit
# Use the BasicAer statevector_simulator backend
# Execute the circuit on the state vector simulator
# Grab the results from the job.
# Obtain the state vector for the quantum circuit
# Output the quantum state vector in a manner that contains a comma-delimited string.
# Plot the state vector on a Q-sphere
# Create a Classical Register with 3 bits
# Create the measurement portion of a quantum circuit
# Create a barrier that separates the gates from the measurements
# Measure the qubits into the classical registers
# Add the measument circuit to the original circuit
# Draw the new circuit
# Use the BasicAer qasm_simulator backend
# Execute the circuit on the qasm simulator, running it 1000 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a histogram
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
#!pip install qiskit
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Create a Quantum Register with 1 qubit (wire).
qr = QuantumRegister(1)
# Create a Classical Register with 1 bit (double wire).
cr = ClassicalRegister(1)
# Create a Quantum Circuit from the quantum and classical registers
circ = QuantumCircuit(qr, cr)
# Place an Hadamard gate on the qubit wire
circ.h(qr[0])
# Measure the qubit into the classical register
circ.measure(qr, cr)
# Draw the circuit
circ.draw(output='mpl')
# Import BasicAer
from qiskit import BasicAer
# Use BasicAer's qasm_simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 100 times.
job_sim = execute(circ, backend_sim, shots=100)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(circ)
print(counts)
from qiskit.tools.visualization import plot_histogram
# Plot the results on a bar chart
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 1 qubit (wire).
# Create a Classical Register with 1 bit (double wire).
# Create a Quantum Circuit from the quantum and classical registers
# Place an X gate followed by a Hadamard gate on the qubit wire. The registers are zero-indexed.
# Measure the qubit into the classical register
# Draw the circuit
# Import BasicAer
# Use BasicAer's qasm_simulator
# Execute the circuit on the qasm simulator, running it 100 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a bar chart
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
#!pip install qiskit
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Create a Quantum Register with 1 qubit (wire).
qr = QuantumRegister(1)
# Create a Classical Register with 1 bit (double wire).
cr = ClassicalRegister(1)
# Create a Quantum Circuit from the quantum and classical registers
circ = QuantumCircuit(qr, cr)
# Place an X gate on the qubit wire. The registers are zero-indexed.
circ.x(qr[0])
# Measure the qubit into the classical register
circ.measure(qr, cr)
# Draw the circuit
circ.draw(output='mpl')
# Import BasicAer
from qiskit import BasicAer
# Use BasicAer's qasm_simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 100 times.
job_sim = execute(circ, backend_sim, shots=100)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(circ)
print(counts)
from qiskit.tools.visualization import plot_histogram
# Plot the results on a bar chart
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 1 qubit (wire).
# Create a Classical Register with 1 bit (double wire).
# Create a Quantum Circuit from the quantum and classical registers
# Place two X gates on the qubit wire. The registers are zero-indexed.
# Measure the qubit into the classical register
# Draw the circuit
# Import BasicAer
# Use BasicAer's qasm_simulator
# Execute the circuit on the qasm simulator, running it 100 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a bar chart
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
#!pip install qiskit
# Do the usual setup, but without classical registers or measurement
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, execute
qr = QuantumRegister(1)
circ = QuantumCircuit(qr)
# Place an Ry gate with a −3π/4 rotation
circ.ry(-3/4 * np.pi, qr[0])
# Draw the circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circ, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector
quantum_state
# Plot the state vector on a Bloch sphere
from qiskit.tools.visualization import plot_bloch_multivector
plot_bloch_multivector(quantum_state)
# Do the usual setup, but without classical registers or measurement
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, execute
qr = QuantumRegister(1)
circ = QuantumCircuit(qr)
# Place gates that will achieve the desired state
# Draw the circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circ, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector
quantum_state
# Plot the state vector on a Bloch sphere
from qiskit.tools.visualization import plot_bloch_multivector
plot_bloch_multivector(quantum_state)
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
# !pip install qiskit==0.7.1
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# Create a Quantum Register with 2 qubits
qr = QuantumRegister(2)
# Create a Classical Register with 2 bits
cr = ClassicalRegister(2)
# Create a Quantum Circuit from the quantum and classical registers
circ = QuantumCircuit(qr, cr)
# Place Hadamard gate on the top wire, putting this qubit in a superposition.
circ.h(qr[0])
# Add a CX (CNOT) gate across the top two wires, entangling the qubits.
circ.cx(qr[0], qr[1])
# Create a barrier that separates the gates from the measurements
circ.barrier(qr)
# Measure the qubits into the classical registers
circ.measure(qr, cr)
# Draw the new circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
# Execute the circuit on the state vector simulator
job_sim = execute(circ, backend_sv_sim)
# Grab the results from the job.
result_sim = job_sim.result()
# Obtain the state vector for the quantum circuit
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector in a manner that contains a comma-delimited string.
quantum_state
# Plot the state vector on a Q-sphere
from qiskit.tools.visualization import plot_state_qsphere
plot_state_qsphere(quantum_state)
# Use the BasicAer qasm_simulator backend
from qiskit import BasicAer
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 1000 times.
job_sim = execute(circ, backend_sim, shots=1000)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(circ)
print(counts)
# Plot the results on a histogram
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 2 qubits
# Create a Classical Register with 2 bits
# Create a Quantum Circuit from the quantum and classical registers
# Place appropriate gates on the wires to achieve the desired Bell state
# Create a barrier that separates the gates from the measurements
# Measure the qubits into the classical registers
# Draw the circuit
# Use the BasicAer statevector_simulator backend
# Execute the circuit on the state vector simulator
# Grab the results from the job.
# Obtain the state vector for the quantum circuit
# Output the quantum state vector in a manner that contains a comma-delimited string.
# Plot the state vector on a Q-sphere
# Use the BasicAer qasm_simulator backend
# Execute the circuit on the qasm simulator, running it 1000 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a histogram
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
# Do the necessary import for our program
#!pip install qiskit-aqua
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 = '((A & B) | (C & D)) & ~(A & D)'
algorithm = Grover(LogicalExpressionOracle(log_expr))
# Run the algorithm on a simulator, printing the most frequently occurring result
backend = BasicAer.get_backend('qasm_simulator')
result = algorithm.run(backend)
print(result['top_measurement'])
plot_histogram(result['measurement'])
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
#!pip install qiskit
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Create a Quantum Register with 3 qubits
qr = QuantumRegister(3)
# Create a Quantum Circuit from the quantum register. Because we're going to use
# the statevector_simulator, we won't measure the circuit or need classical registers.
circ = QuantumCircuit(qr)
# Place an X gate on the 2nd and 3rd wires. The topmost wire is index 0.
circ.x(qr[1])
circ.x(qr[2])
# Draw the circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
# Execute the circuit on the state vector simulator
job_sim = execute(circ, backend_sv_sim)
# Grab the results from the job.
result_sim = job_sim.result()
# Obtain the state vector for the quantum circuit
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector in a manner that contains a comma-delimited string.
quantum_state
# Plot the state vector on a Q-sphere
from qiskit.tools.visualization import plot_state_qsphere
plot_state_qsphere(quantum_state)
# Create a Classical Register with 3 bits
cr = ClassicalRegister(3)
# Create the measurement portion of a quantum circuit
meas_circ = QuantumCircuit(qr, cr)
# Create a barrier that separates the gates from the measurements
meas_circ.barrier(qr)
# Measure the qubits into the classical registers
meas_circ.measure(qr, cr)
# Add the measument circuit to the original circuit
complete_circuit = circ + meas_circ
# Draw the new circuit
complete_circuit.draw(output='mpl')
# Use the BasicAer qasm_simulator backend
from qiskit import BasicAer
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 1000 times.
job_sim = execute(complete_circuit, backend_sim, shots=1000)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(complete_circuit)
print(counts)
# Plot the results on a histogram
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 3 qubits
# Create a Quantum Circuit from the quantum register. Because we're going to use
# the statevector_simulator, we won't measure the circuit or need classical registers.
# Place Hadamard gate on each of the wires.
# Draw the circuit
# Use the BasicAer statevector_simulator backend
# Execute the circuit on the state vector simulator
# Grab the results from the job.
# Obtain the state vector for the quantum circuit
# Output the quantum state vector in a manner that contains a comma-delimited string.
# Plot the state vector on a Q-sphere
# Create a Classical Register with 3 bits
# Create the measurement portion of a quantum circuit
# Create a barrier that separates the gates from the measurements
# Measure the qubits into the classical registers
# Add the measument circuit to the original circuit
# Draw the new circuit
# Use the BasicAer qasm_simulator backend
# Execute the circuit on the qasm simulator, running it 1000 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a histogram
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
#!pip install qiskit
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Create a Quantum Register with 1 qubit (wire).
qr = QuantumRegister(1)
# Create a Classical Register with 1 bit (double wire).
cr = ClassicalRegister(1)
# Create a Quantum Circuit from the quantum and classical registers
circ = QuantumCircuit(qr, cr)
# Place an Hadamard gate on the qubit wire
circ.h(qr[0])
# Measure the qubit into the classical register
circ.measure(qr, cr)
# Draw the circuit
circ.draw(output='mpl')
# Import BasicAer
from qiskit import BasicAer
# Use BasicAer's qasm_simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 100 times.
job_sim = execute(circ, backend_sim, shots=100)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(circ)
print(counts)
from qiskit.tools.visualization import plot_histogram
# Plot the results on a bar chart
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 1 qubit (wire).
# Create a Classical Register with 1 bit (double wire).
# Create a Quantum Circuit from the quantum and classical registers
# Place an X gate followed by a Hadamard gate on the qubit wire. The registers are zero-indexed.
# Measure the qubit into the classical register
# Draw the circuit
# Import BasicAer
# Use BasicAer's qasm_simulator
# Execute the circuit on the qasm simulator, running it 100 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a bar chart
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
#!pip install qiskit
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Create a Quantum Register with 1 qubit (wire).
qr = QuantumRegister(1)
# Create a Classical Register with 1 bit (double wire).
cr = ClassicalRegister(1)
# Create a Quantum Circuit from the quantum and classical registers
circ = QuantumCircuit(qr, cr)
# Place an X gate on the qubit wire. The registers are zero-indexed.
circ.x(qr[0])
# Measure the qubit into the classical register
circ.measure(qr, cr)
# Draw the circuit
circ.draw(output='mpl')
# Import BasicAer
from qiskit import BasicAer
# Use BasicAer's qasm_simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 100 times.
job_sim = execute(circ, backend_sim, shots=100)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(circ)
print(counts)
from qiskit.tools.visualization import plot_histogram
# Plot the results on a bar chart
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 1 qubit (wire).
# Create a Classical Register with 1 bit (double wire).
# Create a Quantum Circuit from the quantum and classical registers
# Place two X gates on the qubit wire. The registers are zero-indexed.
# Measure the qubit into the classical register
# Draw the circuit
# Import BasicAer
# Use BasicAer's qasm_simulator
# Execute the circuit on the qasm simulator, running it 100 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a bar chart
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
#!pip install qiskit
# Do the usual setup, but without classical registers or measurement
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, execute
qr = QuantumRegister(1)
circ = QuantumCircuit(qr)
# Place an Ry gate with a −3π/4 rotation
circ.ry(-3/4 * np.pi, qr[0])
# Draw the circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circ, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector
quantum_state
# Plot the state vector on a Bloch sphere
from qiskit.tools.visualization import plot_bloch_multivector
plot_bloch_multivector(quantum_state)
# Do the usual setup, but without classical registers or measurement
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, execute
qr = QuantumRegister(1)
circ = QuantumCircuit(qr)
# Place gates that will achieve the desired state
# Draw the circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circ, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector
quantum_state
# Plot the state vector on a Bloch sphere
from qiskit.tools.visualization import plot_bloch_multivector
plot_bloch_multivector(quantum_state)
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
"""Imports."""
import matplotlib.pyplot as plt
import numpy as np
import scipy as scp
from IPython.display import clear_output, display
import qiskit.pulse as pulse
import qiskit
"""Plotting style."""
%matplotlib inline
plt.rcParams.update({"font.size": 16, "font.weight": "bold"})
"""Load account: Only do this once."""
qiskit.IBMQ.load_account()
"""Get a provider and see available backends."""
provider = qiskit.IBMQ.get_provider(hub="ibm-q")
print("Available backends:", *provider.backends())
"""Select ibmq-poughkeepsie device to use Pulse."""
# backend = provider.get_backend("ibmq_poughkeepsie")
# config = backend.configuration()
# defaults = backend.defaults()
"""Get a pulse channel system."""
# system = pulse.PulseChannelSpec.from_backend(backend)
"""Video showing conceptual visualization of the above experiment on the Bloch sphere."""
from IPython.display import YouTubeVideo
YouTubeVideo("g10PIHQ65L4", width=640, height=360)
"""Load in the raw data."""
data = data = np.loadtxt("https://raw.githubusercontent.com/rmlarose/qcbq/master/data/t1_data.txt")
times = data[:, 1] # microseconds
measurements = data[:, 0] # probability of excited state
"""Plot the raw data."""
### Your code here!
plt.figure(figsize=(12, 5))
plt.plot(times, measurements, "--o", linewidth=3);
plt.xlabel("Time [microseconds]");
plt.ylabel("Probability of excited state");
plt.title("T1 measurement data")
plt.grid();
plt.show()
"""Do the data fitting."""
def fit(time: float, T1: float) -> float:
return np.exp(-time / T1) ### Your code here!
"""Use scipy.optimize.curve_fit to fit the data."""
### Your code here!
optimal_params, covariance = scp.optimize.curve_fit(fit, times, measurements)
print(f"Computed T1 value: {round(optimal_params[0], 3)} microseconds.")
"""Plot your fit over the raw data here."""
### Your code here!
# Compute the fit
fitvals = fit(times, *optimal_params)
# Plot the fit and data
plt.figure(figsize=(12, 5))
plt.plot(times, measurements, "-.", linewidth=2, label="Data");
plt.plot(times, fitvals, "-", linewidth=4, label="Fit");
plt.xlabel("Time [microseconds]");
plt.ylabel("Frequency of excited state");
plt.title("T1 measurement data");
plt.legend();
plt.grid();
plt.text(20, 0.8, rf"T1 = {round(optimal_params[0], 3)} $\mu$s")
plt.show()
"""Video showing conceptual visualization of the above experiment on the Bloch sphere."""
from IPython.display import YouTubeVideo
YouTubeVideo("9Ekep8zgZHc", width=640, height=360)
"""Load in the raw data."""
t2data = np.loadtxt("https://raw.githubusercontent.com/rmlarose/qcbq/master/data/t2_data.txt")
times = t2data[:, 1] # microseconds
measurements = t2data[:, 0] # probability of ground state
"""Plot the raw data."""
### Your code here!
plt.figure(figsize=(12, 5))
plt.scatter(times, measurements);
plt.xlabel("Time [microseconds]");
plt.ylabel("Probability of ground state");
plt.title("Ramsey measurement data")
plt.grid();
plt.show()
"""Define the fit function."""
def ramsey_fit(time: float, domega: float, T2: float) -> float:
return 0.5 + 0.5 * np.cos(domega * times) * np.exp(- times / T2) ### Your code here!
"""Do the fitting."""
### Your code here!
optimal_params, covariance = scp.optimize.curve_fit(ramsey_fit, times, measurements)
"""Plot the fit and data."""
### Your code here!
# Compute the fit
fitvals = ramsey_fit(times, *optimal_params)
# Do the plotting
plt.figure(figsize=(12, 5))
plt.plot(times, fitvals, "-", linewidth=4, label="Fit", color="red");
plt.scatter(times, measurements, label="Data");
plt.xlabel("Time [microseconds]");
plt.ylabel("Probability of ground state");
plt.title("Ramsey measurement data")
plt.legend();
plt.grid();
plt.text(30, -0.1, rf"T2 = {round(optimal_params[1], 3)} $\mu$s")
plt.show()
"""Video showing conceptual visualization of the above experiment on the Bloch sphere."""
from IPython.display import YouTubeVideo
YouTubeVideo("wkuqcCVhl04", width=640, height=360)
"""Load in the raw data."""
t2echo_data = np.loadtxt("https://raw.githubusercontent.com/rmlarose/qcbq/master/data/t2e_data.txt")
times = t2echo_data[:, 1] # microseconds
measurements = t2echo_data[:, 0] # probability of ground state
"""Plot the raw data."""
### Your code here!
plt.figure(figsize=(12, 5))
plt.plot(times, measurements, "--o", linewidth=3);
plt.xlabel("Time [microseconds]");
plt.ylabel("Frequency of ground state");
plt.title("Hahn-echo measurement data");
plt.grid();
plt.show()
"""Define a fit function."""
def hahn_fit(time: float, T2: float) -> float:
return 0.5 * (1 + np.exp(-time / T2)) ### Your code here!
"""Do the fitting."""
### Your code here!
optimal_params, covariance = scp.optimize.curve_fit(hahn_fit, times, measurements)
print("T2 =", round(optimal_params[0], 2), "microseconds.")
"""Plot the fit function and data."""
### Your code here!
# Compute the fit
fitvals = hahn_fit(times, *optimal_params)
# Plot the fit and data
plt.figure(figsize=(12, 5))
plt.plot(times, measurements, "--o", linewidth=2, label="Data");
plt.plot(times, fitvals, "-", linewidth=4, label="Fit");
plt.xlabel("Time [microseconds]");
plt.ylabel("Frequency of ground state");
plt.title("Hahn-echo measurement data");
plt.legend();
plt.grid();
plt.text(25, 0.9, rf"T2 = {round(optimal_params[0], 3)} $\mu$s")
plt.show()
"""Function for the Bloch-Redfield density matrix."""
def rho(t: float,
alpha0: complex = np.sqrt(1 / 2),
beta0: complex = np.sqrt(1 / 2),
T1: float = 40,
T2: float = 70) -> np.ndarray:
return np.array([
[1 + (abs(alpha0)**2 - 1) * np.exp(- t / T1), alpha0 * np.conj(beta0) * np.exp(-t / T2)],
[np.conj(alpha0) * beta0 * np.exp(-t / T2), abs(beta0)**2 * np.exp(-t / T1)]
])
"""Visualization of the Bloch-Redfield density matrix."""
import ipywidgets
@ipywidgets.interact
def vis(time=(0, 500, 1), T1=(20, 200, 1), T2=(20, 200, 1)):
plt.title(r"$\rho_{BR}$")
plt.imshow(np.real(rho(time, T1=T1, T2=T2)), cmap="Greens", vmin=0, vmax=1)
plt.text(-0.2, 0.0, round(rho(time, T1=T1, T2=T2)[0, 0], 4))
plt.text(-0.2, 1.0, round(rho(time, T1=T1, T2=T2)[1, 0], 4))
plt.text(0.8, 0.0, round(rho(time, T1=T1, T2=T2)[0, 1], 4))
plt.text(0.8, 1.0, round(rho(time, T1=T1, T2=T2)[1, 1], 4))
plt.colorbar()
plt.axis("off")
plt.show()
"""Plot the matrix elements of rho over time."""
# Initial state
alpha = np.sqrt(0.3)
beta = np.sqrt(0.7)
# T1 and T2 times
T1 = 50
T2 = 70
# Time
time = np.linspace(0, 250, 100)
# Matrix elements
rho00 = 1 + (abs(alpha)**2 - 1) * np.exp(-time / T1)
rho01 = alpha * np.conj(beta) * np.exp(-time / T2)
rho10 = np.conj(rho01)
rho11 = 1 - rho00
# Plotting
plt.figure(figsize=(16, 5));
plt.plot(time, rho00, "--", label=r"$\rho_{00}$", linewidth=4);
plt.plot(time, np.real(rho01), "--", label=r"$\Re[\rho_{01}]$", linewidth=4);
plt.plot(time, np.real(rho10), "--", label=r"$\Re[\rho_{10}]$", linewidth=4);
plt.plot(time, rho11, "--", label=r"$\rho_{11}$", linewidth=4);
plt.grid();
plt.legend();
plt.xlabel("Time [microseconds]");
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
"""Imports."""
import matplotlib.pyplot as plt
import numpy as np
import scipy as scp
from IPython.display import clear_output, display
import qiskit.pulse as pulse
import qiskit
"""Plotting style."""
%matplotlib inline
plt.rcParams.update({"font.size": 16, "font.weight": "bold"})
"""Load account: Only do this once."""
qiskit.IBMQ.load_account()
"""Get a provider and see available backends."""
provider = qiskit.IBMQ.get_provider(hub="ibm-q")
print("Available backends:", *provider.backends())
"""Select ibmq-poughkeepsie device to use Pulse."""
# backend = provider.get_backend("ibmq_poughkeepsie")
# config = backend.configuration()
# defaults = backend.defaults()
"""Get a pulse channel system."""
# system = pulse.PulseChannelSpec.from_backend(backend)
"""Video showing conceptual visualization of the above experiment on the Bloch sphere."""
from IPython.display import YouTubeVideo
YouTubeVideo("g10PIHQ65L4", width=640, height=360)
"""Load in the raw data."""
data = data = np.loadtxt("https://raw.githubusercontent.com/rmlarose/qcbq/master/data/t1_data.txt")
times = data[:, 1] # microseconds
measurements = data[:, 0] # probability of excited state
"""Plot the raw data."""
### Your code here!
"""Do the data fitting."""
def fit(time: float, T1: float) -> float:
### Your code here!
"""Use scipy.optimize.curve_fit to fit the data."""
### Your code here!
"""Plot your fit over the raw data here."""
### Your code here!
# Compute the fit
"""Video showing conceptual visualization of the above experiment on the Bloch sphere."""
from IPython.display import YouTubeVideo
YouTubeVideo("9Ekep8zgZHc", width=640, height=360)
"""Load in the raw data."""
t2data = np.loadtxt("https://raw.githubusercontent.com/rmlarose/qcbq/master/data/t2_data.txt")
times = t2data[:, 1] # microseconds
measurements = t2data[:, 0] # probability of ground state
"""Plot the raw data."""
### Your code here!
"""Define the fit function."""
def ramsey_fit(time: float, domega: float, T2: float) -> float:
### Your code here!
"""Do the fitting."""
### Your code here!
"""Plot the fit and data."""
### Your code here!
"""Video showing conceptual visualization of the above experiment on the Bloch sphere."""
from IPython.display import YouTubeVideo
YouTubeVideo("wkuqcCVhl04", width=640, height=360)
"""Load in the raw data."""
t2echo_data = np.loadtxt("https://raw.githubusercontent.com/rmlarose/qcbq/master/data/t2e_data.txt")
times = t2echo_data[:, 1] # microseconds
measurements = t2echo_data[:, 0] # probability of ground state
"""Plot the raw data."""
### Your code here!
"""Define a fit function."""
def hahn_fit(time: float, T2: float) -> float:
### Your code here!
"""Do the fitting."""
### Your code here!
"""Plot the fit function and data."""
### Your code here!
"""Function for the Bloch-Redfield density matrix."""
def rho(t: float,
alpha0: complex = np.sqrt(1 / 2),
beta0: complex = np.sqrt(1 / 2),
T1: float = 40,
T2: float = 70) -> np.ndarray:
return np.array([
[1 + (abs(alpha0)**2 - 1) * np.exp(- t / T1), alpha0 * np.conj(beta0) * np.exp(-t / T2)],
[np.conj(alpha0) * beta0 * np.exp(-t / T2), abs(beta0)**2 * np.exp(-t / T1)]
])
"""Visualization of the Bloch-Redfield density matrix."""
import ipywidgets
@ipywidgets.interact
def vis(time=(0, 500, 1), T1=(20, 200, 1), T2=(20, 200, 1)):
plt.title(r"$\rho_{BR}$")
plt.imshow(np.real(rho(time, T1=T1, T2=T2)), cmap="Greens", vmin=0, vmax=1)
plt.text(-0.2, 0.0, round(rho(time, T1=T1, T2=T2)[0, 0], 4))
plt.text(-0.2, 1.0, round(rho(time, T1=T1, T2=T2)[1, 0], 4))
plt.text(0.8, 0.0, round(rho(time, T1=T1, T2=T2)[0, 1], 4))
plt.text(0.8, 1.0, round(rho(time, T1=T1, T2=T2)[1, 1], 4))
plt.colorbar()
plt.axis("off")
plt.show()
"""Plot the matrix elements of rho over time."""
# Initial state
alpha = np.sqrt(0.3)
beta = np.sqrt(0.7)
# T1 and T2 times
T1 = 50
T2 = 70
# Time
time = np.linspace(0, 250, 100)
# Matrix elements
rho00 = 1 + (abs(alpha)**2 - 1) * np.exp(-time / T1)
rho01 = alpha * np.conj(beta) * np.exp(-time / T2)
rho10 = np.conj(rho01)
rho11 = 1 - rho00
# Plotting
plt.figure(figsize=(16, 5));
plt.plot(time, rho00, "--", label=r"$\rho_{00}$", linewidth=4);
plt.plot(time, np.real(rho01), "--", label=r"$\Re[\rho_{01}]$", linewidth=4);
plt.plot(time, np.real(rho10), "--", label=r"$\Re[\rho_{10}]$", linewidth=4);
plt.plot(time, rho11, "--", label=r"$\rho_{11}$", linewidth=4);
plt.grid();
plt.legend();
plt.xlabel("Time [microseconds]");
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
"""Imports for the notebook."""
_req = """This notebook is written for
qiskit-aqua==0.6.0
Your code may not execute properly.
"""
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import warnings
import qiskit
if "0.6" not in qiskit.__qiskit_version__.get("qiskit-aqua"):
warnings.warn(_req)
"""Optional: Turn off warnings for the notebook."""
warnings.filterwarnings("ignore")
"""Specific imports for QAOA with MaxCut."""
# Import the QAOA object
from qiskit.aqua.algorithms.adaptive import QAOA
# Import tools for the MaxCut problem
from qiskit.aqua.translators.ising.max_cut import (
get_max_cut_qubitops, max_cut_value, random_graph
)
from qiskit.aqua.operators.weighted_pauli_operator import (
Pauli, WeightedPauliOperator
)
# Import optimizers in Qiskit for finding the best parameters in the QAOA circuit
from qiskit.aqua.components.optimizers import ADAM, AQGD, COBYLA, POWELL
"""Helper function for drawing weighted graphs.
You don't need to know how this function works. You will see how to use it below.
"""
def draw_weighted(graph: nx.Graph,
pos_color: str = "blue",
neg_color: str = "red",
scale: float = 2.0,
**kwargs) -> None:
"""Shows a visual of a graph with edges scaled by weight and colored by sign.
Args:
graph: The weighted graph to visualize.
pos_color: Color for edges with a positive weight.
neg_color: Color for edges with a negative weight.
scale: Floating point value to scale edge weights by
in the visualization.
Keyword Args:
cut (List[Int]): A list of 0, 1 values specifying which
nodes are in which class. The number of
values must be equal to the number of
nodes in the graph.
"""
pos = nx.spring_layout(graph)
if "cut" in kwargs.keys():
keys = kwargs["cut"]
if len(keys) != len(graph.nodes):
raise ValueError(
f"ecolor_key has length {len(keys)} but graph has {len(graph.nodes)} nodes."
)
nx.draw_networkx_nodes(graph, pos, node_size=700, node_color=keys, cmap=plt.cm.Greens)
else:
nx.draw_networkx_nodes(graph, pos, node_size=700)
col = lambda sgn: pos_color if sgn > 0 else neg_color
for edge in graph.edges:
weight = graph.get_edge_data(*edge)["weight"]
sgn = np.sign(weight)
size = abs(weight)
nx.draw_networkx_edges(graph,
pos,
edgelist=[edge],
width=scale * size,
edge_color=col(sgn),
alpha=0.5)
nx.draw_networkx_labels(graph, pos, font_size=20)
plt.axis("off")
plt.show()
"""Define the graph for MaxCut via an adjacency matrix."""
nodes = 6 # Vary the number of nodes here
matrix = random_graph(n=nodes, edge_prob=0.5, seed=2)
print("The adjacency matrix is:")
print(matrix)
"""Convert the adjacency matrix to a (weighted) graph and visualize it."""
graph = nx.from_numpy_array(matrix, parallel_edges=False)
draw_weighted(graph)
"""TODO: Put a list of 1s and 0s to assign vertex sets and see
what the value of your cut is.
"""
cut = np.array([0, 1, 0, 0, 0, 0]) ### <-- Your code here!
print("The value of this cut is:", max_cut_value(cut, matrix))
"""Visualize the cut by coloring nodes in distinct vertex sets different colors."""
draw_weighted(graph, cut=[0, 0, 0, 1, 1, 1])
"""Pauli operators from matrix."""
op, shift = get_max_cut_qubitops(matrix)
"""Inspect the Pauli operators."""
print("Edge set of the graph:")
for edge in graph.edges:
print("Weight:", graph.get_edge_data(*edge)["weight"], "Edge:", edge)
print("\nWeighted Pauli operators.")
for pauli in op.paulis:
print(2 * np.real(pauli[0]), "*", pauli[1].to_label()[::-1])
"""Make the QAOA instance."""
qaoa = QAOA(op, POWELL(), p=1)
"""See the settings of the QAOA object."""
print(qaoa.print_settings())
"""Inspect the circuits."""
backend = qiskit.BasicAer.get_backend("qasm_simulator")
circs = qaoa.construct_circuit([1, 2], backend=backend)
print(f"There are {len(circs)} circuits.")
print(circs[0])
"""Set the number of points N to define the grid. Larger N ==> longer runtime."""
N = 10
gammas = np.linspace(-np.pi, np.pi, N)
betas = np.linspace(-np.pi, np.pi, N)
"""Minor hacks for the QAOA instance to make the grid search possible.
Run this cell without too much thought -- this is necessary because the way Aqua is set up.
"""
quantum_instance = qiskit.aqua.QuantumInstance(backend=qiskit.BasicAer.get_backend("qasm_simulator"))
qaoa._quantum_instance = quantum_instance
qaoa._use_simulator_operator_mode = True
"""Do the grid search and display the progress."""
import progressbar
bar = progressbar.ProgressBar(maxval=N**2)
costs = np.zeros((len(gammas), len(betas)), dtype=float)
bar.start()
for (ii, gamma) in enumerate(gammas):
for (jj, beta) in enumerate(betas):
costs[ii][jj] = qaoa._energy_evaluation(np.array([gamma, beta]))
bar.update(N * ii + jj)
bar.finish()
"""Visualize the landscape."""
plt.figure(figsize=(7, 7));
plt.imshow(costs, origin=(0, 0));
plt.xlabel("Gammas")
plt.ylabel("Betas")
plt.colorbar();
"""Your code here!"""
"""Write code to answer the above question here."""
print("Min cost =", np.min(costs)) # Your code here!
"""Get a quantum instance and run the algorithm."""
qaoa._optimizer = POWELL()
result = qaoa.run(quantum_instance)
"""View the optimal cost."""
qaoa.get_optimal_cost()
"""Get the circuit with optimal parameters."""
circ = qaoa.get_optimal_circuit()
qreg = circ.qregs[0]
creg = qiskit.ClassicalRegister(6)
circ.add_register(creg)
circ.measure(qreg, creg)
print(circ)
"""Execute the circuit to sample from it."""
job = qiskit.execute(circ, backend=backend, shots=100000)
res = job.result()
counts = res.get_counts()
"""Visualize the statistics."""
qiskit.visualization.plot_histogram(counts, figsize=(17, 6))
"""Get the top sampled bit strings."""
import operator
ntop = 10
top_cuts = sorted(counts, key=operator.itemgetter(1))
print(f"Top {ntop} sampled cuts.")
for cut in top_cuts[:ntop]:
print(cut[::-1])
"""Select a sampled cut and see its value."""
cut = np.array([1, 1, 0, 0, 0, 1]) ### <-- Your answer here!
print("The value of this cut is:", max_cut_value(cut, matrix))
"""Brute force search for the maximum cut."""
import itertools
high = -np.inf
conf = np.zeros(nodes)
cuts = itertools.product(*[[0, 1]] * nodes)
for cut in cuts:
cur = max_cut_value(np.array(cut), matrix)
if cur > high:
conf = np.array(cut)
high = cur
print("Value of maximum cut:", high)
print("Optimal cut:", conf)
"""Visualize the graph to see the maximum cut."""
draw_weighted(graph, cut=conf)
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
"""Imports for the notebook."""
_req = """This notebook is written for
qiskit-aqua==0.6.0
Your code may not execute properly.
"""
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import warnings
import qiskit
if "0.6" not in qiskit.__qiskit_version__.get("qiskit-aqua"):
warnings.warn(_req)
"""Optional: Turn off warnings for the notebook."""
warnings.filterwarnings("ignore")
"""Specific imports for QAOA with MaxCut."""
# Import the QAOA object
from qiskit.aqua.algorithms.adaptive import QAOA
# Import tools for the MaxCut problem
from qiskit.aqua.translators.ising.max_cut import (
get_max_cut_qubitops, max_cut_value, random_graph
)
from qiskit.aqua.operators.weighted_pauli_operator import (
Pauli, WeightedPauliOperator
)
# Import optimizers in Qiskit for finding the best parameters in the QAOA circuit
from qiskit.aqua.components.optimizers import ADAM, AQGD, COBYLA, POWELL
"""Helper function for drawing weighted graphs.
You don't need to know how this function works. You will see how to use it below.
"""
def draw_weighted(graph: nx.Graph,
pos_color: str = "blue",
neg_color: str = "red",
scale: float = 2.0,
**kwargs) -> None:
"""Shows a visual of a graph with edges scaled by weight and colored by sign.
Args:
graph: The weighted graph to visualize.
pos_color: Color for edges with a positive weight.
neg_color: Color for edges with a negative weight.
scale: Floating point value to scale edge weights by
in the visualization.
Keyword Args:
cut (List[Int]): A list of 0, 1 values specifying which
nodes are in which class. The number of
values must be equal to the number of
nodes in the graph.
"""
pos = nx.spring_layout(graph)
if "cut" in kwargs.keys():
keys = kwargs["cut"]
if len(keys) != len(graph.nodes):
raise ValueError(
f"ecolor_key has length {len(keys)} but graph has {len(graph.nodes)} nodes."
)
nx.draw_networkx_nodes(graph, pos, node_size=700, node_color=keys, cmap=plt.cm.Greens)
else:
nx.draw_networkx_nodes(graph, pos, node_size=700)
col = lambda sgn: pos_color if sgn > 0 else neg_color
for edge in graph.edges:
weight = graph.get_edge_data(*edge)["weight"]
sgn = np.sign(weight)
size = abs(weight)
nx.draw_networkx_edges(graph,
pos,
edgelist=[edge],
width=scale * size,
edge_color=col(sgn),
alpha=0.5)
nx.draw_networkx_labels(graph, pos, font_size=20)
plt.axis("off")
plt.show()
"""Define the graph for MaxCut via an adjacency matrix."""
nodes = 6 # Vary the number of nodes here
matrix = random_graph(n=nodes, edge_prob=0.5, seed=2)
print("The adjacency matrix is:")
print(matrix)
"""Convert the adjacency matrix to a (weighted) graph and visualize it."""
graph = nx.from_numpy_array(matrix, parallel_edges=False)
draw_weighted(graph)
"""TODO: Put a list of 1s and 0s to assign vertex sets and see
what the value of your cut is.
"""
cut = np.array() ### <-- Your code here!
print("The value of this cut is:", max_cut_value(cut, matrix))
"""Visualize the cut by coloring nodes in distinct vertex sets different colors."""
draw_weighted(graph, cut=[0, 0, 0, 1, 1, 1])
"""Pauli operators from matrix."""
op, shift = get_max_cut_qubitops(matrix)
"""Inspect the Pauli operators."""
print("Edge set of the graph:")
for edge in graph.edges:
print("Weight:", graph.get_edge_data(*edge)["weight"], "Edge:", edge)
print("\nWeighted Pauli operators.")
for pauli in op.paulis:
print(2 * np.real(pauli[0]), "*", pauli[1].to_label()[::-1])
"""Make the QAOA instance."""
qaoa = QAOA(op, POWELL(), p=1)
"""See the settings of the QAOA object."""
print(qaoa.print_settings())
"""Inspect the circuits."""
backend = qiskit.BasicAer.get_backend("qasm_simulator")
circs = qaoa.construct_circuit([1, 2], backend=backend)
print(f"There are {len(circs)} circuits.")
print(circs[0])
"""Set the number of points N to define the grid. Larger N ==> longer runtime."""
N = 10
gammas = np.linspace(-np.pi, np.pi, N)
betas = np.linspace(-np.pi, np.pi, N)
"""Minor hacks for the QAOA instance to make the grid search possible.
Run this cell without too much thought -- this is necessary because the way Aqua is set up.
"""
quantum_instance = qiskit.aqua.QuantumInstance(backend=qiskit.BasicAer.get_backend("qasm_simulator"))
qaoa._quantum_instance = quantum_instance
qaoa._use_simulator_operator_mode = True
"""Do the grid search and display the progress."""
import progressbar
bar = progressbar.ProgressBar(maxval=N**2)
costs = np.zeros((len(gammas), len(betas)), dtype=float)
bar.start()
for (ii, gamma) in enumerate(gammas):
for (jj, beta) in enumerate(betas):
costs[ii][jj] = qaoa._energy_evaluation(np.array([gamma, beta]))
bar.update(N * ii + jj)
bar.finish()
"""Visualize the landscape."""
plt.figure(figsize=(7, 7));
plt.imshow(costs, origin=(0, 0));
plt.xlabel("Gammas")
plt.ylabel("Betas")
plt.colorbar();
"""Your code here!"""
"""Write code to answer the above question here."""
print("Min cost =", np.min(costs)) # Your code here!
"""Get a quantum instance and run the algorithm."""
qaoa._optimizer = POWELL()
result = qaoa.run(quantum_instance)
"""View the optimal cost."""
qaoa.get_optimal_cost()
"""Get the circuit with optimal parameters."""
circ = qaoa.get_optimal_circuit()
qreg = circ.qregs[0]
creg = qiskit.ClassicalRegister(6)
circ.add_register(creg)
circ.measure(qreg, creg)
print(circ)
"""Execute the circuit to sample from it."""
job = qiskit.execute(circ, backend=backend, shots=100000)
res = job.result()
counts = res.get_counts()
"""Visualize the statistics."""
qiskit.visualization.plot_histogram(counts, figsize=(17, 6))
"""Get the top sampled bit strings."""
import operator
ntop = 10
top_cuts = sorted(counts, key=operator.itemgetter(1))
print(f"Top {ntop} sampled cuts.")
for cut in top_cuts[:ntop]:
print(cut[::-1])
"""Select a sampled cut and see its value."""
cut = np.array() ### <-- Your answer here!
print("The value of this cut is:", max_cut_value(cut, matrix))
"""Brute force search for the maximum cut."""
import itertools
high = -np.inf
conf = np.zeros(nodes)
cuts = itertools.product(*[[0, 1]] * nodes)
for cut in cuts:
cur = max_cut_value(np.array(cut), matrix)
if cur > high:
conf = np.array(cut)
high = cur
print("Value of maximum cut:", high)
print("Optimal cut:", conf)
"""Visualize the graph to see the maximum cut."""
draw_weighted(graph, cut=conf)
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
"""Imports for the notebook."""
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
import qiskit
"""Defining circuits with parameters."""
# Get a circuit and registers
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
# Add gates with particular parameters
circ.h(qreg)
circ.rx(0.2, qreg[0])
circ.cx(qreg[0], qreg[1])
circ.ry(0.1, qreg[1])
# Visualize the circuit
print(circ)
def circuit(alpha1: float, alpha2: float):
"""Returns the circuit above with the input parameters."""
### Your code here!
# Get a circuit and registers
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
# Add gates with particular parameters
circ.h(qreg)
circ.rx(alpha1, qreg[0])
circ.cx(qreg[0], qreg[1])
circ.ry(alpha2, qreg[1])
return (circ, qreg, creg)
"""Estimating a one qubit expectation value."""
qreg = qiskit.QuantumRegister(1)
creg = qiskit.ClassicalRegister(1)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
### Your code here!
shots = 100000
circ.measure(qreg, creg)
print(circ)
backend = qiskit.BasicAer.get_backend("qasm_simulator")
job = qiskit.execute(circ, backend, shots=shots)
counts = job.result().get_counts()
expec_value = (counts.get("0") - counts.get("1")) / shots
print("Expectation value =", expec_value)
"""Estimating a one qubit expectation value."""
qreg = qiskit.QuantumRegister(1)
creg = qiskit.ClassicalRegister(1)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.x(qreg)
circ.h(qreg)
### Your code here!
shots = 10000
circ.h(qreg)
circ.measure(qreg, creg)
print(circ)
backend = qiskit.BasicAer.get_backend("qasm_simulator")
job = qiskit.execute(circ, backend, shots=shots)
counts = job.result().get_counts()
if "0" in counts.keys():
zero = counts.get("0")
else:
zero = 0
expec_value = (zero - counts.get("1")) / shots
print("Expectation value =", expec_value)
"""Estimating a two qubit expectation value."""
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg[1])
### Your code here!
shots = 10000
circ.h(qreg[1])
circ.measure(qreg, creg)
print(circ)
backend = qiskit.BasicAer.get_backend("qasm_simulator")
job = qiskit.execute(circ, backend, shots=shots)
counts = job.result().get_counts()
# Note: Only 00 will be in the counts, so the line below will throw an error.
# expec_value = (counts.get("00") - counts.get("01") - counts.get("10") + counts.get("11")) / shots
expec_value = counts.get("00") / shots
print("Expectation value =", expec_value)
"""Helper function to evaluate the expectation of any valid Pauli string."""
def expectation_circuit(circuit: qiskit.QuantumCircuit, pauli_string: str) -> qiskit.QuantumCircuit:
"""Returns a circuit to compute expectation of the Pauli string in the
state prepared by the input circuit.
Args:
circuit: Prepares the state |\psi> from |0>.
pauli_string: String (tensor product) of Paulis to evaluate
an expectation of. The length of pauli_string
must be equal to the total number of qubits in
the circuit. (Use identities for no operator!)
"""
if len(circuit.qregs) != 1:
raise ValueError("Circuit should have only one quantum register.")
if len(circuit.cregs) != 1:
print("# cregs =", len(circuit.cregs))
raise ValueError("Circuit should have only one classical register.")
### Your code here!
qreg = circuit.qregs[0]
creg = circuit.cregs[0]
nqubits = len(qreg)
pauli_string = pauli_string.upper().strip()
if len(pauli_string) != nqubits:
raise ValueError(
f"Circuit has {nqubits} qubits but pauli_string has {len(pauli_string)} operators."
)
for (qubit, pauli) in enumerate(pauli_string):
if pauli == "I":
continue
elif pauli == "X":
circuit.h(qreg[qubit])
circuit.measure(qreg[qubit], creg[qubit])
elif pauli == "Y":
circuit.s(qreg[qubit])
circuit.h(qreg[qubit])
circuit.measure(qreg[qubit], creg[qubit])
elif pauli == "Z":
circuit.measure(qreg[qubit], creg[qubit])
else:
raise ValueError(f"{pauli} is an invalid Pauli string key. Should be I, X, Y, or Z.")
return circuit
"""Test your function here."""
circ, qreg, creg = circuit(np.pi / 2, np.pi / 4)
print("Bare circuit:")
print(circ)
### Your code here!
print("\n'Expectation circuit:'")
print(expectation_circuit(circ, "XY"))
"""Function to execute the circuit and do the postprocessing."""
def run_and_process(circuit: qiskit.QuantumCircuit, shots: int = 10000) -> float:
"""Runs an 'expectation circuit' and returns the expectation value of the
measured Pauli string.
Args:
circuit: Circuit to execute.
shots: Number of circuit executions.
"""
### Your code here!
# Execute the circuit
backend = qiskit.BasicAer.get_backend("qasm_simulator")
job = qiskit.execute(circuit, backend, shots=shots)
counts = job.result().get_counts()
# Do the postprocessing
val = 0.0
for bitstring, count in counts.items():
sign = (-1) ** bitstring.count("0")
val += sign * count
return val / shots
"""Define your function here!"""
def expectation(circuit: qiskit.QuantumCircuit, pauli_string: str, shots: int = 10000) -> float:
"""Returns the expectation value of the pauli string in the state prepared by the circuit."""
### Your code here!
to_run = expectation_circuit(circuit, pauli_string)
return run_and_process(to_run, shots)
"""Test your function here."""
### Your code here!
circ, qreg, creg = circuit(0, 0)
print(circ)
expectation(circ, "IX")
"""Compute the expectation of a Hamiltonian."""
# Provided circuit
qreg = qiskit.QuantumRegister(3)
creg = qiskit.ClassicalRegister(3)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
circ.rx(np.pi / 4, qreg[0])
circ.cz(qreg[0], qreg[1])
circ.cz(qreg[1], qreg[2])
print(circ)
weights = (0.5, -0.3, 1.2)
paulis = ("IZZ", "ZZI", "ZIZ")
### Your code here
val = 0.0
for w, p in zip(weights, paulis):
val += w * expectation(circ, p)
print("<H> =", val)
"""Function to compute the cost of any Hamiltonian in the state prepared by the circuit."""
def cost(circuit, weights, paulis):
"""Returns <psi|H|psi> where |psi> is prepared by the circuit
and the weights and paulis define a Hamiltonian H.
Args:
circuit: Circuit which prepares a state.
weights: List of floats which are the coeffs/weights of each Pauli string.
paulis: List of strings which specify the Paulis.
"""
if len(weights) != len(paulis):
raise ValueError("Args weights and paulis must have the same length.")
### Your code here!
val = 0.0
for coeff, pauli in zip(weights, paulis):
val += coeff * expectation(circuit, pauli, shots=10000)
return val
"""Evaluate your cost here!"""
### Your code here!
print("Cost =", cost(circ, weights, paulis))
"""Plot a cost landscape."""
def oneq_circ(param):
qreg = qiskit.QuantumRegister(1)
creg = qiskit.ClassicalRegister(1)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.rx(param, qreg)
return circ
weights = (1.0,)
paulis = ("Z",)
pvals = np.linspace(-np.pi, np.pi, 100)
cvals = []
### Your code here!
for pval in pvals:
cvals.append(cost(oneq_circ(pval), weights, paulis))
plt.figure(figsize=(17, 6))
plt.plot(pvals, cvals, "--o", linewidth=3)
plt.grid()
plt.ylabel("<H>")
plt.xlabel(r"$\alpha$")
plt.show()
"""Get a parameterized circuit."""
def circuit(params):
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
circ.cx(qreg[0], qreg[1])
circ.rx(params[0], qreg[0])
circ.ry(params[1], qreg[1])
circ.cz(qreg[0], qreg[1])
circ.s(qreg[0])
circ.t(qreg[1])
return circ
"""Visualize the circuit."""
print(circuit([1, 2]))
"""Hamiltonian cost to minimize."""
weights = (1.2, -0.2)
paulis = ("IZ", "ZX")
"""Define a cost/objective function."""
def obj(params):
"""Returns the cost for the given parameters."""
### Your code here
circ = circuit(params)
val = cost(circ, weights, paulis)
print("Current cost:", val, end="\r")
return val
"""Test your function on this set of parameters."""
obj([0, 0])
"""Run an optimization algorithm to return the lowest cost and best parameters."""
result = minimize(obj, x0=[0, 0], method="COBYLA")
"""See the optimization results."""
print("Lowest cost function value found:", result.fun)
print("Best parameters:", result.x)
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
"""Imports for the notebook."""
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
import qiskit
"""Defining circuits with parameters."""
# Get a circuit and registers
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
# Add gates with particular parameters
circ.h(qreg)
circ.rx(0.2, qreg[0])
circ.cx(qreg[0], qreg[1])
circ.ry(0.1, qreg[1])
# Visualize the circuit
print(circ)
def circuit(alpha1: float, alpha2: float):
"""Returns the circuit above with the input parameters."""
### Your code here!
"""Estimating a one qubit expectation value."""
qreg = qiskit.QuantumRegister(1)
creg = qiskit.ClassicalRegister(1)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
### Your code here!
"""Estimating a one qubit expectation value."""
qreg = qiskit.QuantumRegister(1)
creg = qiskit.ClassicalRegister(1)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.x(qreg)
circ.h(qreg)
### Your code here!
"""Estimating a two qubit expectation value."""
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg[1])
### Your code here!
"""Helper function to evaluate the expectation of any valid Pauli string."""
def expectation_circuit(circuit: qiskit.QuantumCircuit, pauli_string: str) -> qiskit.QuantumCircuit:
"""Returns a circuit to compute expectation of the Pauli string in the
state prepared by the input circuit.
Args:
circuit: Prepares the state |\psi> from |0>.
pauli_string: String (tensor product) of Paulis to evaluate
an expectation of. The length of pauli_string
must be equal to the total number of qubits in
the circuit. (Use identities for no operator!)
"""
if len(circuit.qregs) != 1:
raise ValueError("Circuit should have only one quantum register.")
if len(circuit.cregs) != 1:
print("# cregs =", len(circuit.cregs))
raise ValueError("Circuit should have only one classical register.")
### Your code here!
"""Test your function here."""
circ, qreg, creg = circuit(np.pi / 2, np.pi / 4)
print("Bare circuit:")
print(circ)
### Your code here!
"""Function to execute the circuit and do the postprocessing."""
def run_and_process(circuit: qiskit.QuantumCircuit, shots: int = 10000) -> float:
"""Runs an 'expectation circuit' and returns the expectation value of the
measured Pauli string.
Args:
circuit: Circuit to execute.
shots: Number of circuit executions.
"""
### Your code here!
"""Define your function here!"""
def expectation(circuit: qiskit.QuantumCircuit, pauli_string: str, shots: int = 10000) -> float:
"""Returns the expectation value of the pauli string in the state prepared by the circuit."""
### Your code here!
"""Test your function here."""
### Your code here!
"""Compute the expectation of a Hamiltonian."""
# Provided circuit
qreg = qiskit.QuantumRegister(3)
creg = qiskit.ClassicalRegister(3)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
circ.rx(np.pi / 4, qreg[0])
circ.cz(qreg[0], qreg[1])
circ.cz(qreg[1], qreg[2])
print(circ)
weights = (0.5, -0.3, 1.2)
paulis = ("IZZ", "ZZI", "ZIZ")
### Your code here
"""Function to compute the cost of any Hamiltonian in the state prepared by the circuit."""
def cost(circuit, weights, paulis):
"""Returns <psi|H|psi> where |psi> is prepared by the circuit
and the weights and paulis define a Hamiltonian H.
Args:
circuit: Circuit which prepares a state.
weights: List of floats which are the coeffs/weights of each Pauli string.
paulis: List of strings which specify the Paulis.
"""
if len(weights) != len(paulis):
raise ValueError("Args weights and paulis must have the same length.")
### Your code here!
"""Evaluate your cost here!"""
### Your code here!
"""Plot a cost landscape."""
def oneq_circ(param):
qreg = qiskit.QuantumRegister(1)
creg = qiskit.ClassicalRegister(1)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.rx(param, qreg)
return circ
weights = (1.0,)
paulis = ("Z",)
pvals = np.linspace(-np.pi, np.pi, 100)
cvals = []
### Your code here!
"""Get a parameterized circuit."""
def circuit(params):
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
circ.cx(qreg[0], qreg[1])
circ.rx(params[0], qreg[0])
circ.ry(params[1], qreg[1])
circ.cz(qreg[0], qreg[1])
circ.s(qreg[0])
circ.t(qreg[1])
return circ
"""Visualize the circuit."""
print(circuit([1, 2]))
"""Hamiltonian cost to minimize."""
weights = (1.2, -0.2)
paulis = ("IZ", "ZX")
"""Define a cost/objective function."""
def obj(params):
"""Returns the cost for the given parameters."""
### Your code here
"""Test your function on this set of parameters."""
obj([0, 0])
"""Run an optimization algorithm to return the lowest cost and best parameters."""
result = minimize(obj, x0=[0, 0], method="COBYLA")
"""See the optimization results."""
print("Lowest cost function value found:", result.fun)
print("Best parameters:", result.x)
|
https://github.com/qiskit-community/Qiskit-Hackathon-at-World-of-QUANTUM
|
qiskit-community
|
# Importing all the parts we will need.
from typing import List, Optional
from qiskit import transpile, QuantumCircuit, QuantumRegister, ClassicalRegister, cAer
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit.visualization import plot_histogram
import warnings
warnings.filterwarnings("ignore")
import math
pi = math.pi
# Your code here: Implementation of the naive solution
# Your code here: Implementation of the good solution
# Your code here: Use code to show graphs
|
https://github.com/qiskit-community/Qiskit-Hackathon-at-World-of-QUANTUM
|
qiskit-community
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, assemble, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
#Apply the CNOT gate to the 00 state
#
qc=QuantumCircuit(2,2)
#
# FILL YOUR CODE IN HERE
#
qc.draw()
#Apply the CNOT gate to the 00 state
#
qc=QuantumCircuit(2,2)
#
# FILL YOUR CODE IN HERE
#
qc.draw()
#Apply the CNOT gate to the 00 state
#
qc=QuantumCircuit(2,2)
#
# FILL YOUR CODE IN HERE
#
# for i in range(2):
# qc.measure(i,i)
# backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
# counts = execute(qc, backend, shots = 1024).result().get_counts() # we run the simulation and get the counts
# plot_histogram(counts)
#Apply the CNOT gate to the 00 state
#
qc=QuantumCircuit(2,2)
#
# FILL YOUR CODE IN HERE
#
for i in range(2):
qc.measure(i,i)
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1024).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts)
|
https://github.com/qiskit-community/Qiskit-Hackathon-at-World-of-QUANTUM
|
qiskit-community
|
import numpy as np
import cmath
# Importing standard Qiskit libraries
from qiskit.quantum_info import Statevector, random_statevector
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, assemble, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.extensions import Initialize
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
qc = QuantumCircuit(1)
#
#
#
# FILL YOUR CODE IN HERE
#
#
#
#
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
qc = QuantumCircuit(1)
#
#
#
# FILL YOUR CODE IN HERE
#
#
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
qc=QuantumCircuit(1,1)
qc.u3(np.pi/4,np.pi/4,np.pi/4,0)
#
# FILL YOUR CODE IN HERE
#
#
#
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
Counts = execute(qc, backend, shots = 1024, seed_simulator=312).result().get_counts() # we run the simulation and get the counts
plot_histogram(Counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
psi = random_statevector(2, seed=11)
init_gate = Initialize(psi)
init_gate.label = "Random State"
## Measure the state in the x,y,z basis and make a guess for the state_vector psi
#Measure in all three different bases
#Put your answer here
#Try to remove any global phase in your answer
phi=
theta=
angles : [phi,theta]
|
https://github.com/qiskit-community/Qiskit-Hackathon-at-World-of-QUANTUM
|
qiskit-community
|
import numpy as np
from qiskit_textbook.tools import random_state
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit,QuantumRegister, ClassicalRegister, transpile, Aer, IBMQ, assemble, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit_textbook.tools import random_state
from qiskit.extensions import Initialize
from qiskit.providers.aer.noise import NoiseModel
import qiskit.quantum_info as qi
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical bits
crx = ClassicalRegister(1, name="crx") # in 2 different register
teleportation_circuit = QuantumCircuit(qr, crz, crx)
def psi_00(circuit, q1, q2):
# FILL YOUR CODE HERE
def Bell_measurement(circuit, q1, q2,crx, crz):
# FILL YOUR CODE HERE
def conditional_gates(circuit, q0, crx, crz):
# FILL YOUR CODE HERE
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") #Classical Registers
teleportation_circuit = QuantumCircuit(qr, crz, crx)
#STEP 1: Create the Bell state between q0 and q1
psi_00(teleportation_circuit, 0, 1 )
#STEP 2: Bell Measurement
teleportation_circuit.barrier()
Bell_measurement(teleportation_circuit, 1, 2, crx, crz)
#STEP 3: Conditional Gates
teleportation_circuit.barrier()
conditional_gates(teleportation_circuit,0, crx, crz)
teleportation_circuit.draw()
|
https://github.com/qiskit-community/Qiskit-Hackathon-at-World-of-QUANTUM
|
qiskit-community
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit.quantum_info import Statevector
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
## X-gate
# FILL IN YOUR CODE HERE
# Keep theta<=np.pi
#
#
#
#
#
## Z-gate
# FILL IN YOUR CODE HERE
#
#
#
#
#
## Y-gate
# FILL IN YOUR CODE HERE
#
#
#
#
## Hadamard
# FILL IN YOUR CODE HERE
#
#
#
#
#
## Which rotation corresponds to the gate set H-Y-S-T ?
#Circuit:
qc=QuantumCircuit(1)
qc.h(0)
qc.y(0)
qc.s(0)
qc.t(0)
##FILL IN YOUR ANSWER HERE
#
#
#
#
#
#Check the result with the u3 rotation gate (arbitrary single qubit rotations)
qc2=QuantumCircuit(1)
qc2.u3(theta,phi,lam,0)
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2024 Qiskit on IQM developers
#
# 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.
"""A simple extension of the QuantumCircuit class to allow the MOVE
gate to be applied with a .move(qubit, resonator) shortcut."""
from qiskit import QuantumCircuit
from iqm.qiskit_iqm.move_gate import MoveGate
class IQMCircuit(QuantumCircuit):
"""Extends the QuantumCircuit class, adding a shortcut for applying the MOVE gate."""
def move(self, qubit: int, resonator: int):
"""Applies the MOVE gate to the circuit.
Note: at this point the circuit layout is only guaranteed to work if the order
of the qubit and the resonator is correct (qubit first, resonator second).
Args:
qubit: the logical index of the qubit
resonator: the logical index of the resonator
"""
self.append(MoveGate(), [qubit, resonator])
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2024 Qiskit on IQM developers
#
# 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.
"""A layout algorithm that generates an initial layout for a quantum circuit that is
valid on the quantum architecture specification of the given IQM backend."""
from qiskit import QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler import PassManager, TranspilerError
from qiskit.transpiler.passes import TrivialLayout
from iqm.qiskit_iqm.iqm_provider import IQMBackend
class IQMMoveLayout(TrivialLayout):
r"""Creates a qubit layout that is valid on the quantum architecture specification of the
given IQM backend with regard to the move gate. In more detail, assumes that the move
operations in the quantum architecture define which physical qubit is the resonator and
which is a move qubit, and shuffles the logical indices of the circuit so that they match
the requirements.
This is required because Qiskit's basic layout algorithm assumes each connection between
two qubits has the same gates defined.
Note: This simple version of the mapper only works reliably with a single move qubit
and resonator, and only if the circuit contains at least one move gate."""
def __init__(self, backend: IQMBackend):
super().__init__(backend.target)
self._backend = backend
def run(self, dag):
"""Creates the qubit layout for the given quantum circuit.
Args:
dag (DAGCircuit): DAG to find layout for.
Raises:
TranspilerError: if dag wider than the target backend or if a valid mapping could not be found
"""
# Run TrivialLayout to get the initial 1-to-1 mapping
super().run(dag)
changes = self._determine_required_changes(dag)
if len(changes) < 1:
# No need to shuffle any qubits
return
layout = self.get_initial_layout()
for src, dst in changes:
layout.swap(src, dst)
self.property_set['layout'] = layout
def get_initial_layout(self):
"""Returns the initial layout generated by the algorithm.
Returns:
the initial layout
"""
return self.property_set['layout']
def _determine_required_changes(self, dag: DAGCircuit) -> list[tuple[int, int]]:
"""Scans the operations in the given circuit and determines what qubits
need to be switched so that the operations are valid for the specified quantum architecture.
Args:
dag - the circuit to check
Returns:
the list of required changes as tuples of logical indices that should be switched;
empty list if no changes are required.
"""
reqs = self._calculate_requirements(dag)
types = self._get_qubit_types()
changes: list[tuple[int, int]] = []
for index, qubit_type in reqs.items():
if index not in types or qubit_type != types[index]:
# Need to change qubit at index to qubit_type
matching_qubit = next((i for i, t in types.items() if t == qubit_type), None)
if matching_qubit is None:
raise TranspilerError(f"Cannot find a '{qubit_type}' from the quantum architecture.")
changes.append((index, matching_qubit))
return changes
def _get_qubit_types(self) -> dict[int, str]:
"""Determines the types of qubits in the quantum architecture.
Returns:
a dictionary mapping logical indices to qubit types for those
qubits where the type is relevant.
"""
backend = self._backend
qubit_types: dict[int, str] = {}
for instruction_name, loci in backend.architecture.operations.items():
if instruction_name == 'move':
for locus in loci:
[qubit, resonator] = [backend.qubit_name_to_index(q) for q in locus]
if qubit is not None:
qubit_types[qubit] = 'move_qubit'
if resonator is not None:
qubit_types[resonator] = 'resonator'
return qubit_types
@staticmethod
def _calculate_requirements(dag: DAGCircuit) -> dict[int, str]:
"""Calculates the requirements for each logical qubit in the circuit.
Args:
dag - the circuit to check
Returns:
A mapping of the logical qubit indices to the required type for that qubit.
"""
required_types: dict[int, str] = {}
def _require_type(qubit_index: int, required_type: str, instruction_name: str):
if qubit_index in required_types and required_types[qubit_index] != required_type:
raise TranspilerError(
f"""Invalid target '{qubit_index}' for the '{instruction_name}' operation,
qubit {qubit_index} would need to be {required_type} but it is already required to be
'{required_types[qubit_index]}'."""
)
required_types[qubit_index] = required_type
for node in dag.topological_op_nodes():
if node.name == 'move':
# The move operation requires that the first operand is the move qubit,
# and the second must be the resonator
(qubit, resonator) = node.qargs
_require_type(qubit.index, 'move_qubit', 'move')
_require_type(resonator.index, 'resonator', 'move')
return required_types
def generate_initial_layout(backend: IQMBackend, circuit: QuantumCircuit):
"""Generates the initial layout for the given circuit, when run against the given backend.
Args:
backend - the IQM backend to run against
circuit - the circuit for which a layout is to be generated
Returns:
a layout that remaps the qubits so that the move qubit and the resonator are using the correct
indices.
"""
layout_gen = IQMMoveLayout(backend)
pm = PassManager(layout_gen)
pm.run(circuit)
return layout_gen.get_initial_layout()
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2024 Qiskit on IQM developers
"""Naive transpilation for N-star architecture"""
from datetime import datetime
from typing import Optional, Union
from qiskit import QuantumCircuit, user_config
from qiskit.circuit import QuantumRegister, Qubit
from qiskit.dagcircuit import DAGCircuit, DAGOpNode
from qiskit.providers.models import BackendProperties
from qiskit.transpiler import CouplingMap, Layout, TranspileLayout
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.passmanager_config import PassManagerConfig
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.transpiler.target import Target
from .fake_backends.iqm_fake_backend import IQMFakeBackend
from .iqm_circuit import IQMCircuit
from .iqm_provider import IQMBackend
from .iqm_transpilation import IQMOptimizeSingleQubitGates
from .move_gate import MoveGate
class IQMNaiveResonatorMoving(TransformationPass):
"""WIP Naive transpilation pass for resonator moving
A naive transpiler pass for use with the Qiskit PassManager.
Although it requires a CouplingMap, Target, or Backend, it does not take this into account when adding MoveGates.
It assumes target connectivity graph is star shaped with a single resonator in the middle.
Which qubit is the resonator is represented with the resonator_register attribute.
The pass assumes that all single qubit and two-qubit gates are allowed.
The resonator is used to swap the qubit states for the two-qubit gates.
Additionally, it assumes that no single qubit gates are allowed on the resonator.
"""
def __init__(self, resonator_register: int, move_qubits: list[int], gate_set: list[str]):
"""WIP Naive transpilation pass for resonator moving
Args:
resonator_register (int): Which qubit/vertex index represents the resonator.
move_qubits (int): Which qubits (indices) can be moved into the resonator.
gate_set (list[str]): Which gates are allowed by the target backend.
"""
super().__init__()
self.resonator_register = resonator_register
self.current_resonator_state_location = resonator_register
self.move_qubits = move_qubits
self.gate_set = gate_set
def run(self, dag: DAGCircuit): # pylint: disable=too-many-branches
"""Run the IQMNaiveResonatorMoving pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the layout are not compatible with the DAG, or if the input gate set is incorrect.
"""
new_dag = dag.copy_empty_like()
# Check for sensible inputs
if len(dag.qregs) != 1 or dag.qregs.get("q", None) is None:
raise TranspilerError("IQMNaiveResonatorMoving runs on physical circuits only")
# Create a trivial layout
canonical_register = dag.qregs["q"]
trivial_layout = Layout.generate_trivial_layout(canonical_register)
current_layout = trivial_layout.copy()
for layer in dag.serial_layers():
subdag = layer["graph"]
if len(layer["partition"]) > 0:
qubits = layer["partition"][0]
else:
new_dag.compose(subdag)
continue # No qubit gate (e.g. Barrier)
if sum(subdag.count_ops().values()) > 1:
raise TranspilerError(
"""The DAGCircuit is not flattened enough for this transpiler pass.
It needs to be processed by another pass first."""
)
if list(subdag.count_ops().keys())[0] not in self.gate_set:
raise TranspilerError(
"""Encountered an incompatible gate in the DAGCircuit.
Please transpile to the correct gate set first."""
)
if len(qubits) == 1: # Single qubit gate
# Check if the qubit is not in the resonator
if self.current_resonator_state_location == qubits[0].index:
# Unload the current qubit from the resonator
new_dag.compose(self._move_resonator(qubits[0].index, canonical_register, current_layout))
new_dag.compose(subdag)
elif len(qubits) == 2: # Two qubit gate
physical_q0 = current_layout[qubits[0]]
physical_q1 = current_layout[qubits[1]]
if self.current_resonator_state_location in (physical_q0, physical_q1):
# The resonator is already loaded with the correct qubit data
pass
else:
swap_layer = DAGCircuit()
swap_layer.add_qreg(canonical_register)
if self.current_resonator_state_location != self.resonator_register:
# Unload the current qubit from the resonator
new_dag.compose(
self._move_resonator(
self.current_resonator_state_location, canonical_register, current_layout
)
)
# Load the new qubit to the resonator
if physical_q0 in self.move_qubits and physical_q1 in self.move_qubits:
# We can choose, let's select the better one by seeing which one is used most.
chosen_qubit = self._lookahead_first_qubit_used(dag, subdag)
new_qubit_to_load = current_layout[chosen_qubit]
elif physical_q0 in self.move_qubits:
new_qubit_to_load = physical_q0
elif physical_q1 in self.move_qubits:
new_qubit_to_load = physical_q1
else:
raise TranspilerError(
"""Two qubit gate between qubits that are not allowed to move.
Please route the circuit first."""
)
new_dag.compose(self._move_resonator(new_qubit_to_load, canonical_register, current_layout))
# Add the gate to the circuit
order = list(range(len(canonical_register)))
order[self.resonator_register] = self.current_resonator_state_location
order[self.current_resonator_state_location] = self.resonator_register
new_dag.compose(subdag, qubits=order)
else:
raise TranspilerError(
"""Three qubit gates are not allowed as input for this pass.
Please use a different transpiler pass to decompose first."""
)
new_dag.compose(
self._move_resonator(
self.current_resonator_state_location,
canonical_register,
current_layout,
)
)
return new_dag
def _lookahead_first_qubit_used(self, full_dag: DAGCircuit, current_layer: DAGCircuit) -> Qubit:
"""Lookahead function to see which qubit will be used first again for a CZ gate.
Args:
full_dag (DAGCircuit): The DAG representing the circuit
current_layer (DAGCircuit): The DAG representing the current operator
Returns:
Qubit: Which qubit is recommended to move because it will be used first.
"""
nodes = [n for n in current_layer.nodes() if isinstance(n, DAGOpNode)]
current_opnode = nodes[0]
qb1, qb2 = current_opnode.qargs
next_ops = [
n for n, _ in full_dag.bfs_successors(current_opnode) if isinstance(n, DAGOpNode) and n.name == "cz"
]
# Check which qubit will be used next first
for qb1_used, qb2_used in zip([qb1 in n.qargs for n in next_ops], [qb2 in n.qargs for n in next_ops]):
if qb1_used and not qb2_used:
return qb1
if qb2_used and not qb1_used:
return qb2
return qb1
def _move_resonator(self, qubit: int, canonical_register: QuantumRegister, current_layout: Layout):
"""Logic for creating the DAG for swapping a qubit in and out of the resonator.
Args:
qubit (int): The qubit to swap in or out. The returning DAG is empty if the qubit is the resonator.
canonical_register (QuantumRegister): The qubit register to initialize the DAG
current_layout (Layout): The current qubit layout to map the qubit index to a Qiskit Qubit object.
Returns:
DAGCircuit: A DAG storing the MoveGate logic to be added into the circuit by this TranspilerPass.
"""
swap_layer = DAGCircuit()
swap_layer.add_qreg(canonical_register)
if qubit != self.resonator_register:
swap_layer.apply_operation_back(
MoveGate(),
qargs=(current_layout[qubit], current_layout[self.resonator_register]),
cargs=(),
check=False,
)
if self.current_resonator_state_location == self.resonator_register:
# We just loaded the qubit into the register
self.current_resonator_state_location = qubit
else:
# We just unloaded the qubit from the register
self.current_resonator_state_location = self.resonator_register
return swap_layer
def _to_qubit_indices(backend: Union[IQMBackend, IQMFakeBackend], qubit_names: list[str]) -> list[int]:
indices = [backend.qubit_name_to_index(res) for res in qubit_names]
return [i for i in indices if i is not None]
def _qubit_to_index_without_resonator(
backend: Union[IQMBackend, IQMFakeBackend], resonator_registers: list[str], qb: str
) -> Optional[int]:
resonator_indices = _to_qubit_indices(backend, resonator_registers)
idx = backend.qubit_name_to_index(qb)
return (idx - sum(1 for r in resonator_indices if r < idx)) if idx is not None else None
def _generate_coupling_map_without_resonator(backend: Union[IQMBackend, IQMFakeBackend]) -> CouplingMap:
# Grab qubits from backend operations
allowed_ops = backend.architecture.operations
allowed_czs = allowed_ops["cz"]
allowed_moves = allowed_ops["move"]
iqm_registers = backend.architecture.qubits
resonator_registers = [r for r in iqm_registers if r.startswith("COMP_R")]
move_qubits = {r: [q for pair in allowed_moves for q in pair if r in pair and q != r] for r in resonator_registers}
edges = []
for qb1, qb2 in allowed_czs:
if qb1 in resonator_registers:
vs1 = move_qubits[qb1]
else:
vs1 = [qb1]
if qb2 in resonator_registers:
vs2 = move_qubits[qb2]
else:
vs2 = [qb2]
for v1 in vs1:
for v2 in vs2:
qb1_idx = _qubit_to_index_without_resonator(backend, resonator_registers, v1)
qb2_idx = _qubit_to_index_without_resonator(backend, resonator_registers, v2)
if qb1_idx is not None and qb2_idx is not None:
edges.append((qb1_idx, qb2_idx))
return CouplingMap(edges)
def build_IQM_star_pass_manager_config(
backend: Union[IQMBackend, IQMFakeBackend], circuit: QuantumCircuit
) -> PassManagerConfig:
"""Build configuration for IQM backend.
We need to pass precomputed values to be used in transpiler passes via backend_properties.
This function performs precomputation for the backend and packages the values to the config object."""
coupling_map = _generate_coupling_map_without_resonator(backend)
allowed_ops = backend.architecture.operations
allowed_moves = allowed_ops["move"]
iqm_registers = backend.architecture.qubits
classical_registers = [bit.index for bit in circuit.clbits]
resonator_registers = [r for r in iqm_registers if r.startswith("COMP_R")]
move_qubits = {r: [q for pair in allowed_moves for q in pair if r in pair and q != r] for r in resonator_registers}
qubit_registers = [q for q in iqm_registers if q not in resonator_registers]
qubit_indices = [backend.qubit_name_to_index(qb) for qb in qubit_registers]
bit_indices = [_qubit_to_index_without_resonator(backend, resonator_registers, qb) for qb in qubit_registers]
resonator_indices = [backend.qubit_name_to_index(r) for r in resonator_registers]
if len(resonator_indices) != 1:
raise NotImplementedError("Device must have exactly one resonator.")
if any(idx is None for idx in resonator_indices):
raise RuntimeError("Could not find index of a resonator.")
move_indices = _to_qubit_indices(backend, move_qubits[resonator_registers[0]])
extra_backend_properties = {
"resonator_indices": resonator_indices,
"move_indices": move_indices,
"qubit_indices": qubit_indices,
"bit_indices": bit_indices,
"classical_registers": classical_registers,
}
backend_properties = BackendProperties(
backend_name=backend.name,
backend_version="",
last_update_date=datetime.now(),
qubits=[],
gates=[],
general=[],
)
backend_properties._data.update(**extra_backend_properties)
return PassManagerConfig(
basis_gates=backend.operation_names,
backend_properties=backend_properties,
target=Target(num_qubits=len(qubit_indices)),
coupling_map=coupling_map,
)
def build_IQM_star_pass(pass_manager_config: PassManagerConfig) -> TransformationPass:
"""Build translate pass for IQM star architecture"""
backend_props = pass_manager_config.backend_properties.to_dict()
resonator_indices = backend_props.get("resonator_indices")
return IQMNaiveResonatorMoving(
resonator_indices[0],
backend_props.get("move_indices"),
pass_manager_config.basis_gates,
)
def transpile_to_IQM( # pylint: disable=too-many-arguments
circuit: QuantumCircuit,
backend: Union[IQMBackend, IQMFakeBackend],
optimize_single_qubits: bool = True,
ignore_barriers: bool = False,
remove_final_rzs: bool = False,
optimization_level: Optional[int] = None,
) -> QuantumCircuit:
"""Basic function for transpiling to IQM backends. Currently works with Deneb and Garnet
Args:
circuit (QuantumCircuit): The circuit to be transpiled without MOVE gates.
backend (IQMBackend | IQMFakeBackend): The target backend to compile to containing a single resonator.
optimize_single_qubits (bool): Whether to optimize single qubit gates away (default = True).
ignore_barriers (bool): Whether to ignore barriers when optimizing single qubit gates away (default = False).
remove_final_rzs (bool): Whether to remove the final Rz rotations (default = False).
optimization_level: How much optimization to perform on the circuits as per Qiskit transpiler.
Higher levels generate more optimized circuits,
at the expense of longer transpilation time.
* 0: no optimization
* 1: light optimization (default)
* 2: heavy optimization
* 3: even heavier optimization
Raises:
NotImplementedError: Thrown when the backend supports multiple resonators.
Returns:
QuantumCircuit: The transpiled circuit ready for running on the backend.
"""
passes = []
if optimize_single_qubits:
optimize_pass = IQMOptimizeSingleQubitGates(remove_final_rzs, ignore_barriers)
passes.append(optimize_pass)
if optimization_level is None:
config = user_config.get_config()
optimization_level = config.get("transpile_optimization_level", 1)
if "move" not in backend.architecture.operations.keys():
pass_manager = generate_preset_pass_manager(backend=backend, optimization_level=optimization_level)
simple_transpile = pass_manager.run(circuit)
if passes:
return PassManager(passes).run(simple_transpile)
return simple_transpile
pass_manager_config = build_IQM_star_pass_manager_config(backend, circuit)
move_pass = build_IQM_star_pass(pass_manager_config)
passes.append(move_pass)
backend_props = pass_manager_config.backend_properties.to_dict()
qubit_indices = backend_props.get("qubit_indices")
resonator_indices = backend_props.get("resonator_indices")
classical_registers = backend_props.get("classical_registers")
n_qubits = len(qubit_indices)
n_resonators = len(resonator_indices)
pass_manager = generate_preset_pass_manager(
optimization_level,
basis_gates=pass_manager_config.basis_gates,
coupling_map=pass_manager_config.coupling_map,
)
simple_transpile = pass_manager.run(circuit)
circuit_with_resonator = IQMCircuit(
n_qubits + n_resonators,
max(classical_registers) + 1 if len(classical_registers) > 0 else 0,
)
layout_dict = {
qb: i + sum(1 for r_i in resonator_indices if r_i <= i + n_resonators)
for qb, i in simple_transpile._layout.initial_layout._v2p.items()
}
layout_dict.update({Qubit(QuantumRegister(n_resonators, "resonator"), r_i): r_i for r_i in resonator_indices})
initial_layout = Layout(input_dict=layout_dict)
init_mapping = layout_dict
final_layout = None
if simple_transpile.layout.final_layout:
final_layout_dict = {
qb: i + sum(1 for r_i in resonator_indices if r_i <= i + n_resonators)
for qb, i in simple_transpile.layout.final_layout._v2p.items()
}
final_layout_dict.update(
{Qubit(QuantumRegister(n_resonators, "resonator"), r_i): r_i for r_i in resonator_indices}
)
final_layout = Layout(final_layout_dict)
new_layout = TranspileLayout(initial_layout, init_mapping, final_layout=final_layout)
circuit_with_resonator.append(
simple_transpile, qubit_indices, classical_registers if len(classical_registers) > 0 else None
)
circuit_with_resonator._layout = new_layout
circuit_with_resonator = circuit_with_resonator.decompose()
transpiled_circuit = PassManager(passes).run(circuit_with_resonator)
transpiled_circuit._layout = new_layout
return transpiled_circuit
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022 Qiskit on IQM developers
#
# 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.
"""Qiskit Backend Provider for IQM backends.
"""
from copy import copy
from importlib.metadata import PackageNotFoundError, version
from functools import reduce
from typing import Optional, Union
from uuid import UUID
import warnings
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers import JobStatus, JobV1, Options
from iqm.iqm_client import Circuit, HeraldingMode, Instruction, IQMClient
from iqm.iqm_client.util import to_json_dict
from iqm.qiskit_iqm.fake_backends import IQMFakeAdonis
from iqm.qiskit_iqm.iqm_backend import IQMBackendBase
from iqm.qiskit_iqm.iqm_job import IQMJob
from iqm.qiskit_iqm.qiskit_to_iqm import MeasurementKey
try:
__version__ = version('qiskit-iqm')
except PackageNotFoundError: # pragma: no cover
__version__ = 'unknown'
finally:
del version, PackageNotFoundError
class IQMBackend(IQMBackendBase):
"""Backend for executing quantum circuits on IQM quantum computers.
Args:
client: client instance for communicating with an IQM server
**kwargs: optional arguments to be passed to the parent Backend initializer
"""
def __init__(self, client: IQMClient, **kwargs):
architecture = client.get_quantum_architecture()
super().__init__(architecture, **kwargs)
self.client: IQMClient = client
self._max_circuits: Optional[int] = None
self.name = f'IQM{architecture.name}Backend'
@classmethod
def _default_options(cls) -> Options:
return Options(
shots=1024,
calibration_set_id=None,
max_circuit_duration_over_t2=None,
heralding_mode=HeraldingMode.NONE,
circuit_callback=None,
)
@property
def max_circuits(self) -> Optional[int]:
"""Maximum number of circuits that should be run in a single batch.
Currently there is no hard limit on the number of circuits that can be executed in a single batch/job.
However, some libraries like Qiskit Experiments use this property to split multi-circuit computational
tasks into multiple baches/jobs.
The default value is ``None``, meaning there is no limit. You can set it to a specific integer
value to force these libraries to execute at most that many circuits in a single batch.
"""
return self._max_circuits
@max_circuits.setter
def max_circuits(self, value: Optional[int]) -> None:
self._max_circuits = value
def run(self, run_input: Union[QuantumCircuit, list[QuantumCircuit]], **options) -> IQMJob:
if self.client is None:
raise RuntimeError('Session to IQM client has been closed.')
circuits = [run_input] if isinstance(run_input, QuantumCircuit) else run_input
if len(circuits) == 0:
raise ValueError('Empty list of circuits submitted for execution.')
unknown_options = set(options.keys()) - set(self.options.keys())
if unknown_options:
warnings.warn(f'Unknown backend option(s): {unknown_options}')
# merge given options with default options and get resulting values
merged_options = copy(self.options)
merged_options.update_options(**dict(options))
shots = merged_options['shots']
calibration_set_id = merged_options['calibration_set_id']
if calibration_set_id is not None and not isinstance(calibration_set_id, UUID):
calibration_set_id = UUID(calibration_set_id)
max_circuit_duration_over_t2 = merged_options['max_circuit_duration_over_t2']
heralding_mode = merged_options['heralding_mode']
circuit_callback = merged_options['circuit_callback']
if circuit_callback:
circuit_callback(circuits)
circuits_serialized: list[Circuit] = [self.serialize_circuit(circuit) for circuit in circuits]
used_indices: set[int] = reduce(
lambda qubits, circuit: qubits.union(set(int(q) for q in circuit.all_qubits())), circuits_serialized, set()
)
qubit_mapping = {str(idx): qb for idx, qb in self._idx_to_qb.items() if idx in used_indices}
job_id = self.client.submit_circuits(
circuits_serialized,
qubit_mapping=qubit_mapping,
calibration_set_id=calibration_set_id if calibration_set_id else None,
shots=shots,
max_circuit_duration_over_t2=max_circuit_duration_over_t2,
heralding_mode=heralding_mode,
)
job = IQMJob(self, str(job_id), shots=shots)
job.circuit_metadata = [c.metadata for c in circuits]
return job
def retrieve_job(self, job_id: str) -> IQMJob:
"""Create and return an IQMJob instance associated with this backend with given job id."""
return IQMJob(self, job_id)
def close_client(self):
"""Close IQMClient's session with the authentication server. Discard the client."""
if self.client is not None:
self.client.close_auth_session()
self.client = None
def serialize_circuit(self, circuit: QuantumCircuit) -> Circuit:
"""Serialize a quantum circuit into the IQM data transfer format.
Serializing is not strictly bound to the native gateset, i.e. some gates that are not explicitly mentioned in
the native gateset of the backend can still be serialized. For example, the native single qubit gate for IQM
backend is the 'r' gate, however 'x', 'rx', 'y' and 'ry' gates can also be serialized since they are just
particular cases of the 'r' gate. If the circuit was transpiled against a backend using Qiskit's transpiler
machinery, these gates are not supposed to be present. However, when constructing circuits manually and
submitting directly to the backend, it is sometimes more explicit and understandable to use these concrete
gates rather than 'r'. Serializing them explicitly makes it possible for the backend to accept such circuits.
Qiskit uses one measurement instruction per qubit (i.e. there is no measurement grouping concept). While
serializing we do not group any measurements together but rather associate a unique measurement key with each
measurement instruction, so that the results can later be reconstructed correctly (see :class:`MeasurementKey`
documentation for more details).
Args:
circuit: quantum circuit to serialize
Returns:
data transfer object representing the circuit
Raises:
ValueError: circuit contains an unsupported instruction or is not transpiled in general
"""
# pylint: disable=too-many-branches
if len(circuit.qregs) != 1 or len(circuit.qregs[0]) != self.num_qubits:
raise ValueError(
f"The circuit '{circuit.name}' does not contain a single quantum register of length {self.num_qubits}, "
f'which indicates that it has not been transpiled against the current backend.'
)
instructions = []
for instruction, qubits, clbits in circuit.data:
qubit_names = [str(circuit.find_bit(qubit).index) for qubit in qubits]
if instruction.name == 'r':
angle_t = float(instruction.params[0] / (2 * np.pi))
phase_t = float(instruction.params[1] / (2 * np.pi))
instructions.append(
Instruction(name='prx', qubits=qubit_names, args={'angle_t': angle_t, 'phase_t': phase_t})
)
elif instruction.name == 'x':
instructions.append(Instruction(name='prx', qubits=qubit_names, args={'angle_t': 0.5, 'phase_t': 0.0}))
elif instruction.name == 'rx':
angle_t = float(instruction.params[0] / (2 * np.pi))
instructions.append(
Instruction(name='prx', qubits=qubit_names, args={'angle_t': angle_t, 'phase_t': 0.0})
)
elif instruction.name == 'y':
instructions.append(Instruction(name='prx', qubits=qubit_names, args={'angle_t': 0.5, 'phase_t': 0.25}))
elif instruction.name == 'ry':
angle_t = float(instruction.params[0] / (2 * np.pi))
instructions.append(
Instruction(name='prx', qubits=qubit_names, args={'angle_t': angle_t, 'phase_t': 0.25})
)
elif instruction.name == 'cz':
instructions.append(Instruction(name='cz', qubits=qubit_names, args={}))
elif instruction.name == 'move':
instructions.append(Instruction(name='move', qubits=qubit_names, args={}))
elif instruction.name == 'barrier':
instructions.append(Instruction(name='barrier', qubits=qubit_names, args={}))
elif instruction.name == 'measure':
mk = MeasurementKey.from_clbit(clbits[0], circuit)
instructions.append(Instruction(name='measure', qubits=qubit_names, args={'key': str(mk)}))
elif instruction.name == 'id':
pass
else:
raise ValueError(
f"Instruction '{instruction.name}' in the circuit '{circuit.name}' is not natively supported. "
f'You need to transpile the circuit before execution.'
)
try:
metadata = to_json_dict(circuit.metadata)
except ValueError:
warnings.warn(
f'Metadata of circuit {circuit.name} was dropped because it could not be serialised to JSON.',
)
metadata = None
return Circuit(name=circuit.name, instructions=instructions, metadata=metadata)
class IQMFacadeBackend(IQMBackend):
"""Facade backend for mimicking the execution of quantum circuits on IQM quantum computers. Allows to submit a
circuit to the IQM server, and if the execution was successful, performs a simulation with a respective IQM noise
model locally, then returns the simulated results.
Args:
client: client instance for communicating with an IQM server
**kwargs: optional arguments to be passed to the parent Backend initializer
"""
def __init__(self, client: IQMClient, **kwargs):
self.fake_adonis = IQMFakeAdonis()
target_architecture = client.get_quantum_architecture()
if not self.fake_adonis.validate_compatible_architecture(target_architecture):
raise ValueError('Quantum architecture of the remote quantum computer does not match Adonis.')
super().__init__(client, **kwargs)
self.client = client
self.name = f'IQMFacade{target_architecture.name}Backend'
def _validate_no_empty_cregs(self, circuit):
"""Returns True if given circuit has no empty (unused) classical registers, False otherwise."""
cregs_utilization = dict.fromkeys(circuit.cregs, 0)
used_cregs = [circuit.find_bit(i.clbits[0]).registers[0][0] for i in circuit.data if len(i.clbits) > 0]
for creg in used_cregs:
cregs_utilization[creg] += 1
if 0 in cregs_utilization.values():
return False
return True
def run(self, run_input: Union[QuantumCircuit, list[QuantumCircuit]], **options) -> JobV1:
circuits = [run_input] if isinstance(run_input, QuantumCircuit) else run_input
circuits_validated_cregs: list[bool] = [self._validate_no_empty_cregs(circuit) for circuit in circuits]
if not all(circuits_validated_cregs):
raise ValueError(
'One or more circuits contain unused classical registers. This is not allowed for Facade simulation, '
'see user guide.'
)
iqm_backend_job = super().run(run_input, **options)
iqm_backend_job.result() # get and discard results
if iqm_backend_job.status() == JobStatus.ERROR:
raise RuntimeError('Remote execution did not succeed.')
return self.fake_adonis.run(run_input, **options)
class IQMProvider:
"""Provider for IQM backends.
Args:
url: URL of the IQM Cortex server
Keyword Args:
auth_server_url: URL of the user authentication server, if required by the IQM Cortex server.
Can also be set in the ``IQM_AUTH_SERVER`` environment variable.
username: Username, if required by the IQM Cortex server.
Can also be set in the ``IQM_AUTH_USERNAME`` environment variable.
password: Password, if required by the IQM Cortex server.
Can also be set in the ``IQM_AUTH_PASSWORD`` environment variable.
"""
def __init__(self, url: str, **user_auth_args): # contains keyword args auth_server_url, username, password
self.url = url
self.user_auth_args = user_auth_args
def get_backend(self, name=None) -> Union[IQMBackend, IQMFacadeBackend]:
"""An IQMBackend instance associated with this provider.
Args:
name: optional name of a custom facade backend
"""
client = IQMClient(self.url, client_signature=f'qiskit-iqm {__version__}', **self.user_auth_args)
if name == 'facade_adonis':
return IQMFacadeBackend(client)
return IQMBackend(client)
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2023 Qiskit on IQM developers
#
# 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.
"""Transpilation tool to optimize the decomposition of single-qubit gates tailored to IQM hardware."""
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary
from qiskit.circuit.library import RGate
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.passes import BasisTranslator, Optimize1qGatesDecomposition, RemoveBarriers
from qiskit.transpiler.passmanager import PassManager
class IQMOptimizeSingleQubitGates(TransformationPass):
r"""Optimize the decomposition of single-qubit gates for the IQM gate set.
This optimisation pass expects the circuit to be correctly layouted and translated to the IQM architecture
and raises an error otherwise.
The optimisation logic follows the steps:
1. Convert single-qubit gates to :math:`U` gates and combine all neighbouring :math:`U` gates.
2. Convert :math:`U` gates according to
:math:`U(\theta , \phi , \lambda) ~ RZ(\phi + \lambda) R(\theta, \pi / 2 - \lambda)`.
3. Commute `RZ` gates to the end of the circuit using the fact that `RZ` and `CZ` gates commute, and
:math:`R(\theta , \phi) RZ(\lambda) = RZ(\lambda) R(\theta, \phi - \lambda)`.
4. Drop `RZ` gates immediately before measurements, and otherwise replace them according to
:math:`RZ(\lambda) = R(\pi, \lambda / 2) R(- \pi, 0)`.
Args:
drop_final_rz: Drop terminal RZ gates even if there are no measurements following them (since they do not affect
the measurement results). Note that this will change the unitary propagator of the circuit.
ignore_barriers (bool): Removes the barriers from the circuit before optimization (default = False).
"""
def __init__(self, drop_final_rz: bool = False, ignore_barriers: bool = False):
super().__init__()
self._basis = ['r', 'cz']
self._intermediate_basis = ['u', 'cz']
self._drop_final_rz = drop_final_rz
self._ignore_barriers = ignore_barriers
def run(self, dag: DAGCircuit) -> DAGCircuit:
self._validate_ops(dag)
# accumulated RZ angles for each qubit, from the beginning of the circuit to the current gate
rz_angles: list[float] = [0] * dag.num_qubits()
if self._ignore_barriers:
dag = RemoveBarriers().run(dag)
# convert all gates in the circuit to U and CZ gates
dag = BasisTranslator(SessionEquivalenceLibrary, self._intermediate_basis).run(dag)
# combine all sequential U gates into one
dag = Optimize1qGatesDecomposition(self._intermediate_basis).run(dag)
for node in dag.topological_op_nodes():
if node.name == 'u':
qubit_index = dag.find_bit(node.qargs[0])[0]
dag.substitute_node(
node, RGate(node.op.params[0], np.pi / 2 - node.op.params[2] - rz_angles[qubit_index])
)
phase = node.op.params[1] + node.op.params[2]
dag.global_phase += phase / 2
rz_angles[qubit_index] += phase
elif node.name == 'measure':
for qubit in node.qargs:
rz_angles[dag.find_bit(qubit)[0]] = 0
if not self._drop_final_rz:
for qubit_index, rz_angle in enumerate(rz_angles):
if rz_angle != 0:
qubit = dag.qubits[qubit_index]
dag.apply_operation_back(RGate(-np.pi, 0), qargs=(qubit,))
dag.apply_operation_back(RGate(np.pi, rz_angles[qubit_index] / 2), qargs=(qubit,))
return dag
def _validate_ops(self, dag: DAGCircuit):
for node in dag.op_nodes():
if node.name not in self._basis + ['measure', 'barrier']:
raise ValueError(
f"""Invalid operation '{node.name}' found in IQMOptimize1QbDecomposition pass,
expected operations {self._basis + ['measure', 'barrier']}"""
)
def optimize_single_qubit_gates(
circuit: QuantumCircuit, drop_final_rz: bool = True, ignore_barriers: bool = False
) -> QuantumCircuit:
"""Optimize number of single-qubit gates in a transpiled circuit exploiting the IQM specific gate set.
Args:
circuit: quantum circuit to optimise
drop_final_rz: Drop terminal RZ gates even if there are no measurements following them (since they do not affect
the measurement results). Note that this will change the unitary propagator of the circuit.
ignore_barriers (bool): Removes barriers from the circuit if they exist (default = False) before optimization.
Returns:
optimised circuit
"""
return PassManager(IQMOptimizeSingleQubitGates(drop_final_rz, ignore_barriers)).run(circuit)
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022 Qiskit on IQM developers
#
# 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.
"""Conversion tools from Qiskit to IQM representation.
"""
from __future__ import annotations
from dataclasses import dataclass
import re
from qiskit import QuantumCircuit as QiskitQuantumCircuit
from qiskit.circuit import Clbit
class InstructionNotSupportedError(RuntimeError):
"""Raised when a given instruction is not supported by the IQM server."""
@dataclass(frozen=True)
class MeasurementKey:
"""Unique key associated with a measurement instruction.
Qiskit stores the results of quantum measurements in classical registers consisting of bits.
The circuit execution results are presented as bitstrings of a certain structure so that the classical
register and the index within that register for each bit is implied from its position in the bitstring.
For example, if you have two classical registers in the circuit with lengths 3 and 2, then the
measurement results will look like '01 101' if the classical register of length 3 was added to
the circuit first, and '101 01' otherwise. If a bit in a classical register is not used in any
measurement operation it will still show up in the results with the default value of '0'.
To be able to handle measurement results in a Qiskit-friendly way, we need to keep around some
information about how the circuit was constructed. This can, for example, be achieved by keeping
around the original Qiskit quantum circuit and using it when constructing the results in
:class:`.IQMJob`. This should be done so that the circuit is saved on the server side and not in
``IQMJob``, since otherwise users will not be able to retrieve results from a detached Python
environment solely based on the job id. Another option is to use measurement key strings to
store the required info. Qiskit does not use measurement keys, so we are free to use them
internally in the communication with the IQM server, and can encode the necessary information in
them.
This class encapsulates the necessary info, and provides methods to transform between this
representation and the measurement key string representation.
Args:
creg_name: name of the classical register
creg_len: number of bits in the classical register
creg_idx: Index of the classical register in the circuit. Determines the order in which this register was added
to the circuit relative to the others.
clbit_idx: index of the classical bit within the classical register
"""
creg_name: str
creg_len: int
creg_idx: int
clbit_idx: int
def __str__(self):
return f'{self.creg_name}_{self.creg_len}_{self.creg_idx}_{self.clbit_idx}'
@classmethod
def from_string(cls, string: str) -> MeasurementKey:
"""Create a MeasurementKey from its string representation."""
match = re.match(r'^(.*)_(\d+)_(\d+)_(\d+)$', string)
if match is None:
raise ValueError('Invalid measurement key string representation.')
return cls(match.group(1), int(match.group(2)), int(match.group(3)), int(match.group(4)))
@classmethod
def from_clbit(cls, clbit: Clbit, circuit: QiskitQuantumCircuit) -> MeasurementKey:
"""Create a MeasurementKey for a classical bit in a quantum circuit."""
bitloc = circuit.find_bit(clbit)
creg = bitloc.registers[0][0]
creg_idx = circuit.cregs.index(creg)
clbit_idx = bitloc.registers[0][1]
return cls(creg.name, len(creg), creg_idx, clbit_idx)
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2023 Qiskit on IQM developers
#
# 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.
"""This file is an example of using Qiskit on IQM to execute a simple but non-trivial quantum circuit on an IQM quantum
computer. See the Qiskit on IQM user guide for instructions:
https://iqm-finland.github.io/qiskit-on-iqm/user_guide.html
"""
import argparse
from qiskit import QuantumCircuit, execute
from iqm.qiskit_iqm.iqm_provider import IQMProvider
def bell_measure(server_url: str) -> dict[str, int]:
"""Execute a circuit that prepares and measures a Bell state.
Args:
server_url: URL of the IQM Cortex server used for execution
Returns:
a mapping of bitstrings representing qubit measurement results to counts for each result
"""
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()
return execute(circuit, IQMProvider(server_url).get_backend(), shots=1000).result().get_counts()
if __name__ == '__main__':
argparser = argparse.ArgumentParser()
argparser.add_argument(
'--cortex_server_url',
help='URL of the IQM Cortex server',
default='https://demo.qc.iqm.fi/cocos',
)
print(bell_measure(argparser.parse_args().cortex_server_url))
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2023 Qiskit on IQM developers
#
# 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.
"""This file is an example of using Qiskit on IQM to execute a simple but non-trivial quantum circuit on an IQM quantum
computer. See the Qiskit on IQM user guide for instructions:
https://iqm-finland.github.io/qiskit-on-iqm/user_guide.html
"""
import argparse
from qiskit import QuantumCircuit, execute
from iqm.qiskit_iqm import transpile_to_IQM
from iqm.qiskit_iqm.iqm_provider import IQMProvider
def transpile_example(server_url: str) -> tuple[QuantumCircuit, dict[str, int]]:
"""Execute a circuit transpiled using transpile_to_IQM function.
Args:
server_url: URL of the IQM Cortex server used for execution
Returns:
transpiled circuit, a mapping of bitstrings representing qubit measurement results to counts for each result
"""
backend = IQMProvider(server_url).get_backend()
num_qubits = min(backend.num_qubits, 5) # use 5 qubits if available, otherwise maximum number of available qubits
circuit = QuantumCircuit(num_qubits)
circuit.h(0)
for i in range(1, num_qubits):
circuit.cx(0, i)
circuit.measure_all()
transpiled_circuit = transpile_to_IQM(circuit, backend)
counts = execute(transpiled_circuit, backend, shots=1000).result().get_counts()
return transpiled_circuit, counts
if __name__ == '__main__':
argparser = argparse.ArgumentParser()
argparser.add_argument(
'--url',
help='URL of the IQM service',
default='https://cocos.resonance.meetiqm.com/deneb',
)
circuit_transpiled, results = transpile_example(argparser.parse_args().url)
print(circuit_transpiled)
print(results)
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022-2023 Qiskit on IQM developers
#
# 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.
"""
Error profile and fake backend base class for simulating IQM quantum computers.
"""
from __future__ import annotations
from copy import deepcopy
from dataclasses import dataclass
from itertools import permutations
from typing import Any, Optional, Union
from qiskit import QuantumCircuit
from qiskit.providers import JobV1, Options
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel
from qiskit_aer.noise.errors import depolarizing_error, thermal_relaxation_error
from iqm.iqm_client import QuantumArchitectureSpecification
from iqm.qiskit_iqm.iqm_backend import IQM_TO_QISKIT_GATE_NAME, IQMBackendBase
# pylint: disable=too-many-instance-attributes
@dataclass
class IQMErrorProfile:
r"""Properties of an IQM QPU specimen, used for constructing an error model.
All the attributes of this class refer to the qubits of the QPU using their physical names.
Args:
t1s: maps qubits to their :math:`T_1` times (in ns)
t2s: maps qubits to the :math:`T_2` times (in ns)
single_qubit_gate_depolarizing_error_parameters: Depolarizing error parameters for single-qubit gates.
Maps single-qubit gate names to a mapping of qubits (on which the gate acts) to a depolarizing error.
The error, used in a one-qubit depolarizing channel, concatenated with a thermal relaxation channel,
leads to average gate fidelities that would be determined by benchmarking.
two_qubit_gate_depolarizing_error_parameters: Depolarizing error parameters for two-qubit gates.
Maps two-qubit gate names to a mapping of pairs of qubits (on which the gate acts) to a depolarizing error.
The error, used in a two-qubit depolarizing channel, concatenated with thermal relaxation channels for the
qubits, leads to average gate fidelities that would be determined by benchmarking.
single_qubit_gate_durations: Gate duration (in ns) for each single-qubit gate
two_qubit_gate_durations: Gate duration (in ns) for each two-qubit gate.
readout_errors: Maps physical qubit names to dicts that describe their single-qubit readout errors.
For each qubit, the inner dict maps the state labels "0" and "1" to the probability :math:`P(\neg x|x)`
of observing the state :math:`\ket{\neg x}` given the true state is :math:`\ket{x}`.
name: Identifier of the QPU specimen.
Example:
.. code-block::
IQMErrorProfile(
t1s={"QB1": 10000.0, "QB2": 12000.0, "QB3": 14000.0},
t2s={"QB1": 10000.0, "QB2": 12000.0, "QB3": 13000.0},
single_qubit_gate_depolarizing_error_parameters={"r": {"QB1": 0.0005, "QB2": 0.0004, "QB3": 0.0010}},
two_qubit_gate_depolarizing_error_parameters={"cz": {("QB1", "QB2"): 0.08, ("QB2", "QB3"): 0.03}},
single_qubit_gate_durations={"r": 50.},
two_qubit_gate_durations={"cz": 100.},
readout_errors={"QB1": {"0": 0.02, "1": 0.03},
"QB2": {"0": 0.02, "1": 0.03},
"QB3": {"0": 0.02, "1": 0.03}},
name="threequbit-example_sample"
)
"""
t1s: dict[str, float]
t2s: dict[str, float]
single_qubit_gate_depolarizing_error_parameters: dict[str, dict[str, float]]
two_qubit_gate_depolarizing_error_parameters: dict[str, dict[tuple[str, str], float]]
single_qubit_gate_durations: dict[str, float]
two_qubit_gate_durations: dict[str, float]
readout_errors: dict[str, dict[str, float]]
name: Optional[str] = None
class IQMFakeBackend(IQMBackendBase):
"""Simulated backend that mimics the behaviour of IQM quantum computers.
Can be used to perform noisy gate-level simulations of quantum circuit execution on IQM hardware.
A fake backend contains information about a specific IQM system, such as the quantum architecture (number of qubits,
connectivity), the native gate set, and a noise model based on system parameters such as relaxation (:math:`T_1`)
and dephasing (:math:`T_2`) times, gate infidelities, and readout errors.
Args:
architecture: Quantum architecture associated with the backend instance.
error_profile: Characteristics of a particular QPU specimen.
"""
def __init__(
self,
architecture: QuantumArchitectureSpecification,
error_profile: IQMErrorProfile,
name: str = "IQMFakeBackend",
**kwargs,
):
super().__init__(architecture, **kwargs)
self._validate_architecture_and_error_profile(architecture, error_profile)
self.__architecture, self.__error_profile = architecture, error_profile
self.noise_model = self._create_noise_model(architecture, error_profile)
self.name = name
@property
def error_profile(self) -> IQMErrorProfile:
"""Error profile of this instance of IQM fake backend"""
return deepcopy(self.__error_profile)
@error_profile.setter
def error_profile(self, value: IQMErrorProfile) -> None:
""""""
raise NotImplementedError(
"Setting error profile of existing fake backend is not allowed. "
"You may consider using the method .copy_with_error_profile."
)
def copy_with_error_profile(self, new_error_profile: IQMErrorProfile) -> IQMFakeBackend:
"""Return another instance of IQMFakeBackend, which has the same quantum architecture but a different error
profile."""
return self.__class__(self.__architecture, new_error_profile)
@staticmethod
def _validate_architecture_and_error_profile(
architecture: QuantumArchitectureSpecification, error_profile: IQMErrorProfile
) -> None:
"""Verifies that the parameters of the QPU error profile match the constraints of its quantum architecture.
Raises:
ValueError: when length of `t1s` and number of qubits do not match.
ValueError: when length of `t2s` and number of qubits do not match.
ValueError: when length of `one_qubit_gate` parameter lists and number of qubits do not match.
ValueError: when length of `two_qubit_gate` parameter lists and number of couplings do not match.
ValueError: when gates in gate parameter lists are not supported by the quantum architecture.
"""
num_qubits = len(architecture.qubits)
# Check that T1 list has one element for each qubit
if len(error_profile.t1s) != num_qubits:
raise ValueError(
f"Length of t1s ({len(error_profile.t1s)}) and number of qubits ({num_qubits}) should match."
)
# Check that T2 list has one element for each qubit
if len(error_profile.t2s) != num_qubits:
raise ValueError(
f"Length of t2s ({len(error_profile.t2s)}) and number of qubits ({num_qubits}) should match."
)
property_dict: dict[str, dict[Any, float]]
# Check that one-qubit gate parameter qubits match those of the architecture
for property_name, property_dict in [
("depolarizing rates", error_profile.single_qubit_gate_depolarizing_error_parameters),
]:
gate_dict: dict[Any, float]
for gate, gate_dict in property_dict.items():
if set(gate_dict.keys()) != set(architecture.qubits):
raise ValueError(
(
f"The qubits specified for one-qubit gate {property_name} ({set(gate_dict.keys())}) "
f"don't match the qubits of the quantum architecture "
f"`{architecture.name}` ({architecture.qubits})."
)
)
# Check that two-qubit gate parameter couplings match those of the architecture
for property_name, property_dict in [
("depolarizing error parameters", error_profile.two_qubit_gate_depolarizing_error_parameters),
]:
for gate, gate_dict in property_dict.items():
if set(gate_dict.keys()) != set(tuple(item) for item in architecture.qubit_connectivity):
raise ValueError(
(
f"The couplings specified for two-qubit gate {property_name} ({set(gate_dict.keys())}) "
f"don't match the couplings of the quantum architecture "
f"`{architecture.name}` ({architecture.qubit_connectivity})."
)
)
# Check that the basis gates of the chip sample match the quantum architecture's
for property_name, specified_gates in [
(
"single_qubit_gate_depolarizing_error_parameters",
error_profile.single_qubit_gate_depolarizing_error_parameters.keys(),
),
(
"two_qubit_gate_depolarizing_error_parameters",
error_profile.two_qubit_gate_depolarizing_error_parameters.keys(),
),
("durations", (error_profile.single_qubit_gate_durations | error_profile.two_qubit_gate_durations).keys()),
]:
for gate in specified_gates:
if gate not in architecture.operations:
raise ValueError(
(
f"Gate `{gate}` in `{property_name}` "
f"is not supported by quantum architecture `{architecture.name}`. "
f"Valid gates: {architecture.operations}"
)
)
if set(error_profile.readout_errors.keys()) != set(architecture.qubits):
raise ValueError(
f"The qubits specified in readout errors ({set(error_profile.readout_errors.keys())}) "
f"don't match the qubits of the quantum architecture "
f"`{architecture.name}` ({architecture.qubits})."
)
def _create_noise_model(
self, architecture: QuantumArchitectureSpecification, error_profile: IQMErrorProfile
) -> NoiseModel:
"""
Builds a noise model from the attributes.
"""
noise_model = NoiseModel(basis_gates=["r", "cz"])
# Add single-qubit gate errors to noise model
for gate in error_profile.single_qubit_gate_depolarizing_error_parameters.keys():
for qb in architecture.qubits:
thermal_relaxation_channel = thermal_relaxation_error(
error_profile.t1s[qb], error_profile.t2s[qb], error_profile.single_qubit_gate_durations[gate]
)
depolarizing_channel = depolarizing_error(
error_profile.single_qubit_gate_depolarizing_error_parameters[gate][qb], 1
)
full_error_channel = thermal_relaxation_channel.compose(depolarizing_channel)
noise_model.add_quantum_error(
full_error_channel, IQM_TO_QISKIT_GATE_NAME[gate], [self.qubit_name_to_index(qb)]
)
# Add two-qubit gate errors to noise model
for gate, rates in error_profile.two_qubit_gate_depolarizing_error_parameters.items():
for (qb1, qb2), rate in rates.items():
for qb_order in permutations((qb1, qb2)):
thermal_relaxation_channel = thermal_relaxation_error(
error_profile.t1s[qb_order[0]],
error_profile.t2s[qb_order[0]],
error_profile.two_qubit_gate_durations[gate],
).tensor(
thermal_relaxation_error(
error_profile.t1s[qb_order[1]],
error_profile.t2s[qb_order[1]],
error_profile.two_qubit_gate_durations[gate],
)
)
depolarizing_channel = depolarizing_error(rate, 2)
full_error_channel = thermal_relaxation_channel.compose(depolarizing_channel)
noise_model.add_quantum_error(
full_error_channel,
IQM_TO_QISKIT_GATE_NAME[gate],
[self.qubit_name_to_index(qb_order[0]), self.qubit_name_to_index(qb_order[1])],
)
# Add readout errors
for qb, readout_error in error_profile.readout_errors.items():
probabilities = [[1 - readout_error["0"], readout_error["0"]], [readout_error["1"], 1 - readout_error["1"]]]
noise_model.add_readout_error(probabilities, [self.qubit_name_to_index(qb)])
return noise_model
@classmethod
def _default_options(cls) -> Options:
return Options(shots=1024, calibration_set_id=None)
@property
def max_circuits(self) -> Optional[int]:
return None
def run(self, run_input: Union[QuantumCircuit, list[QuantumCircuit]], **options) -> JobV1:
"""
Run `run_input` on the fake backend using a simulator.
This method runs circuit jobs (an individual or a list of QuantumCircuit
) and returns a :class:`~qiskit.providers.JobV1` object.
It will run the simulation with a noise model of the fake backend (e.g. Adonis).
Args:
run_input: One or more quantum circuits to simulate on the backend.
options: Any kwarg options to pass to the backend.
Returns:
The job object representing the run.
Raises:
ValueError: If empty list of circuits is provided.
"""
circuits = [run_input] if isinstance(run_input, QuantumCircuit) else run_input
if len(circuits) == 0:
raise ValueError("Empty list of circuits submitted for execution.")
shots = options.get("shots", self.options.shots)
# Create noisy simulator backend and run circuits
sim_noise = AerSimulator(noise_model=self.noise_model)
job = sim_noise.run(circuits, shots=shots)
return job
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022-2023 Qiskit on IQM developers
#
# 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.
"""Testing IQM backend.
"""
from typing import Optional
import pytest
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.providers import Options
from iqm.qiskit_iqm.iqm_backend import IQMBackendBase
class DummyIQMBackend(IQMBackendBase):
"""Dummy implementation for abstract methods of IQMBacked, so that instances can be created
and the rest of functionality tested."""
@classmethod
def _default_options(cls) -> Options:
return Options()
@property
def max_circuits(self) -> Optional[int]:
return None
def run(self, run_input, **options):
...
@pytest.fixture
def backend(linear_architecture_3q):
return DummyIQMBackend(linear_architecture_3q)
def test_qubit_name_to_index_to_qubit_name(adonis_architecture_shuffled_names):
backend = DummyIQMBackend(adonis_architecture_shuffled_names)
correct_idx_name_associations = set(enumerate(['QB1', 'QB2', 'QB3', 'QB4', 'QB5']))
assert all(backend.index_to_qubit_name(idx) == name for idx, name in correct_idx_name_associations)
assert all(backend.qubit_name_to_index(name) == idx for idx, name in correct_idx_name_associations)
assert backend.index_to_qubit_name(7) is None
assert backend.qubit_name_to_index('Alice') is None
def test_transpile(backend):
circuit = QuantumCircuit(3, 3)
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.cx(2, 0)
circuit_transpiled = transpile(circuit, backend=backend)
cmap = backend.coupling_map.get_edges()
for instruction, qubits, _ in circuit_transpiled.data:
assert instruction.name in ('r', 'cz')
if instruction.name == 'cz':
idx1 = circuit_transpiled.find_bit(qubits[0]).index
idx2 = circuit_transpiled.find_bit(qubits[1]).index
assert ((idx1, idx2) in cmap) or ((idx2, idx1) in cmap)
def test_validate_compatible_architecture(
adonis_architecture, adonis_architecture_shuffled_names, linear_architecture_3q
):
backend = DummyIQMBackend(adonis_architecture)
assert backend.validate_compatible_architecture(adonis_architecture) is True
assert backend.validate_compatible_architecture(adonis_architecture_shuffled_names) is True
assert backend.validate_compatible_architecture(linear_architecture_3q) is False
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022-2023 Qiskit on IQM developers
#
# 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.
"""Testing IQM backend.
"""
import re
from mockito import mock, when
import pytest
from qiskit import QuantumCircuit, transpile
from iqm.iqm_client import IQMClient
from iqm.qiskit_iqm.iqm_provider import IQMFacadeBackend
def test_run_fails_empty_cregs(adonis_architecture):
circuit = QuantumCircuit(5, 5)
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(0, 2)
circuit.measure_all()
client = mock(IQMClient)
when(client).get_quantum_architecture().thenReturn(adonis_architecture)
backend = IQMFacadeBackend(client)
circuit_transpiled = transpile(circuit, backend=backend)
with pytest.raises(ValueError, match='One or more circuits contain unused classical registers.'):
backend.run(circuit_transpiled)
def test_backend_name(adonis_architecture):
client = mock(IQMClient)
when(client).get_quantum_architecture().thenReturn(adonis_architecture)
backend = IQMFacadeBackend(client)
assert re.match(r'IQMFacade(.*)Backend', backend.name)
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022 Qiskit on IQM developers
#
# 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.
"""Testing IQMJob.
"""
import io
import uuid
import mockito
from mockito import mock, unstub, verify, when
import pytest
from qiskit import QuantumCircuit
from qiskit.providers import JobStatus
from qiskit.result import Counts
from qiskit.result import Result as QiskitResult
from qiskit.tools.monitor import job_monitor
from iqm.iqm_client import (
HeraldingMode,
Instruction,
IQMClient,
JobAbortionError,
RunResult,
RunStatus,
SingleQubitMapping,
Status,
)
from iqm.qiskit_iqm.iqm_job import IQMJob
from iqm.qiskit_iqm.iqm_provider import IQMBackend
@pytest.fixture()
def job(adonis_architecture):
client = mock(IQMClient)
when(client).get_quantum_architecture().thenReturn(adonis_architecture)
backend = IQMBackend(client)
return IQMJob(backend, str(uuid.uuid4()))
@pytest.fixture()
def iqm_result_no_shots():
return {'c_2_0_0': [], 'c_2_0_1': []}
@pytest.fixture()
def iqm_result_two_registers():
return {'c_2_0_0': [[1], [0], [1], [0]], 'c_2_0_1': [[1], [1], [0], [1]], 'd_4_1_2': [[1], [1], [1], [1]]}
@pytest.fixture()
def iqm_metadata():
measurement = Instruction(name='measure', implementation=None, qubits=('0',), args={'key': 'm1'})
return {
'calibration_set_id': 'df124054-f6d8-41f9-b880-8487f90018f9',
'request': {
'shots': 4,
'circuits': [{'name': 'circuit_1', 'instructions': (measurement,), 'metadata': {'a': 'b'}}],
'calibration_set_id': 'df124054-f6d8-41f9-b880-8487f90018f9',
'qubit_mapping': [
SingleQubitMapping(logical_name='0', physical_name='QB1'),
SingleQubitMapping(logical_name='1', physical_name='QB2'),
],
},
}
@pytest.fixture()
def iqm_metadata_with_timestamps():
measurement = Instruction(name='measure', implementation=None, qubits=('0',), args={'key': 'm1'})
return {
'calibration_set_id': 'df124054-f6d8-41f9-b880-8487f90018f9',
'request': {
'shots': 4,
'circuits': [{'name': 'circuit_1', 'instructions': (measurement,), 'metadata': {'a': 'b'}}],
'calibration_set_id': 'df124054-f6d8-41f9-b880-8487f90018f9',
'qubit_mapping': [
SingleQubitMapping(logical_name='0', physical_name='QB1'),
SingleQubitMapping(logical_name='1', physical_name='QB2'),
],
},
'timestamps': {
'job_start': '2023-01-02T12:34:56.123456+00:00',
'job_end': '2023-01-02T12:34:56.123456+03:00',
},
}
def test_submit_raises(job):
with pytest.raises(NotImplementedError, match='You should never have to submit jobs by calling this method.'):
job.submit()
def test_cancel_successful(job, recwarn):
when(job._client).abort_job(uuid.UUID(job.job_id())).thenReturn(None)
assert job.cancel() is True
assert len(recwarn) == 0
verify(job._client, times=1).abort_job(uuid.UUID(job.job_id()))
unstub()
def test_cancel_failed(job):
when(job._client).abort_job(uuid.UUID(job.job_id())).thenRaise(JobAbortionError)
with pytest.warns(UserWarning, match='Failed to cancel job'):
assert job.cancel() is False
verify(job._client, times=1).abort_job(uuid.UUID(job.job_id()))
unstub()
def test_status_for_ready_result(job):
job._result = [('circuit_1', ['11', '10', '10'])]
assert job.status() == JobStatus.DONE
result = job.result()
assert isinstance(result, QiskitResult)
assert result.get_memory() == ['11', '10', '10']
def test_status_done(job, iqm_metadata):
client_result = RunResult(status=Status.READY, measurements=None, metadata=iqm_metadata)
when(job._client).get_run_status(uuid.UUID(job.job_id())).thenReturn(client_result)
assert job.status() == JobStatus.DONE
assert job._result is None
@pytest.mark.parametrize(
'run_status,job_status',
[
(Status.PENDING_COMPILATION, JobStatus.QUEUED),
(Status.PENDING_EXECUTION, JobStatus.RUNNING),
(Status.FAILED, JobStatus.ERROR),
(Status.ABORTED, JobStatus.CANCELLED),
],
)
def test_other_job_statuses(job, run_status: Status, job_status: JobStatus):
when(job._client).get_run_status(uuid.UUID(job.job_id())).thenReturn(RunStatus(status=run_status))
assert job.status() == job_status
def test_error_message(job, iqm_metadata):
err_msg = 'The job failed with this error message'
client_result = RunResult(status=Status.FAILED, message=err_msg, metadata=iqm_metadata)
when(job._client).get_run_status(uuid.UUID(job.job_id())).thenReturn(client_result)
assert job.status() == JobStatus.ERROR
assert job.error_message() == err_msg
def test_error_message_on_successful_job(job, iqm_metadata):
client_result = RunResult(status=Status.READY, metadata=iqm_metadata)
when(job._client).get_run_status(uuid.UUID(job.job_id())).thenReturn(client_result)
assert job.status() == JobStatus.DONE
assert job.error_message() is None
def test_result(job, iqm_result_two_registers, iqm_metadata):
client_result = RunResult(
status=Status.READY,
measurements=[iqm_result_two_registers],
metadata=iqm_metadata,
)
when(job._client).wait_for_results(uuid.UUID(job.job_id())).thenReturn(client_result)
result = job.result()
assert isinstance(result, QiskitResult)
assert result.get_memory() == ['0100 11', '0100 10', '0100 01', '0100 10']
assert result.get_counts() == Counts({'0100 11': 1, '0100 10': 2, '0100 01': 1})
for r in result.results:
assert r.calibration_set_id == uuid.UUID('df124054-f6d8-41f9-b880-8487f90018f9')
assert r.data.metadata == {'a': 'b'}
assert result.request.qubit_mapping == iqm_metadata['request']['qubit_mapping']
# Assert that repeated call does not query the client (i.e. works without calling the mocked wait_for_results)
# and call to status() does not call any functions from client.
result = job.result()
assert isinstance(result, QiskitResult)
assert job.status() == JobStatus.DONE
mockito.verify(job._client, times=1).wait_for_results(uuid.UUID(job.job_id()))
def test_result_no_shots(job, iqm_result_no_shots, iqm_metadata):
iqm_metadata['request']['heralding_mode'] = HeraldingMode.ZEROS
client_result = RunResult(
status=Status.READY,
measurements=[iqm_result_no_shots],
metadata=iqm_metadata,
)
when(job._client).wait_for_results(uuid.UUID(job.job_id())).thenReturn(client_result)
with pytest.warns(UserWarning, match='Received measurement results containing zero shots.'):
result = job.result()
assert isinstance(result, QiskitResult)
assert result.get_memory() == []
assert result.get_counts() == Counts({})
def test_result_multiple_circuits(job, iqm_result_two_registers):
instruction_meta = [{'name': 'measure', 'qubits': ['0'], 'args': {'key': 'm1'}}]
iqm_metadata_multiple_circuits = {
'calibration_set_id': '9d75904b-0c93-461f-b1dc-bd200cfad1f1',
'request': {
'shots': 4,
'circuits': [
{'name': 'circuit_1', 'instructions': instruction_meta, 'metadata': {'a': 0}},
{'name': 'circuit_2', 'instructions': instruction_meta, 'metadata': {'a': 1}},
],
'calibration_set_id': '9d75904b-0c93-461f-b1dc-bd200cfad1f1',
'qubit_mapping': [
SingleQubitMapping(logical_name='0', physical_name='QB1'),
SingleQubitMapping(logical_name='1', physical_name='QB2'),
SingleQubitMapping(logical_name='2', physical_name='QB3'),
],
},
}
client_result = RunResult(
status=Status.READY,
measurements=[iqm_result_two_registers, iqm_result_two_registers],
metadata=iqm_metadata_multiple_circuits,
)
when(job._client).wait_for_results(uuid.UUID(job.job_id())).thenReturn(client_result)
result = job.result()
assert isinstance(result, QiskitResult)
for circuit_idx in range(2):
assert result.get_memory(circuit_idx) == ['0100 11', '0100 10', '0100 01', '0100 10']
assert result.get_counts(circuit_idx) == Counts({'0100 11': 1, '0100 10': 2, '0100 01': 1})
assert result.get_counts(QuantumCircuit(name='circuit_1')) == Counts({'0100 11': 1, '0100 10': 2, '0100 01': 1})
assert result.get_counts(QuantumCircuit(name='circuit_2')) == Counts({'0100 11': 1, '0100 10': 2, '0100 01': 1})
for i, r in enumerate(result.results):
assert r.calibration_set_id == uuid.UUID('9d75904b-0c93-461f-b1dc-bd200cfad1f1')
assert r.data.metadata == {'a': i}
assert result.request.qubit_mapping == iqm_metadata_multiple_circuits['request']['qubit_mapping']
def test_result_with_timestamps(job, iqm_result_two_registers, iqm_metadata_with_timestamps):
client_result = RunResult(
status=Status.READY,
measurements=[iqm_result_two_registers],
metadata=iqm_metadata_with_timestamps,
)
when(job._client).wait_for_results(uuid.UUID(job.job_id())).thenReturn(client_result)
assert job.metadata.get('timestamps') is None
result = job.result()
assert 'timestamps' in job.metadata
assert job.metadata.pop('timestamps') == iqm_metadata_with_timestamps.get('timestamps')
assert 'timestamps' in result._metadata
assert result.timestamps == iqm_metadata_with_timestamps.get('timestamps')
def test_job_monitor(job, iqm_metadata):
client_result = RunResult(status=Status.READY, metadata=iqm_metadata)
run_responses = [
[RunStatus(status=Status.PENDING_COMPILATION), RunStatus(status=Status.ABORTED)],
[RunStatus(status=Status.PENDING_COMPILATION)] * 2 + [RunStatus(status=Status.FAILED)],
[RunStatus(status=Status.PENDING_COMPILATION)] * 2
+ [RunStatus(status=Status.PENDING_EXECUTION), client_result],
[RunStatus(status=s.value) for s in Status],
]
sep = '---'
for responses in run_responses:
when(job._client).get_run_status(uuid.UUID(job.job_id())).thenReturn(*responses)
monitor_string = io.StringIO()
job_monitor(job, output=monitor_string, line_discipline=sep, interval=0)
monitor_string.close()
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022-2023 Qiskit on IQM developers
#
# 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.
"""Testing IQM provider.
"""
from collections.abc import Sequence
from importlib.metadata import version
import re
import uuid
from mockito import ANY, matchers, mock, patch, when
import numpy as np
import pytest
from qiskit import QuantumCircuit, execute
from qiskit.circuit import Parameter
from qiskit.circuit.library import RGate, RXGate, RYGate, XGate, YGate
from qiskit.compiler import transpile
import requests
from iqm.iqm_client import HeraldingMode, IQMClient, QuantumArchitecture, RunResult, RunStatus
from iqm.qiskit_iqm.iqm_provider import IQMBackend, IQMFacadeBackend, IQMJob, IQMProvider
from tests.utils import get_mock_ok_response
@pytest.fixture
def backend(linear_architecture_3q):
client = mock(IQMClient)
when(client).get_quantum_architecture().thenReturn(linear_architecture_3q)
return IQMBackend(client)
@pytest.fixture
def circuit():
return QuantumCircuit(3, 3)
@pytest.fixture
def circuit_2() -> QuantumCircuit:
circuit = QuantumCircuit(5)
circuit.cz(0, 1)
return circuit
@pytest.fixture
def submit_circuits_default_kwargs() -> dict:
return {
'qubit_mapping': None,
'calibration_set_id': None,
'shots': 1024,
'max_circuit_duration_over_t2': None,
'heralding_mode': HeraldingMode.NONE,
}
@pytest.fixture
def job_id():
return uuid.uuid4()
def test_default_options(backend):
assert backend.options.shots == 1024
assert backend.options.calibration_set_id is None
assert backend.options.max_circuit_duration_over_t2 is None
assert backend.options.heralding_mode == HeraldingMode.NONE
assert backend.options.circuit_callback is None
def test_backend_name(backend):
assert re.match(r'IQM(.*)Backend', backend.name)
def test_retrieve_job(backend):
job = backend.retrieve_job('a job id')
assert job.backend() == backend
assert job.job_id() == 'a job id'
def test_default_max_circuits(backend):
assert backend.max_circuits is None
def test_set_max_circuits(backend):
assert backend.max_circuits is None
backend.max_circuits = 17
assert backend.max_circuits == 17
backend.max_circuits = 168
assert backend.max_circuits == 168
def test_qubit_name_to_index_to_qubit_name(adonis_architecture_shuffled_names):
client = mock(IQMClient)
when(client).get_quantum_architecture().thenReturn(adonis_architecture_shuffled_names)
backend = IQMBackend(client)
correct_idx_name_associations = set(enumerate(['QB1', 'QB2', 'QB3', 'QB4', 'QB5']))
assert all(backend.index_to_qubit_name(idx) == name for idx, name in correct_idx_name_associations)
assert all(backend.qubit_name_to_index(name) == idx for idx, name in correct_idx_name_associations)
assert backend.index_to_qubit_name(7) is None
assert backend.qubit_name_to_index('Alice') is None
def test_serialize_circuit_raises_error_for_non_transpiled_circuit(backend, circuit):
circuit = QuantumCircuit(2, 2)
with pytest.raises(ValueError, match='has not been transpiled against the current backend'):
backend.serialize_circuit(circuit)
def test_serialize_circuit_raises_error_for_unsupported_instruction(backend, circuit):
circuit.sx(0)
with pytest.raises(ValueError, match=f"Instruction 'sx' in the circuit '{circuit.name}' is not natively supported"):
backend.serialize_circuit(circuit)
def test_serialize_circuit_does_not_raise_for_x_rx_y_ry(backend, circuit):
circuit.x(0)
circuit.rx(0.123, 0)
circuit.y(0)
circuit.ry(0.321, 0)
backend.serialize_circuit(circuit)
def test_serialize_circuit_raises_error_for_unsupported_metadata(backend, circuit):
circuit.append(RGate(theta=np.pi, phi=0), [0])
circuit.metadata = {'some-key': complex(1.0, 2.0)}
with pytest.warns(UserWarning):
serialized_circuit = backend.serialize_circuit(circuit)
assert serialized_circuit.metadata is None
@pytest.mark.parametrize(
'gate, expected_angle, expected_phase',
[
(RGate(theta=np.pi, phi=0), 1 / 2, 0),
(RGate(theta=0, phi=np.pi), 0, 1 / 2),
(RGate(theta=0, phi=2 * np.pi), 0, 1),
(RGate(theta=2 * np.pi, phi=np.pi), 1, 1 / 2),
],
)
def test_serialize_circuit_maps_r_gate(circuit, gate, expected_angle, expected_phase, backend):
circuit.append(gate, [0])
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 1
instr = circuit_ser.instructions[0]
assert instr.name == 'prx'
assert instr.qubits == ('0',)
# Serialized angles should be in full turns
assert instr.args['angle_t'] == expected_angle
assert instr.args['phase_t'] == expected_phase
@pytest.mark.parametrize(
'gate, expected_angle, expected_phase',
[
(XGate(), 1 / 2, 0),
(RXGate(theta=np.pi / 2), 1 / 4, 0),
(RXGate(theta=2 * np.pi / 3), 1 / 3, 0),
(YGate(), 1 / 2, 1 / 4),
(RYGate(theta=np.pi / 2), 1 / 4, 1 / 4),
(RYGate(theta=2 * np.pi / 3), 1 / 3, 1 / 4),
],
)
def test_serialize_circuit_maps_x_rx_y_ry_gates(backend, circuit, gate, expected_angle, expected_phase):
circuit.append(gate, [0])
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 1
instr = circuit_ser.instructions[0]
assert instr.name == 'prx'
assert instr.qubits == ('0',)
assert instr.args['angle_t'] == expected_angle
assert instr.args['phase_t'] == expected_phase
def test_serialize_circuit_maps_cz_gate(circuit, backend):
circuit.cz(0, 2)
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 1
assert circuit_ser.instructions[0].name == 'cz'
assert circuit_ser.instructions[0].qubits == ('0', '2')
assert circuit_ser.instructions[0].args == {}
def test_serialize_circuit_maps_individual_measurements(circuit, backend):
circuit.measure(0, 0)
circuit.measure(1, 1)
circuit.measure(2, 2)
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 3
for i, instruction in enumerate(circuit_ser.instructions):
assert instruction.name == 'measure'
assert instruction.qubits == (f'{i}',)
assert instruction.args == {'key': f'c_3_0_{i}'}
def test_serialize_circuit_batch_measurement(circuit, backend):
circuit.measure([0, 1, 2], [0, 1, 2])
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 3
for i, instruction in enumerate(circuit_ser.instructions):
assert instruction.name == 'measure'
assert instruction.qubits == (f'{i}',)
assert instruction.args == {'key': f'c_3_0_{i}'}
def test_serialize_circuit_barrier(circuit, backend):
circuit.r(theta=np.pi, phi=0, qubit=0)
circuit.barrier([0, 1])
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 2
assert circuit_ser.instructions[1].name == 'barrier'
assert circuit_ser.instructions[1].qubits == ('0', '1')
assert circuit_ser.instructions[1].args == {}
def test_serialize_circuit_id(circuit, backend):
circuit.r(theta=np.pi, phi=0, qubit=0)
circuit.id(0)
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 1
assert circuit_ser.instructions[0].name == 'prx'
def test_transpile(backend, circuit):
circuit.h(0)
circuit.id(1)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.cx(2, 0)
circuit_transpiled = transpile(circuit, backend=backend)
cmap = backend.coupling_map.get_edges()
for instruction, qubits, _ in circuit_transpiled.data:
assert instruction.name in ('r', 'cz')
if instruction.name == 'cz':
idx1 = circuit_transpiled.find_bit(qubits[0]).index
idx2 = circuit_transpiled.find_bit(qubits[1]).index
assert ((idx1, idx2) in cmap) or ((idx2, idx1) in cmap)
def test_run_non_native_circuit_with_the_execute_function(backend, circuit):
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(0, 2)
some_id = uuid.uuid4()
backend.client.submit_circuits = lambda *args, **kwargs: some_id
job = execute(circuit, backend=backend, optimization_level=0)
assert isinstance(job, IQMJob)
assert job.job_id() == str(some_id)
def test_run_gets_options_from_execute_function(backend, circuit):
"""Test that any additional keyword arguments to the `execute` function are passed to `IQMBackend.run`. This is more
of a test for Qiskit's `execute` function itself, but still good to have it here to know that the use case works.
"""
def run_mock(qc, **kwargs):
assert isinstance(qc, QuantumCircuit)
assert 'calibration_set_id' in kwargs
assert kwargs['calibration_set_id'] == '92d8dd9a-2678-467e-a20b-ef9c1a594d1f'
assert 'something_else' in kwargs
assert kwargs['something_else'] == [1, 2, 3]
patch(backend.run, run_mock)
execute(
circuit, backend, shots=10, calibration_set_id='92d8dd9a-2678-467e-a20b-ef9c1a594d1f', something_else=[1, 2, 3]
)
def test_run_single_circuit(backend, circuit, submit_circuits_default_kwargs, job_id):
circuit.measure(0, 0)
circuit_ser = backend.serialize_circuit(circuit)
kwargs = submit_circuits_default_kwargs | {'qubit_mapping': {'0': 'QB1'}}
when(backend.client).submit_circuits([circuit_ser], **kwargs).thenReturn(job_id)
job = backend.run(circuit)
assert isinstance(job, IQMJob)
assert job.job_id() == str(job_id)
# Should also work if the circuit is passed inside a list
job = backend.run([circuit])
assert isinstance(job, IQMJob)
assert job.job_id() == str(job_id)
def test_run_sets_circuit_metadata_to_the_job(backend):
circuit_1 = QuantumCircuit(3)
circuit_1.cz(0, 1)
circuit_1.metadata = {'key1': 'value1', 'key2': 'value2'}
circuit_2 = QuantumCircuit(3)
circuit_2.cz(0, 1)
circuit_2.metadata = {'key1': 'value2', 'key2': 'value1'}
some_id = uuid.uuid4()
backend.client.submit_circuits = lambda *args, **kwargs: some_id
job = backend.run([circuit_1, circuit_2], shots=10)
assert isinstance(job, IQMJob)
assert job.job_id() == str(some_id)
assert job.circuit_metadata == [circuit_1.metadata, circuit_2.metadata]
@pytest.mark.parametrize('shots', [13, 978, 1137])
def test_run_with_custom_number_of_shots(backend, circuit, submit_circuits_default_kwargs, job_id, shots):
circuit.measure(0, 0)
kwargs = submit_circuits_default_kwargs | {'shots': shots, 'qubit_mapping': {'0': 'QB1'}}
when(backend.client).submit_circuits(ANY, **kwargs).thenReturn(job_id)
backend.run(circuit, shots=shots)
@pytest.mark.parametrize(
'calibration_set_id', ['67e77465-d90e-4839-986e-9270f952b743', uuid.UUID('67e77465-d90e-4839-986e-9270f952b743')]
)
def test_run_with_custom_calibration_set_id(
backend, circuit, submit_circuits_default_kwargs, job_id, calibration_set_id
):
circuit.measure(0, 0)
circuit_ser = backend.serialize_circuit(circuit)
kwargs = submit_circuits_default_kwargs | {
'calibration_set_id': uuid.UUID('67e77465-d90e-4839-986e-9270f952b743'),
'qubit_mapping': {'0': 'QB1'},
}
when(backend.client).submit_circuits([circuit_ser], **kwargs).thenReturn(job_id)
backend.run([circuit], calibration_set_id=calibration_set_id)
def test_run_with_duration_check_disabled(backend, circuit, submit_circuits_default_kwargs, job_id):
circuit.measure(0, 0)
circuit_ser = backend.serialize_circuit(circuit)
kwargs = submit_circuits_default_kwargs | {'qubit_mapping': {'0': 'QB1'}, 'max_circuit_duration_over_t2': 0.0}
when(backend.client).submit_circuits([circuit_ser], **kwargs).thenReturn(job_id)
backend.run([circuit], max_circuit_duration_over_t2=0.0)
def test_run_uses_heralding_mode_none_by_default(backend, circuit, submit_circuits_default_kwargs, job_id):
circuit.measure(0, 0)
circuit_ser = backend.serialize_circuit(circuit)
kwargs = submit_circuits_default_kwargs | {'heralding_mode': HeraldingMode.NONE, 'qubit_mapping': {'0': 'QB1'}}
when(backend.client).submit_circuits([circuit_ser], **kwargs).thenReturn(job_id)
backend.run([circuit])
def test_run_with_heralding_mode_zeros(backend, circuit, submit_circuits_default_kwargs, job_id):
circuit.measure(0, 0)
circuit_ser = backend.serialize_circuit(circuit)
kwargs = submit_circuits_default_kwargs | {'heralding_mode': HeraldingMode.ZEROS, 'qubit_mapping': {'0': 'QB1'}}
when(backend.client).submit_circuits([circuit_ser], **kwargs).thenReturn(job_id)
backend.run([circuit], heralding_mode='zeros')
# mypy: disable-error-code="attr-defined"
def test_run_with_circuit_callback(backend, job_id, submit_circuits_default_kwargs):
qc1 = QuantumCircuit(3)
qc1.measure_all()
qc2 = QuantumCircuit(3)
qc2.r(np.pi, 0.3, 0)
qc2.measure_all()
def sample_callback(circuits) -> None:
assert isinstance(circuits, Sequence)
assert all(isinstance(c, QuantumCircuit) for c in circuits)
assert len(circuits) == 2
assert circuits[0].name == qc1.name
assert circuits[1].name == qc2.name
sample_callback.called = True
sample_callback.called = False
kwargs = submit_circuits_default_kwargs | {'qubit_mapping': {'0': 'QB1', '1': 'QB2', '2': 'QB3'}}
when(backend.client).submit_circuits(ANY, **kwargs).thenReturn(job_id)
backend.run([qc1, qc2], circuit_callback=sample_callback)
assert sample_callback.called is True
def test_run_with_unknown_option(backend, circuit, job_id):
circuit.measure_all()
when(backend.client).submit_circuits(...).thenReturn(job_id)
with pytest.warns(Warning, match=r'Unknown backend option\(s\)'):
backend.run(circuit, to_option_or_not_to_option=17)
def test_run_batch_of_circuits(backend, circuit, submit_circuits_default_kwargs, job_id):
theta = Parameter('theta')
theta_range = np.linspace(0, 2 * np.pi, 3)
circuit.cz(0, 1)
circuit.r(theta, 0, 0)
circuit.cz(0, 1)
circuits = [circuit.assign_parameters({theta: t}) for t in theta_range]
circuits_serialized = [backend.serialize_circuit(circuit) for circuit in circuits]
kwargs = submit_circuits_default_kwargs | {'qubit_mapping': {'0': 'QB1', '1': 'QB2'}}
when(backend.client).submit_circuits(circuits_serialized, **kwargs).thenReturn(job_id)
job = backend.run(circuits)
assert isinstance(job, IQMJob)
assert job.job_id() == str(job_id)
def test_error_on_empty_circuit_list(backend):
with pytest.raises(ValueError, match='Empty list of circuits submitted for execution.'):
backend.run([], shots=42)
def test_close_client(backend):
when(backend.client).close_auth_session().thenReturn(True)
try:
backend.close_client()
except Exception as exc: # pylint: disable=broad-except
assert False, f'backend raised an exception {exc} on .close_client()'
def test_get_backend(linear_architecture_3q):
url = 'http://some_url'
when(IQMClient).get_quantum_architecture().thenReturn(linear_architecture_3q)
provider = IQMProvider(url)
backend = provider.get_backend()
assert isinstance(backend, IQMBackend)
assert backend.client._base_url == url
assert backend.num_qubits == 3
assert set(backend.coupling_map.get_edges()) == {(0, 1), (1, 0), (1, 2), (2, 1)}
def test_client_signature(adonis_architecture):
url = 'http://some_url'
provider = IQMProvider(url)
when(requests).get('http://some_url/quantum-architecture', headers=matchers.ANY, timeout=matchers.ANY).thenReturn(
get_mock_ok_response(QuantumArchitecture(quantum_architecture=adonis_architecture).model_dump())
)
backend = provider.get_backend()
assert f'qiskit-iqm {version("qiskit-iqm")}' in backend.client._signature
def test_get_facade_backend(adonis_architecture, adonis_coupling_map):
url = 'http://some_url'
when(IQMClient).get_quantum_architecture().thenReturn(adonis_architecture)
provider = IQMProvider(url)
backend = provider.get_backend('facade_adonis')
assert isinstance(backend, IQMFacadeBackend)
assert backend.client._base_url == url
assert backend.num_qubits == 5
assert set(backend.coupling_map.get_edges()) == adonis_coupling_map
def test_get_facade_backend_raises_error_non_matching_architecture(linear_architecture_3q):
url = 'http://some_url'
when(IQMClient).get_quantum_architecture().thenReturn(linear_architecture_3q)
provider = IQMProvider(url)
with pytest.raises(ValueError, match='Quantum architecture of the remote quantum computer does not match Adonis.'):
provider.get_backend('facade_adonis')
def test_facade_backend_raises_error_on_remote_execution_fail(adonis_architecture, circuit_2):
url = 'http://some_url'
result = {
'status': 'failed',
'measurements': [],
'metadata': {
'request': {
'shots': 1024,
'circuits': [
{
'name': 'circuit_2',
'instructions': [{'name': 'measure', 'qubits': ['0'], 'args': {'key': 'm1'}}],
}
],
}
},
}
result_status = {'status': 'failed'}
when(IQMClient).get_quantum_architecture().thenReturn(adonis_architecture)
when(IQMClient).submit_circuits(...).thenReturn(uuid.uuid4())
when(IQMClient).get_run(ANY(uuid.UUID)).thenReturn(RunResult.from_dict(result))
when(IQMClient).get_run_status(ANY(uuid.UUID)).thenReturn(RunStatus.from_dict(result_status))
provider = IQMProvider(url)
backend = provider.get_backend('facade_adonis')
with pytest.raises(RuntimeError, match='Remote execution did not succeed'):
backend.run(circuit_2)
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022-2023 Qiskit on IQM developers
#
# 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.
"""Testing IQM transpilation.
"""
import numpy as np
import pytest
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from iqm.qiskit_iqm.iqm_transpilation import optimize_single_qubit_gates
from tests.utils import get_transpiled_circuit_json
def test_optimize_single_qubit_gates_preserves_unitary():
"""Test that single-qubit gate decomposition preserves the unitary of the circuit."""
circuit = QuantumCircuit(2, 2)
circuit.t(0)
circuit.rx(0.4, 0)
circuit.cx(0, 1)
circuit.ry(0.7, 1)
circuit.h(1)
circuit.r(0.2, 0.8, 0)
circuit.h(0)
transpiled_circuit = transpile(circuit, basis_gates=['r', 'cz'])
optimized_circuit = optimize_single_qubit_gates(transpiled_circuit, drop_final_rz=False)
transpiled_circuit.save_unitary()
optimized_circuit.save_unitary()
simulator = AerSimulator(method='unitary')
transpiled_unitary = simulator.run(transpiled_circuit).result().get_unitary(transpiled_circuit)
optimized_unitary = simulator.run(optimized_circuit).result().get_unitary(optimized_circuit)
np.testing.assert_almost_equal(transpiled_unitary.data, optimized_unitary.data)
def test_optimize_single_qubit_gates_drops_final_rz():
"""Test that single-qubit gate decomposition drops the final rz gate if requested and there is no measurement."""
circuit = QuantumCircuit(2, 1)
circuit.h(0)
circuit.h(1)
circuit.cz(0, 1)
circuit.h(1)
circuit.measure(1, 0)
transpiled_circuit = transpile(circuit, basis_gates=['r', 'cz'])
optimized_circuit_dropped_rz = optimize_single_qubit_gates(transpiled_circuit)
optimized_circuit = optimize_single_qubit_gates(transpiled_circuit, drop_final_rz=False)
simulator = AerSimulator(method='statevector')
shots = 1000
transpiled_counts = simulator.run(transpiled_circuit, shots=shots).result().get_counts()
optimized_counts = simulator.run(optimized_circuit, shots=shots).result().get_counts()
optimized_dropped_rz_counts = simulator.run(optimized_circuit_dropped_rz, shots=shots).result().get_counts()
for counts in [transpiled_counts, optimized_counts, optimized_dropped_rz_counts]:
for key in counts:
counts[key] = np.round(counts[key] / shots, 1)
assert transpiled_counts == optimized_counts == optimized_dropped_rz_counts
assert len(optimized_circuit_dropped_rz.get_instructions('r')) == 3
assert len(optimized_circuit.get_instructions('r')) == 5
def test_optimize_single_qubit_gates_reduces_gate_count():
"""Test that single-qubit gate decomposition optimizes the number of single-qubit gates."""
circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()
transpiled_circuit = transpile(circuit, basis_gates=['r', 'cz'])
optimized_circuit = optimize_single_qubit_gates(transpiled_circuit)
assert len(optimized_circuit.get_instructions('r')) == 3
def test_optimize_single_qubit_gates_raises_on_invalid_basis():
"""Test that optimisation pass raises error if gates other than ``RZ`` and ``CZ`` are provided."""
circuit = QuantumCircuit(1, 1)
circuit.h(0)
with pytest.raises(ValueError, match="Invalid operation 'h' found "):
optimize_single_qubit_gates(circuit)
def test_submitted_circuit(adonis_architecture):
"""Test that a circuit submitted via IQM backend gets transpiled into proper JSON."""
circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()
# This transpilation seed maps virtual qubit 0 to physical qubit 2, and virtual qubit 1 to physical qubit 4
# Other seeds will switch the mapping, and may also reorder the first phased_rx instructions
submitted_circuit = get_transpiled_circuit_json(circuit, adonis_architecture, seed_transpiler=123)
instr_names = [f"{instr.name}:{','.join(instr.qubits)}" for instr in submitted_circuit.instructions]
assert instr_names == [
# Hadamard on 0 (= physical 0)
'prx:2',
'prx:2',
# CX phase 1: Hadamard on target qubit 1 (= physical 4)
'prx:4',
'prx:4',
# CX phase 2: CZ on 0,1 (= physical 2,4)
'cz:2,4',
# Hadamard again on target qubit 1 (= physical 4)
'prx:4',
'prx:4',
# Barrier before measurements
'barrier:2,4',
# Measurement on both qubits
'measure:2',
'measure:4',
]
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022 Qiskit on IQM developers
#
# 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.
"""Testing Qiskit to IQM conversion tools.
"""
import pytest
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from iqm.qiskit_iqm.qiskit_to_iqm import MeasurementKey
@pytest.fixture()
def circuit() -> QuantumCircuit:
return QuantumCircuit(3, 3)
def test_measurement_key_to_str():
mk = MeasurementKey('abc', 1, 2, 3)
assert str(mk) == 'abc_1_2_3'
def test_measurement_key_from_clbit():
qreg = QuantumRegister(3)
creg1, creg2 = ClassicalRegister(2, name='cr1'), ClassicalRegister(1, name='cr2')
circuit = QuantumCircuit(qreg, creg1, creg2)
mk1 = MeasurementKey.from_clbit(creg1[0], circuit)
mk2 = MeasurementKey.from_clbit(creg1[1], circuit)
mk3 = MeasurementKey.from_clbit(creg2[0], circuit)
assert str(mk1) == 'cr1_2_0_0'
assert str(mk2) == 'cr1_2_0_1'
assert str(mk3) == 'cr2_1_1_0'
@pytest.mark.parametrize('key_str', ['abc_4_5_6', 'a_bc_4_5_6'])
def test_measurement_key_from_string(key_str):
mk = MeasurementKey.from_string(key_str)
assert str(mk) == key_str
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# -*- 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/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022-2023 Qiskit on IQM developers
#
# 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.
"""Testing IQM fake backend.
"""
import pytest
from qiskit import QuantumCircuit
from qiskit.providers import JobV1
from qiskit_aer.noise.noise_model import NoiseModel
from iqm.qiskit_iqm.fake_backends.iqm_fake_backend import IQMFakeBackend
@pytest.fixture
def backend(linear_architecture_3q, create_3q_error_profile):
return IQMFakeBackend(linear_architecture_3q, create_3q_error_profile())
def test_fake_backend_with_incomplete_t1s(linear_architecture_3q, create_3q_error_profile):
"""Test that IQMFakeBackend construction fails if T1 times are not provided for all qubits"""
with pytest.raises(ValueError, match="Length of t1s"):
error_profile = create_3q_error_profile(t1s={"QB1": 2000, "QB3": 2000})
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_fake_backend_with_incomplete_t2s(linear_architecture_3q, create_3q_error_profile):
"""Test that IQMFakeBackend construction fails if T2 times are not provided for all qubits"""
with pytest.raises(ValueError, match="Length of t2s"):
error_profile = create_3q_error_profile(t2s={"QB1": 2000, "QB3": 2000})
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_fake_backend_with_single_qubit_gate_depolarizing_errors_qubits_not_matching_quantum_architecture(
linear_architecture_3q,
create_3q_error_profile,
):
"""Test that IQMFakeBackend construction fails if depolarizing rates are not provided for all qubits"""
with pytest.raises(ValueError, match="The qubits specified for one-qubit gate"):
error_profile = create_3q_error_profile(
single_qubit_gate_depolarizing_error_parameters={"prx": {"QB1": 0.0001, "QB2": 0.0001}},
)
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_fake_backend_with_single_qubit_gate_depolarizing_errors_more_qubits_than_in_quantum_architecture(
linear_architecture_3q,
create_3q_error_profile,
):
"""Test that IQMFakeBackend construction fails if depolarizing rates are provided for
other qubits than specified in the quantum architecture"""
with pytest.raises(ValueError, match="The qubits specified for one-qubit gate"):
error_profile = create_3q_error_profile(
single_qubit_gate_depolarizing_error_parameters={
"prx": {"QB1": 0.0001, "QB2": 0.0001, "QB3": 0.0001, "QB4": 0.0001}
},
)
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_fake_backend_with_two_qubit_gate_depolarizing_errors_couplings_not_matching_quantum_architecture(
linear_architecture_3q,
create_3q_error_profile,
):
"""Test that IQMFakeBackend construction fails if depolarizing rates are
not provided for all couplings of the quantum architecture (QB1 -- QB2 -- QB3 here)"""
with pytest.raises(ValueError, match="The couplings specified for two-qubit gate"):
error_profile = create_3q_error_profile(
two_qubit_gate_depolarizing_error_parameters={"cz": {("QB1", "QB2"): 0.001}},
)
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_fake_backend_with_two_qubit_gate_depolarizing_errors_more_couplings_than_in_quantum_architecture(
linear_architecture_3q,
create_3q_error_profile,
):
"""Test that IQMFakeBackend construction fails if depolarizing rates are provided for
other couplings than specified in the quantum architecture"""
with pytest.raises(ValueError, match="The couplings specified for two-qubit gate"):
error_profile = create_3q_error_profile(
two_qubit_gate_depolarizing_error_parameters={
"cz": {("QB1", "QB2"): 0.001, ("QB2", "QB3"): 0.001, ("QB1", "QB3"): 0.001}
},
)
IQMFakeBackend(linear_architecture_3q, error_profile)
@pytest.mark.parametrize(
"param_name,param_value",
[
(
"single_qubit_gate_depolarizing_error_parameters",
{"wrong": {"QB1": 0.0001, "QB2": 0.0001, "QB3": 0}},
),
(
"two_qubit_gate_depolarizing_error_parameters",
{"wrong": {("QB1", "QB2"): 0.001, ("QB2", "QB3"): 0.001}},
),
],
)
def test_fake_backend_not_matching_quantum_architecture(
linear_architecture_3q,
create_3q_error_profile,
param_name: str,
param_value: dict,
):
"""Test that IQMFakeBackend construction fails if one qubit depolarizing rates are
refering to a gate not available in quantum architecture"""
with pytest.raises(
ValueError,
match=f"Gate `wrong` in `{param_name}` is not supported",
):
error_profile = create_3q_error_profile(**{param_name: param_value})
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_error_profile(linear_architecture_3q, create_3q_error_profile):
err_profile = create_3q_error_profile()
backend = IQMFakeBackend(linear_architecture_3q, err_profile)
assert backend.error_profile == err_profile
# Assert that error profile cannot be modified
backend.error_profile.t1s["QB1"] = backend.error_profile.t1s["QB1"] + 127
assert backend.error_profile == err_profile
def test_set_error_profile(backend, create_3q_error_profile):
with pytest.raises(NotImplementedError, match="Setting error profile of existing fake backend is not allowed."):
backend.error_profile = create_3q_error_profile()
def test_copy_with_error_profile(linear_architecture_3q, create_3q_error_profile):
err_profile = create_3q_error_profile()
backend = IQMFakeBackend(linear_architecture_3q, err_profile)
new_t1s = err_profile.t1s
new_t1s["QB1"] = new_t1s["QB1"] + 128
new_err_profile = create_3q_error_profile(t1s=new_t1s)
new_backend = backend.copy_with_error_profile(new_err_profile)
assert new_backend.error_profile == new_err_profile
def test_iqm_fake_backend_noise_model_instantiated(backend):
"""Test that creating a Fake Backend instantiates a Qiskit noise model"""
assert isinstance(backend.noise_model, NoiseModel)
def test_iqm_fake_backend_noise_model_basis_gates(backend):
"""Test that all operations named as part of the backend are utilizes in the noise_model"""
assert all(gates in backend.operation_names for gates in backend.noise_model.basis_gates)
def test_run_single_circuit(backend):
"""Test that the backend can be called with a circuit
or a list of circuits and returns a result."""
circuit = QuantumCircuit(1, 1)
circuit.measure(0, 0)
shots = 10
job = backend.run(circuit, qubit_mapping=None, shots=shots)
assert isinstance(job, JobV1)
assert job.result() is not None
# Should also work if the circuit is passed inside a list
job = backend.run([circuit], qubit_mapping=None, shots=shots)
assert isinstance(job, JobV1)
assert job.result() is not None
def test_error_on_empty_circuit_list(backend):
"""Test that calling run with an empty list of circuits raises a ValueError."""
with pytest.raises(ValueError, match="Empty list of circuits submitted for execution."):
backend.run([], qubit_mapping=None)
def test_noise_on_all_qubits(backend):
"""
Tests if noise is applied to all qubits of the device.
"""
noise_model = backend.noise_model
simulator_qubit_indices = list(range(backend.num_qubits))
noisy_qubits = noise_model.noise_qubits
assert simulator_qubit_indices == noisy_qubits
def test_noise_model_has_noise_terms(backend):
"""
Tests if the noise model has some noise terms, i.e., tests if the noise model
doesn't have no noise terms.
"""
noise_model = backend.noise_model
assert not noise_model.is_ideal()
def test_fake_backend_with_readout_errors_more_qubits_than_in_quantum_architecture(
linear_architecture_3q,
create_3q_error_profile,
):
"""Test that IQMFakeBackend construction fails if readout errors are provided for
other qubits than specified in the quantum architecture"""
with pytest.raises(ValueError, match="The qubits specified in readout errors"):
error_profile = create_3q_error_profile(
readout_errors={
"QB1": {"0": 0.02, "1": 0.03},
"QB2": {"0": 0.02, "1": 0.03},
"QB4": {"0": 0.02, "1": 0.03},
},
)
IQMFakeBackend(linear_architecture_3q, error_profile)
def test_noise_model_contains_all_errors(backend):
"""
Test that the noise model contains all necessary errors.
"""
assert set(backend.noise_model.noise_instructions) == {"r", "cz", "measure"}
# Assert that CZ gate error is applied independent of argument order in gate specification
assert set(backend.noise_model._local_quantum_errors["cz"].keys()) == set([(0, 1), (1, 0), (1, 2), (2, 1)])
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2024 Qiskit on IQM developers
#
# 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.
"""Testing the new move gate
"""
import pytest
from qiskit import QuantumCircuit
from qiskit.transpiler import TranspilerError
from iqm.qiskit_iqm.iqm_circuit import IQMCircuit
from iqm.qiskit_iqm.move_gate import MoveGate
from tests.utils import describe_instruction, get_transpiled_circuit_json
def test_move_gate_trivial_layout(new_architecture):
"""Tests that a trivial 1-to-1 layout is translated correctly."""
qc = QuantumCircuit(7)
qc.append(MoveGate(), [6, 0])
qc.cz(0, 3)
qc.cz(2, 0)
submitted_circuit = get_transpiled_circuit_json(qc, new_architecture)
assert [describe_instruction(i) for i in submitted_circuit.instructions] == ['move:6,0', 'cz:0,3', 'cz:2,0']
def test_move_gate_nontrivial_layout(new_architecture):
"""
For now only trivial layouts (1-to-1 mapping between virtual and physical qubits) are supported
if there are qubit connections that don't have all operations specified.
"""
qc = QuantumCircuit(7)
qc.append(MoveGate(), [3, 0])
with pytest.raises(TranspilerError):
get_transpiled_circuit_json(qc, new_architecture)
def test_mapped_move_qubit(new_architecture):
"""
Test that other qubit indices can be used if we manually calculate a working
initial layout using the IQMMoveLayout() layout pass.
"""
qc = QuantumCircuit(7)
qc.cz(0, 2)
qc.append(MoveGate(), [3, 0])
submitted_circuit = get_transpiled_circuit_json(qc, new_architecture, create_move_layout=True)
assert [describe_instruction(i) for i in submitted_circuit.instructions] == ['cz:0,2', 'move:6,0']
def test_mapped_move_qubit_and_resonator(new_architecture):
qc = IQMCircuit(7)
# Now resonator is 2, move qubit 5, so need to switch 2<->0, 5<->6
qc.cz(2, 4)
qc.move(5, 2)
qc.cz(2, 1)
qc.cz(2, 0)
qc.move(5, 2)
qc.h(5)
submitted_circuit = get_transpiled_circuit_json(qc, new_architecture, create_move_layout=True)
assert [describe_instruction(i) for i in submitted_circuit.instructions] == [
'cz:0,4',
'move:6,0',
'cz:0,1',
'cz:0,2',
'move:6,0',
'prx:6',
'prx:6',
]
def test_cant_layout_two_resonators(new_architecture):
qc = QuantumCircuit(7)
qc.append(MoveGate(), [0, 6])
qc.append(MoveGate(), [3, 6])
with pytest.raises(TranspilerError):
get_transpiled_circuit_json(qc, new_architecture, create_move_layout=True)
def test_cant_layout_two_move_qubits(new_architecture):
qc = QuantumCircuit(7)
qc.append(MoveGate(), [0, 6])
qc.append(MoveGate(), [0, 4])
with pytest.raises(TranspilerError):
get_transpiled_circuit_json(qc, new_architecture, create_move_layout=True)
def test_transpiled_circuit(new_architecture):
"""
Tests that a circuit with a move operation is transpiled correctly into JSON.
"""
qc = IQMCircuit(7, 2)
qc.move(6, 0)
qc.cz(0, 3)
qc.h(6)
qc.h(4)
qc.cz(4, 0)
qc.barrier()
qc.move(6, 0)
qc.measure(6, 0)
qc.measure(3, 1)
submitted_circuit = get_transpiled_circuit_json(qc, new_architecture, seed_transpiler=1)
assert [describe_instruction(i) for i in submitted_circuit.instructions] == [
# h(4) is moved before the move gate
'prx:4',
'prx:4',
# move(6, 0)
'move:6,0',
# cz(0, 3)
'cz:0,3',
# cz(4, 0) is optimized before h(6)
'cz:4,0',
# h(6)
'prx:6',
'prx:6',
# barrier()
'barrier:0,1,2,3,4,5,6',
# move (6, 0)
'move:6,0',
# measurements
'measure:6',
'measure:3',
]
|
https://github.com/quantumjim/Qiskit-PyConDE
|
quantumjim
|
%matplotlib notebook
import pew # setting up tools for the pewpew
from microqiskit import QuantumCircuit, simulate # setting up tools for quantum
pew.init() # initialize the game engine...
screen = pew.Pix() # ...and the screen
qc = QuantumCircuit(2,2) # create an empty circuit with two qubits and two output bits
# create a circuit with the required measurements, so we can add them in easily
meas = QuantumCircuit(2,2)
meas.measure(0,0)
meas.measure(1,1)
# loop over the squares centered on (1,2) and (6,2) and make all dim
for (X,Y) in [(1,2),(6,2)]:
for dX in [+1,0,-1]:
for dY in [+1,0,-1]:
screen.pixel(X+dX,Y+dY,2)
for (X,Y) in [(1,2),(6,2)]:
screen.pixel(X,Y,0) # turn off the center pixels of the squares
old_keys = 0
while True: # loop which checks for user input and responds
# look for and act upon key presses
keys = pew.keys() # get current key presses
if keys!=0 and keys!=old_keys:
if keys&pew.K_UP:
qc.x(0) # x for qubit 0 when UP is pressed
if keys&pew.K_LEFT:
qc.x(1) # x for qubit 1 when LEFT is pressed
old_keys = keys
# execute the circuit and get a single sample of memory
m = simulate(qc+meas,shots=1,get='memory')
# turn the pixel (1,2) on or off depending on whether the first bit value is 1 or 0
if m[0][0]=='1':
screen.pixel(1,2,3)
else:
screen.pixel(1,2,0)
# do the same for pixel (6,2)
if m[0][1]=='1':
screen.pixel(6,2,3)
else:
screen.pixel(6,2,0)
pew.show(screen) # update screen to display the above changes
pew.tick(1/6) # pause for a sixth of a second
import pew # setting up tools for the pewpew
from microqiskit import QuantumCircuit, simulate # setting up tools for quantum
pew.init() # initialize the game engine...
screen = pew.Pix() # ...and the screen
# create an empty circuit with two qubits and two output bits
qc = QuantumCircuit(2,2)
cnot = QuantumCircuit(2,2)
cnot.cx(0,1)
# create a circuit with the required measurements, so we can add them in easily
meas = QuantumCircuit(2,2)
meas.measure(0,0)
meas.measure(1,1)
# loop over the square centered on (1,2) and make all dim
for (X,Y) in [(1,2),(6,2)]:
for dX in [+1,0,-1]:
for dY in [+1,0,-1]:
screen.pixel(X+dX,Y+dY,2)
for (X,Y) in [(1,2),(6,2)]:
screen.pixel(X,Y,0) # turn off the center pixels of the squares
old_keys = 0
while True: # loop which checks for user input and responds
# look for and act upon key presses
keys = pew.keys() # get current key presses
if keys!=0 and keys!=old_keys:
if keys&pew.K_UP:
qc.x(0) # x for qubit 0 when UP is pressed
if keys&pew.K_LEFT:
qc.x(1) # x for qubit 1 when LEFT is pressed
old_keys = keys
# execute the circuit and get a single sample of memory
m = simulate(qc+meas,shots=1,get='memory')
# turn the pixel (1,2) on or off depending on whether the first bit value is 1 or 0
if m[0][0]=='1':
screen.pixel(1,2,3)
else:
screen.pixel(1,2,0)
# do the same for pixel (6,2)
if m[0][1]=='1':
screen.pixel(6,2,3)
else:
screen.pixel(6,2,0)
m = simulate(qc+cnot+meas,shots=1,get='memory')
xor = m[0][0]
if xor=='0':
for (X,Y) in [(3,2),(4,2)]:
screen.pixel(X,Y,0)
else:
for (X,Y) in [(3,2),(4,2)]:
screen.pixel(X,Y,3)
pew.show(screen) # update screen to display any changes
pew.tick(1/6) # pause for a sixth of a second
|
https://github.com/quantumjim/Qiskit-PyConDE
|
quantumjim
|
run controller.py
|
https://github.com/quantumjim/Qiskit-PyConDE
|
quantumjim
|
%matplotlib notebook
import pew # setting up tools for the pewpew
pew.init() # initialize the game engine...
screen = pew.Pix() # ...and the screen
# fill the screen with medium brightness pixels
for X in range(8):
for Y in range(8):
screen.pixel(X,Y,2)
B = 3 # set brightness
screen.pixel(6,6,B) # put a bright pixel at (6,6)
pew.show(screen) # update screen to display the above changes
pew.tick(5) # pause for 5 seconds before quitting
import pew # setting up tools for the pewpew
pew.init() # initialize the game engine...
screen = pew.Pix() # ...and the screen
# fill the screen with medium brightness pixels
for X in range(8):
for Y in range(8):
screen.pixel(X,Y,2)
B = 3 # set initial brightness
pressing = False
while True: # loop which checks for user input and responds
keys = pew.keys() # get current key presses
if not pressing:
if keys&pew.K_X: # pressing X turns off the program
break
if keys&pew.K_UP: # if UP is pressed, increase brightness of pixel at at (6,6)
B = min(B+1,3)
if keys&pew.K_DOWN: # if DOWN is pressed, decrease brightness of pixel at at (6,6)
B = max(B-1,0)
if keys:
pressing = True
else:
if not keys:
pressing = False
screen.pixel(6,6,B) # put a pixel at (6,6) with current brightness
pew.show(screen) # update screen to display the above changes
pew.tick(1/6) # pause for a sixth of a second
import pew # setting up tools for the pewpew
from microqiskit import QuantumCircuit, simulate # setting up tools for quantum
pew.init() # initialize the game engine...
screen = pew.Pix() # ...and the screen
# fill the screen with dim pixels
for X in range(8):
for Y in range(8):
screen.pixel(X,Y,2)
pew.show(screen) # update screen to display the above changes
qc = QuantumCircuit(1,1) # create an empty single qubit circuit
# create a circuit that measures the qubit in the z basis
m_z = QuantumCircuit(1,1)
m_z.measure(0,0)
pressing = False
while True: # loop which checks for user input and responds
keys = pew.keys() # get current key presses
if not pressing:
if keys&pew.K_X: # pressing X turns off the program
break
if keys&pew.K_UP: # if UP is pressed, add an x gate
qc.x(0)
if keys&pew.K_DOWN: # if DOWN is pressed, add an h gate
qc.h(0)
if keys:
pressing = True
else:
if not keys:
pressing = False
# get the output from the current circuit
full_circuit = qc + m_z
bit = simulate(full_circuit,shots=1,get='memory')[0]
# set the brightness of 6,6 according to the output
if bit=='1':
B = 3
else:
B = 0
screen.pixel(6,6,B) # put a pixel at (6,1) with current brightness
pew.show(screen) # update screen to display the above changes
pew.tick(1/6) # pause for a sixth of a second
import pew # setting up tools for the pewpew
from microqiskit import QuantumCircuit, simulate # setting up tools for quantum
from math import pi
pew.init() # initialize the game engine...
screen = pew.Pix() # ...and the screen
# fill the screen with dim pixels
for X in range(8):
for Y in range(8):
screen.pixel(X,Y,2)
pew.show(screen) # update screen to display the above changes
qc = QuantumCircuit(1,1) # create an empty single qubit circuit
# create a circuit that measures the qubit in the z basis
m_z = QuantumCircuit(1,1)
m_z.measure(0,0)
# create a circuit that measures the qubit in the x basis
m_x = QuantumCircuit(1,1)
m_x.h(0)
m_x.measure(0,0)
basis = 'z' # set initial measurement basis
pressing = False
while True: # loop which checks for user input and responds
keys = pew.keys() # get current key presses
if not pressing:
if keys&pew.K_X: # pressing X turns off the program
break
if keys&pew.K_UP: # if UP is pressed, add an x gate
qc.x(0)
if keys&pew.K_DOWN: # if DOWN is pressed, add an h gate
qc.h(0)
if keys&pew.K_O:
basis = (basis=='z')*'x' + (basis=='x')*'z'
if keys:
pressing = True
else:
if not keys:
pressing = False
# get the output from the current circuit
if basis=='z':
full_circuit = qc + m_z
elif basis=='x':
full_circuit = qc + m_x
bit = simulate(full_circuit,shots=1,get='memory')[0]
# set the brightness of 6,6 according to the output
if bit=='1':
B = 3
else:
B = 0
if basis=='z':
screen.pixel(6,6,B)
screen.pixel(1,1,2)
elif basis=='x':
screen.pixel(6,6,2)
screen.pixel(1,1,B)
pew.show(screen) # update screen to display the above changes
pew.tick(1/6) # pause for a sixth of a second
import pew # setting up tools for the pewpew
from microqiskit import QuantumCircuit, simulate # setting up tools for quantum
from math import pi
pew.init() # initialize the game engine...
screen = pew.Pix() # ...and the screen
# fill the screen with dim pixels
for X in range(8):
for Y in range(8):
screen.pixel(X,Y,2)
pew.show(screen) # update screen to display the above changes
qc = QuantumCircuit(1,1) # create an empty single qubit circuit
# create a circuit that measures the qubit in the z basis
m_z = QuantumCircuit(1,1)
m_z.measure(0,0)
# create a circuit that measures the qubit in the x basis
m_x = QuantumCircuit(1,1)
m_x.h(0)
m_x.measure(0,0)
# create a circuit that measures the qubit in the y basis
m_y = QuantumCircuit(1,1)
m_y.rx(pi/2,0)
m_y.measure(0,0)
basis = 'z' # set initial measurement basis
pressing = False
while True: # loop which checks for user input and responds
keys = pew.keys() # get current key presses
if not pressing:
if keys&pew.K_X: # pressing X turns off the program
break
if keys&pew.K_UP: # if UP is pressed, add an x gate
qc.x(0)
if keys&pew.K_DOWN: # if DOWN is pressed, add an h gate
qc.h(0)
if keys&pew.K_LEFT: # if LEFT is pressed, add a sqrt(x) gate
qc.rx(pi/2,0)
if keys&pew.K_O:
basis = (basis=='z')*'x' + (basis=='x')*'y'+ (basis=='y')*'z'
if keys:
pressing = True
else:
if not keys:
pressing = False
# get the output from the current circuit
if basis=='z':
full_circuit = qc + m_z
elif basis=='x':
full_circuit = qc + m_x
elif basis=='y':
full_circuit = qc + m_y
bit = simulate(full_circuit,shots=1,get='memory')[0]
# set the brightness of 6,6 according to the output
if bit=='1':
B = 3
else:
B = 0
if basis=='z':
screen.pixel(6,6,B)
screen.pixel(6,1,2)
screen.pixel(1,1,2)
elif basis=='x':
screen.pixel(6,6,2)
screen.pixel(6,1,2)
screen.pixel(1,1,B)
elif basis=='y':
screen.pixel(6,6,2)
screen.pixel(6,1,B)
screen.pixel(1,1,2)
pew.show(screen) # update screen to display the above changes
pew.tick(1/6) # pause for a sixth of a second
%matplotlib inline
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Set up tools for visualizing the Bloch sphere
from math import pi
def get_bloch(qc):
# create a circuit that measures the qubit in the z basis
m_z = QuantumCircuit(1,1)
m_z.measure(0,0)
# create a circuit that measures the qubit in the x basis
m_x = QuantumCircuit(1,1)
m_x.h(0)
m_x.measure(0,0)
# create a circuit that measures the qubit in the y basis
m_y = QuantumCircuit(1,1)
m_y.rx(pi/2,0)
m_y.measure(0,0)
shots = 2**14 # number of samples used for statistics
bloch_vector = []
# look at each possible measurement
for measure_circuit in [m_x, m_y, m_z]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
counts = execute(qc+measure_circuit,Aer.get_backend('qasm_simulator'),shots=shots).result().get_counts()
# calculate the probabilities for each bit value
probs = {}
for output in ['0','1']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
# the bloch vector needs the different between these values
bloch_vector.append( probs['0'] - probs['1'] )
return bloch_vector
qc = QuantumCircuit(1,1)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.x(0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.h(0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.x(0)
qc.h(0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.rx(-pi/2,0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.rx(pi/2,0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.rx(pi*1/8,0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.rx(pi*2/8,0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.rx(pi*3/8,0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.rx(pi*4/8,0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.rx(pi*4/8,0)
qc.rz(pi*1/8,0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.rx(pi*4/8,0)
qc.rz(pi*2/8,0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.rx(pi*4/8,0)
qc.rz(pi*3/8,0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.rx(pi*4/8,0)
qc.rz(pi*4/8,0)
plot_bloch_vector(get_bloch(qc))
qc = QuantumCircuit(1,1)
qc.rx(pi*4/8,0)
qc.rz(pi*4/8,0)
qc.ry(-pi*1/8,0)
plot_bloch_vector(get_bloch(qc))
|
https://github.com/quantumjim/Qiskit-PyConDE
|
quantumjim
|
%matplotlib notebook
# define a function that determines a brightness for any given point
# uses a seed that is a list of four numbers
def get_brightness(x,y,qc,seed):
qc.data.clear() # empty the circuit
# perform rotations, whose angles depend on x and y
qc.rx( (1/8)*(seed[0]*x-seed[1]*y)*pi ,0)
qc.ry( (1/16)*(seed[2]*x+seed[3]*y)*pi ,0)
# calculate probability for outcome 1
qc.measure(0,0)
p = simulate(qc,shots=1000,get='counts')['1']/1000
# return brightness depending on this probability
# the chosen values here are fairly arbitrarily
if p>0.7:
if p<0.8:
return 1
elif p<0.9:
return 2
else:
return 3
else:
return 0
from microqiskit import QuantumCircuit, simulate
from math import pi
from random import random
seed = [random() for _ in range(4)]
# initialize circuit used by the function
qc = QuantumCircuit(1,1)
for y in range(50):
line = ''
for x in range(50):
B = get_brightness(x,y,qc,seed)
char = (B==0)*'▓▓' + (B==1)*'▒▒' + (B==2)*'░░' + (B==3)*' '
line += char
print(line)
###########################################################
# Replace this comment with the `get_brightness` function #
# if running anywhere other than this notebook #
###########################################################
import pew
from microqiskit import QuantumCircuit, simulate
from math import pi
from random import random
pew.init()
screen = pew.Pix()
# initialize circuit
qc = QuantumCircuit(1,1)
# set a random seed, composed of four numbers
seed = [(2*(random()<0.5)-1)*(1+random())/2 for _ in range(4)]
# coordinate of the current screen
X,Y = 0,0
# loop to allow player to move half a screen
while True:
# arrow keys move to neighbouring screens
keys = pew.keys()
if keys!=0:
if keys&pew.K_UP:
Y -= 4
if keys&pew.K_DOWN:
Y += 4
if keys&pew.K_LEFT:
X -= 4
if keys&pew.K_RIGHT:
X += 4
# loop over all points on the screen, and display the brightness
for x in range(8):
for y in range(8):
B = get_brightness(x+X,y+Y,qc,seed) # coordinate of the player is accounted for also
screen.pixel(x,y,B)
pew.show(screen)
pew.tick(1/6)
from qiskit import QuantumCircuit, execute, Aer
from math import pi
from random import random
###########################################################
# This is the function to edit #
###########################################################
# define a function that determines a brightness for any given point
# uses a seed that is a list of four numbers
def get_brightness(x,y,qc,seed):
qc.data.clear() # empty the circuit
# perform rotations whose angles depend on x and y
qc.rx((1/8)*(seed[0]*x-seed[1]*y)*pi,0)
qc.ry((1/8)*(seed[2]*x+seed[3]*y**2)*pi+pi,0)
# calculate probability for outcome 1
qc.measure(0,0)
try:
p = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000).result().get_counts()['1']/1000
except:
p = 0
# return brightness depending on this probability
# the chosen values here are fairly arbitrary
if p>0.7:
if p<0.8:
return 1
elif p<0.9:
return 2
else:
return 3
else:
return 0
###########################################################
# The following uses the above function to create a 50x50 map, and print it in ASCII
seed = [random() for _ in range(4)]
# initialize circuit used by the function
qc = QuantumCircuit(1,1)
for y in range(50):
line = ''
for x in range(50):
B = get_brightness(x,y,qc,seed)
char = (B==0)*'▓▓' + (B==1)*'▒▒' + (B==2)*'░░' + (B==3)*' '
line += char
print(line)
|
https://github.com/rubenandrebarreiro/ibm-qiskit-global-summer-school-2023
|
rubenandrebarreiro
|
# required import of libraries and modules
# import array to latex converter from
# IBM's Qiskit visualization module
from qiskit.visualization import array_to_latex
# import state-vector and random state-vector from
# IBM's Qiskit quantum information module
from qiskit.quantum_info import Statevector, random_statevector
# import abstract operator and pauli operator from
# IBM's Qiskit quantum information's operators module
from qiskit.quantum_info.operators import Operator, Pauli
# import quantum circuit from IBM's Qiskit
from qiskit import QuantumCircuit
# import hadamard gate and CX/CNOT gate from IBM's Qiskit
from qiskit.circuit.library import HGate, CXGate
# import numpy
import numpy as np
# define the column-vector for |0>
ket0 = [[1],[0]]
# convert the column-vector |0> to latex
array_to_latex(ket0)
# define the row-vector for <0|
bra0 = [1, 0]
# convert the row-vector <0| to latex
array_to_latex(bra0)
# put your answer answer here for the column-vector |1>
ket1 = [ [0], [1] ]
# put your answer here for the row-vector <1|
bra1 = [0, 1]
# import the grader for the exercise 1 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex1
# grade the exercise 1 of the lab 1
grade_lab1_ex1([ket1, bra1])
# create a state-vector for the row-vector <0|
sv_bra0 = Statevector(bra0)
# show the object of the state-vector for the row-vector <0|
sv_bra0
# draw the state-vector for the row-vector <0| in latex
sv_bra0.draw("latex")
# create a complex state-vector for multiple qubits
sv_eq = Statevector( [ 1/2, 3/4, 4/5, 6/8 ] )
# draw the complex state-vector created before in latex
sv_eq.draw("latex")
# check if the complex state-vector created before
# is valid for a quantum state (i.e., if it is normalised)
sv_eq.is_valid()
# create your valid statevector here
sv_valid = Statevector( [ 1/2, 1/2, 1/2, 1/2 ] )
# import the grader for the exercise 2 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex2
# grade the exercise 2 of the lab 1
grade_lab1_ex2(sv_valid)
# create an operator for the row-vector <0|
op_bra0 = Operator(bra0)
# show the object of the operator for the row-vector <0|
op_bra0
# create an operator for the column-vector |0>
op_ket0 = Operator(ket0)
# apply the tensor product of the operator
# created before to the operator applied to
# the row-vector <0|
op_bra0.tensor(op_ket0)
# compute the inner product between the row-vector <0|
# and the column-vector |0>, as a bra-ket product <0|0>
# note: this operator is also used to check if
# two pure quantum states overlap (i.e., are equal)
braket = np.dot(op_bra0, op_ket0)
# convert the result of the inner product
# computed before to latex
array_to_latex(braket)
# compute the outer product between the column-vector |0>
# and the column-vector <0|, as a ket-bra product |0><0|
ketbra = np.outer(ket0,bra0)
# convert the result of the outer product
# computed before to latex
array_to_latex(ketbra)
# definition of the operators for the row-vectors (bra vectors)
# <0| and <1|, and the column-vectors (ket vectors) |0> and |1>
op_bra0 = Operator(bra0)
op_bra1 = Operator(bra1)
op_ket0 = Operator(ket0)
op_ket1 = Operator(ket1)
# definition of the inner products (bra-ket products)
# put your answer for the inner product
# (bra-ket product) <1|0> here
bra1ket0 = np.dot(op_bra1, op_ket0)
# put your answer for the inner product
# (bra-ket product) <0|1> here
bra0ket1 = np.dot(op_bra0, op_ket1)
# put your answer for the inner product
# (bra-ket product) <1|1> here
bra1ket1 = np.dot(op_bra1, op_ket1)
# definition of the outer products (ket-bra products)
# put your answer for the outer product
# (ket-bra product) |1><0| here
ket1bra0 = np.outer(op_ket1, op_bra0)
# put your answer for the outer product
# (ket-bra product) |0><1| here
ket0bra1 = np.outer(op_ket0, op_bra1)
# put your answer for the outer product
# (ket-bra product) |1><1| here
ket1bra1 = np.outer(op_ket1, op_bra1)
# import the grader for the exercise 3 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex3
# grade the exercise 3 of the lab 1
grade_lab1_ex3( [ bra1ket0, bra0ket1, bra1ket1, ket1bra0, ket0bra1, ket1bra1 ] )
# two quantum states are orthogonal if
# they are completely opposite and
# never overlap with each other
# (i.e., when their inner product is equal to 0)
# <0|1> = <1|0> = 0, the quantum states |0> and |1>
# never overlap with each other and are completely opposite,
# or in other words, they are orthogonal
# add or remove your answer from this list
answer = ["a"]
# import the grader for the exercise 4 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex4
# grade the exercise 4 of the lab 1
grade_lab1_ex4(answer)
# create an operator for a single qubit system defined as
# m_1 = [ [1, 1],
# [0, 0] ], which represents the f1 = constant-0
# deterministic operation
m1 = Operator( [ [1, 1], [0, 0] ] )
# convert the operator created before to latex
array_to_latex(m1)
# create an operator for a single qubit system defined as
# m_3 = [ [0, 1],
# [1, 0] ], which represents the f3 = bit flip / not
# deterministic operation
m3 = Operator( [ [0, 1], [1,0] ] )
# convert the operator created before to latex
array_to_latex(m3)
# represent in latex the result of applying
# the operator m1 to the column-vector (ket vector) |0>
array_to_latex(m1@ket0)
# create an operator for a single qubit system defined as
# m_2 = [ [1, 0],
# [0, 1] ], which represents the f2 = identity
# deterministic operation
m2 = Operator( [ [1, 0], [0, 1] ] )
# create an operator for a single qubit system defined as
# m_4 = [ [0, 0],
# [1, 1] ], which represents the f4 = constant-1
# deterministic operation
m4 = Operator( [ [0, 0], [1, 1] ] )
# import the grader for the exercise 5 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex5
# grade the exercise 5 of the lab 1
grade_lab1_ex5( [ m2, m4 ] )
# create a CX/CNOT quantum gate as an operator
cnot = CXGate()
# convert the operator created before to latex
array_to_latex(cnot)
# check if the operator for a single qubit system defined as
# m_3 = [ [0, 1],
# [1, 0] ], which represents the f3 = bit flip / not
# deterministic operation, is unitary
m3.is_unitary()
# create a random operator for multiple qubit system
random = Operator( np.array(
[ [ 0.50778085 - 0.44607116j, -0.1523741 + 0.14128434j,
0.44607116 + 0.50778085j, -0.14128434 - 0.1523741j ],
[ 0.16855994 + 0.12151822j, 0.55868196 + 0.38038841j,
-0.12151822 + 0.16855994j, -0.38038841 + 0.55868196j ],
[ 0.50778085 - 0.44607116j, -0.1523741 + 0.14128434j,
-0.44607116 - 0.50778085j, 0.14128434 + 0.1523741j ],
[ 0.16855994 + 0.12151822j, 0.55868196 + 0.38038841j,
0.12151822 - 0.16855994j, 0.38038841-0.55868196j ] ] ) )
# check if the random operator for multiple qubit system is random
random.is_unitary()
# create your non-unitary operator here
non_unitary_op = Operator( [ [1, 0], [1, 1] ] )
# import the grader for the exercise 6 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex6
# grade the exercise 6 of the lab 1
grade_lab1_ex6(non_unitary_op)
# create the Pauli-X (bit flip / not) quantum gate
pauli_x = Pauli("X")
# convert the quantum gate created before to latex
array_to_latex(pauli_x)
# create the Pauli-Y quantum gate
pauli_y = Pauli("Y")
# convert the quantum gate created before to latex
array_to_latex(pauli_y)
# create the Pauli-Z (phase flip) quantum gate
pauli_z = Pauli("Z")
# convert the quantum gate created before to latex
array_to_latex(pauli_z)
# convert the Pauli-X (bit flip / not)
# quantum gate to an operator
op_x = Operator(pauli_x)
# show the Pauli-X (bit flip / not)
# quantum gate converted to an operator
op_x
# apply the inner product between the Pauli-X (bit flip / not) operator
# the quantum state of the column-vector (ket vector) |0>, resulting to
# a new quantum state of the column-vector (ket vector) |1>
op_new = np.dot(op_x ,ket0)
# convert the resulting new operator to latex
array_to_latex(op_new)
# do your operations here
# convert the Pauli-Z (phase flip)
# quantum gate to an operator
op_z = Operator(pauli_z)
# apply the inner product between the Pauli-Z (phase flip) operator
# the quantum state of the column-vector (ket vector) |1>, resulting to
# a new quantum state of the column-vector (ket vector) -|1>
result = np.dot(op_z ,ket1)
# convert the resulting new operator to latex
array_to_latex(result)
# import the grader for the exercise 7 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex7
# grade the exercise 7 of the lab 1
grade_lab1_ex7(result)
# create the Hadamard quantum gate
hadamard = HGate()
# convert the quantum gate created before to latex
array_to_latex(hadamard)
# convert the Hadamard quantum gate to an operator
op_h = Operator(hadamard)
# show the Hadamard quantum gate
# converted to an operator
print(op_h)
# check if the Hadamard quantum gate
# converted to an operator is unitary
op_h.is_unitary()
# create a quantum circuit for two qubits
# and to implement a Bell state
bell = QuantumCircuit(2)
# apply a Hadamard gate to
# the 1st qubit of the quantum circuit
bell.h(0)
# apply a CX/CNOT gate to
# the 1st and 2nd qubits of the quantum circuit
bell.cx(0, 1)
# draw the quantum circuit implementing the Bell state
bell.draw(output="mpl")
# converting the quantum circuit
# implementing the Bell state to an operator
bell_op = Operator(bell)
# convert the quantum operator representing
# the quantum circuit created before to latex
array_to_latex(bell_op)
# create a quantum circuit for three qubits
# and to implement a GHZ state
ghz = QuantumCircuit(3)
##############################
# add gates to your quantum circuit here
# apply a Hadamard gate to
# the quantum circuit, on the 1st qubit
ghz.h(0)
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on 1st qubit
# and target on 2nd qubit
ghz.cx(0, 1)
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on 2nd qubit
# and target on 3rd qubit
ghz.cx(1, 2)
##############################
# draw the quantum circuit implementing the GHZ state
ghz.draw(output="mpl")
# import the grader for the exercise 8 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex8
# grade the exercise 8 of the lab 1
grade_lab1_ex8(ghz)
# create the state-vector for
# the quantum superposition state |+>
plus_state = Statevector.from_label("+")
# convert the state-vector created before to latex
plus_state.draw("latex")
# show the state-vector |+> created before
plus_state
# show the probabilities of the possible
# classical outcomes/states resulting
# from measuring the quantum superposition state |+>
plus_state.probabilities_dict()
# run this cell multiple times to show collapsing
# into one state or the other (i.e., 0 or 1)
# for a number of trials equal to 5
for _ in range(5):
# measure the quantum superposition state |+>
res = plus_state.measure()
# print the result of the measurement of
# the quantum superposition state |+>
print(res)
# create a quantum circuit for one qubit and one bit,
# to implement a |+> quantum superposition state
qc = QuantumCircuit(1, 1)
# apply a Hadamard gate to
# the quantum circuit, on the 1st qubit
qc.h(0)
# measure the 1st qubit of the quantum circuit
# to the respective 1st bit of the same
qc.measure(0, 0)
# draw the quantum circuit for one qubit and one bit,
# implementing a |+> quantum superposition state
qc.draw(output="mpl")
# create the state-vector for the Bell State |phi^+>
sv_bell = Statevector( [ np.sqrt(1 / 2), 0, 0, np.sqrt(1 / 2) ] )
# draw the state-vector for the Bell State |phi^+>
sv_bell.draw("latex")
sv_bell.probabilities_dict()
# creation of the three quantum states in the Bell basis,
# namely, |psi^+⟩, |psi^-⟩, and |phi^-⟩
# create a statevector for |psi^+⟩ here
sv_psi_plus = Statevector( [ 0, np.sqrt(1 / 2), np.sqrt(1 / 2), 0 ] )
# find the measurement probabilities for |psi^+⟩ here
prob_psi_plus = sv_psi_plus.probabilities_dict()
# create a statevector for |psi^-⟩ here
sv_psi_minus = Statevector( [ 0, np.sqrt(1 / 2), -1 * np.sqrt(1 / 2), 0 ] )
# find the measurement probabilities for |psi^−⟩ here
prob_psi_minus = sv_psi_minus.probabilities_dict()
# create a statevector for |phi^-⟩ here
sv_phi_minus = Statevector( [ np.sqrt(1 / 2), 0, 0, -1 * np.sqrt(1 / 2) ] )
# find the measurement probabilities for |phi^-⟩ here
prob_phi_minus = sv_phi_minus.probabilities_dict()
# import the grader for the exercise 9 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex9
# grade the exercise 9 of the lab 1
grade_lab1_ex9([prob_psi_plus, prob_psi_minus, prob_phi_minus])
# create a quantum circuit for two qubits,
# to implement a quantum fourier transform
qft = QuantumCircuit(2)
##############################
# add gates to your quantum circuit here
# apply an Hadamard gate to
# the quantum circuit, on the 2nd qubit
qft.h(1)
# apply a Controlled-Phase (CP) gate to
# the quantum circuit acccording to
# a theta angle, with control on
# the 1st qubit and target on the 2nd qubit
qft.cp( np.pi/2, 0, 1 )
# apply an Hadamard gate to
# the quantum circuit, on the 1st qubit
qft.h(0)
# apply a SWAP gate to
# the quantum circuit,
# between the 1st qubit
# and the 2nd qubit
qft.swap(0, 1)
##############################
# draw the quantum circuit for two qubits,
# implementing a quntum fourier transform
qft.draw(output="mpl")
# import the grader for the exercise 10 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex10
# grade the exercise 10 of the lab 1
grade_lab1_ex10(qft)
# create an operator U from the quantum circuit of
# the quantum fourier transform created before
U = Operator(qft)
# convert the quantum operator U representing
# the quantum circuit created before to latex
array_to_latex(U)
# import the IBM's Qiskit Jupyter Tools
import qiskit.tools.jupyter
# show the table of the IBM's Qiskit version
%qiskit_version_table
|
https://github.com/rubenandrebarreiro/ibm-qiskit-global-summer-school-2023
|
rubenandrebarreiro
|
# required import of libraries and modules
# import quantum circuit from IBM's Qiskit circuit module
from qiskit.circuit import QuantumCircuit
# import estimator and sample
# from IBM's Qiskit primitives module
from qiskit.primitives import Estimator, Sampler
# import Sparse Pauli operator
# from IBM's Qiskit quantum information module
from qiskit.quantum_info import SparsePauliOp
# import histogram plotting
# from IBM's Qiskit visualization module
from qiskit.visualization import plot_histogram
# import numpy
import numpy as np
# import plotting from Matplotlib's pyplot module
import matplotlib.pyplot as plt
# OPTIONAL: use the dark background style
# for the plotting from Matplotlib's pyplot module
plt.style.use("dark_background")
# create an excited state |1>
# create a quantum circuit for one qubit
# and to implement an excited state |1>
qc_1 = QuantumCircuit(1)
# apply a Pauli-X (bit flip / not) gate to
# the quantum circuit, on the 1st qubit
qc_1.x(0)
# draw the quantum circuit implementing
# the excited state |1>
qc_1.draw("mpl")
# create quantum superposition state |+>
# create a quantum circuit for one qubit
# and to implement a quantum superposition state |+>
qc_plus = QuantumCircuit(1)
# apply a Hadamard gate to
# the quantum circuit, on the 1st qubit
qc_plus.h(0)
# draw the quantum circuit implementing
# the quantum superposition state |+>
qc_plus.draw("mpl")
# measure all the qubits of
# the quantum circuit implementing
# an excited state |1>
qc_1.measure_all()
# measure all the qubits of
# the quantum circuit implementing
# a quantum superposition state |+>
qc_plus.measure_all()
# create a Sampler object
sampler = Sampler()
# create a job for the quantum circuit implementing
# an excited state |1>, running the Sampler
job_1 = sampler.run(qc_1)
# create a job for the quantum circuit implementing
# a quantum superposition state |+>, running the Sampler
job_plus = sampler.run(qc_plus)
# retrieve the quasi-distribution of
# the job for the quantum circuit
# implementing an excited state |1>
quasi_dists_ket_1 = job_1.result().quasi_dists
# fix the legend issue for
# the quasi-distribution of the outcome 0
quasi_dists_ket_1[0][0] = 1e-20
# show the quasi-distribution of
# the job for the quantum circuit
# implementing an excited state |1>
quasi_dists_ket_1
# retrieve the quasi-distribution of
# the job for the quantum circuit implementing
# a quantum superposition state |+>
quasi_dists_ket_plus = job_plus.result().quasi_dists
# show the quasi-distribution of
# the job for the quantum circuit
# implementing a quantum superposition state |+>
quasi_dists_ket_plus
# create the legend for the two quantum states
# created before, namely the excited state |1> and
# the quantum superposition state |+>
legend = ["Excited State", "Plus State"]
# plot the histogram for the quasi-distributions
# for the two quantum states created before,
# namely the excited state |1> and
# the quantum superposition state |+>
plot_histogram( [ quasi_dists_ket_1[0], quasi_dists_ket_plus[0] ],
legend=legend, title="Measurement Results\n" )
# remove all the qubits' measurements of
# the quantum circuit implementing
# an excited state |1>
qc_1.remove_final_measurements()
# remove all the qubits' measurements of
# the quantum circuit implementing
# a quantum superposition state |+>
qc_plus.remove_final_measurements()
# prepare the 1st qubit of the quantum circuit
# implementing an excited state |1>,
# for the X-Basis measurement,
# applying a Hadamard gate
qc_1.h(0)
# prepare the 1st qubit of the quantum circuit
# implementing a quantum superposition state |+>,
# for the X-Basis measurement,
# applying a Hadamard gate
qc_plus.h(0)
# measure all the qubits of
# the quantum circuit implementing
# an excited state |1>
qc_1.measure_all()
# measure all the qubits of
# the quantum circuit implementing
# a quantum superposition state |+>
qc_plus.measure_all()
# create a Sampler object
sampler = Sampler()
# create a job for the quantum circuit implementing
# an excited state |1>, running the Sampler
job_1 = sampler.run(qc_1)
# create a job for the quantum circuit implementing
# a quantum superposition state |+>, running the Sampler
job_plus = sampler.run(qc_plus)
# retrieve the quasi-distribution of
# the job for the quantum circuit
# implementing an excited state |1>,
# measured in the X-Basis
quasi_dists_ket_1 = job_1.result().quasi_dists
# show the quasi-distribution of
# the job for the quantum circuit
# implementing an excited state |1>,
# measured in the X-Basis
quasi_dists_ket_1
# retrieve the quasi-distribution of
# the job for the quantum circuit
# implementing a quantum superposition state |+>,
# measured in the X-Basis
quasi_dists_ket_plus = job_plus.result().quasi_dists
# fix the legend issue for
# the quasi-distribution of the outcome 1
quasi_dists_ket_plus[0][1] = 1e-20
# show the quasi-distribution of
# the job for the quantum circuit
# implementing a quantum superposition state |+>,
# measured in the X-Basis
quasi_dists_ket_plus
# plot the histogram for the quasi-distributions
# for the two quantum states created before,
# namely the excited state |1> and
# the quantum superposition state |+>,
# measured in the X-Basis
plot_histogram( [ quasi_dists_ket_1[0], quasi_dists_ket_plus[0] ],
legend=legend, title="Measurement Results\n" )
# create a quantum circuit for one qubit
# and to implement an excited state |1>
qc2_1 = QuantumCircuit(1)
# apply a Pauli-X (bit flip / not) gate to
# the quantum circuit, on the 1st qubit
qc2_1.x(0)
# create a quantum circuit for one qubit
# and to implement a quantum superposition state |+>
qc2_plus = QuantumCircuit(1)
# apply a Hadamard gate to
# the quantum circuit, on the 1st qubit
qc2_plus.h(0)
# create a list for the observables for
# the Sparse Pauli-Z and Pauli-X operators
obsvs = list( SparsePauliOp( [ "Z", "X" ] ) )
# crate an Estimator object
estimator = Estimator()
# create a job for the quantum circuit implementing
# an excited state |1>, running the Estimator
job2_1 = estimator.run( [ qc2_1 ] * len(obsvs), observables=obsvs )
# create a job for the quantum circuit implementing
# a quantum superposition state |+>, running the Estimator
job2_plus = estimator.run( [ qc2_plus ] * len(obsvs), observables=obsvs )
# show the results of the job ran by
# the Estimator created before,
# that was ran on the excited state |1>
job2_1.result()
# print a table with results (and eigenvalues) for
# the quantum states created before and measured in the bases set before
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]}')
# import the Sparse Pauli operator from
# the IBM's Qiskit quantum information module
from qiskit.quantum_info import SparsePauliOp
# For Alice: A = Z ; a = X
# For Bob: B = Z ; b = X
# create the Sparse Pauli operator ZZ, for <AB>
ZZ = SparsePauliOp.from_list( [ ( "ZZ", 1 ) ] )
# create the Sparse Pauli operator ZX, for <Ab>
ZX = SparsePauliOp.from_list( [ ( "ZX", 1 ) ] )
# create the Sparse Pauli operator XZ, for <aB>
XZ = SparsePauliOp.from_list( [ ( "XZ", 1 ) ] )
# create the Sparse Pauli operator XX, for <ab>
XX = SparsePauliOp.from_list( [ ( "XX", 1 ) ] )
# create the list of required
# operators ZZ, ZX, XZ, and XX
ops = [ ZZ, ZX, XZ, XX ]
# there are two possible CHSH witnesses
# create operator for CHSH witness <CHSH_1>
# <CHSH_1> = <ZZ> - <ZX> + <XZ> + <XX> (=)
# (=) <CHSH_1> = <AB> - <Ab> + <aB> + <ab>
#obsv = ops[0] - ops[1] + ops[2] + ops[3]
# create operator for CHSH witness <CHSH_2>
# <CHSH_2> = <ZZ> + <ZX> - <XZ> + <XX> (=)
# (=) <CHSH_2> = <AB> + <Ab> - <aB> + <ab>
obsv = ( ops[0] + ops[1] - ops[2] + ops[3] )
# import the grader for the exercise 1 of the lab 2
from qc_grader.challenges.qgss_2023 import grade_lab2_ex1
# grade the exercise 1 of the lab 2
grade_lab2_ex1( obsv )
# import the parameter from
# the IBM's Qiskit circuit module
from qiskit.circuit import Parameter
# create a parameter for the theta angle
theta = Parameter("θ")
# create a quantum circuit for two qubits
# and to implement a parametrized quantum entangled pair
qc = QuantumCircuit(2)
# apply a Hadamard gate to
# the quantum circuit, on the 1st qubit
qc.h(0)
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on 1st qubit
# and target on 2nd qubit
qc.cx(0, 1)
# apply a RY (Rotation-Y) gate to
# the quantum circuit, on the 1st qubit,
# with the theta angle defined before
qc.ry(theta, 0)
# draw the quantum circuit implementing
# a parametrized quantum entangled pair
qc.draw("mpl")
# create a parameterization of theta angles that
# will violate the CHSH inequality
# number of theta angles to violate the CHSH inequality
number_of_phases = 20
# for the 1st CHSH witness
# <CHSH_1> = <ZZ> - <ZX> + <XZ> + <XX> (=)
# (=) <CHSH_1> = <AB> - <Ab> + <aB> + <ab>
#phases_chsh_1_1 = np.linspace(0.5 * np.pi, np.pi, number_of_phases)
#phases_chsh_1_2 = np.linspace(1.5 * np.pi, 2 * np.pi, number_of_phases)
# create the two lists of theta angles that
# violate the CHSH inequality
#angles_chsh_1_1 = [[ph] for ph in phases_chsh_1_1]
#angles_chsh_1_2 = [[ph] for ph in phases_chsh_1_2]
# merge the two lists of theta angles that
# violate the CHSH inequality, for the final result
#angles = angles_chsh_1_1 + angles_chsh_1_2
# for the 2nd CHSH witness
# <CHSH_2> = <ZZ> + <ZX> - <XZ> + <XX> (=)
# (=) <CHSH_2> = <AB> + <Ab> - <aB> + <ab>
phases_chsh_2_1 = np.linspace( 0, ( 0.5 * np.pi ), number_of_phases )
phases_chsh_2_2 = np.linspace( ( 1 * np.pi ) , ( 1.5 * np.pi ), number_of_phases )
# create the two lists of theta angles that
# violate the CHSH inequality
angles_chsh_2_1 = [ [ph] for ph in phases_chsh_2_1 ]
angles_chsh_2_2 = [ [ph] for ph in phases_chsh_2_2 ]
# merge the two lists of theta angles that
# violate the CHSH inequality, for the final result
angles = angles_chsh_2_1 + angles_chsh_2_2
# crate an Estimator object
estimator = Estimator()
# create a job for the quantum circuit implementing
# a parametrized quantum entangled pair,
# varying the elements in the list of
# theta angles defined before
job = estimator.run( [qc] * len(angles),
observables=[obsv] * len(angles),
parameter_values=angles )
# retrieve the expectation values
# from the results of the job ran by
# the Estimator created before,
# that was ran on the parametrized
# quantum entangled pair
exps = job.result().values
# plot the angles theta parametrized from the list built before
plt.plot( angles, exps, marker='x', ls='-', color="green" )
# plot the two classical bounds that violates the CHSH inequality
plt.plot( angles, [2]*len(angles), ls="--", color="red", label="Classical Bound" )
plt.plot( angles, [-2]*len(angles), ls="--", color="red" )
# add the X-axis label to the plot built before
plt.xlabel("angle (rad)")
# add the Y-axis label to the plot built before
plt.ylabel("CHSH Witness")
# add the title to the plot built before
plt.title("CHSH Witnesses\n")
# add the legend to the plot built before
plt.legend(loc=4)
# import the grader for the exercise 2 of the lab 2
from qc_grader.challenges.qgss_2023 import grade_lab2_ex2
# grade the exercise 2 of the lab 2
grade_lab2_ex2( obsv, angles )
# import the classical and quantum registers
# from the IBM's Qiksit circuit module
from qiskit.circuit import ClassicalRegister, QuantumRegister
# create a parameter for the theta angle
theta = Parameter("θ")
# create a quantum register for one qubit
# and to implement a parametrized quantum operation
qr = QuantumRegister(1, "q")
# create a quantum circuit with
# the quantum register created before
qc = QuantumCircuit(qr)
# apply a RY (Rotation-Y) gate to
# the quantum circuit, on the 1st qubit,
# with the theta angle defined before
qc.ry(theta, 0)
# draw the quantum circuit implementing
# a parametrized quantum operation
qc.draw("mpl")
# create a copy of the quantum circuit defined before
# to initialize the quantum circuit implementing
# a parametrized quantum teleportation
tele_qc = qc.copy()
# create a quantum register with two qubits
# for the Bell State to be shared on
# the parametrized quantum teleportation
bell = QuantumRegister(2, "Bell")
# create a classical register with two qubits
# for Alice's part on the parametrized
# quantum teleportation
alice = ClassicalRegister(2, "Alice")
# create a classical register with one qubit
# for Bob's part on the parametrized
# quantum teleportation
bob = ClassicalRegister(1, "Bob")
# add all the quantum and classical registers
# created before to the quantum circuit implementing
# a parametrized quantum teleportation
tele_qc.add_register(bell, alice, bob)
# draw the quantum circuit implementing
# the 1st step of a parametrized
# quantum teleportation
tele_qc.draw("mpl")
# add a barrier to the quantum circuit implementing
# a parametrized quantum teleportation
tele_qc.barrier()
# create Bell state with the other two qubits,
# in the quantum register defined before
# for that purpose
# apply a Hadamard gate to
# the quantum circuit, on the 2nd qubit
tele_qc.h(1)
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on 2nd qubit
# and target on 3rd qubit
tele_qc.cx(1, 2)
# add a barrier to the quantum circuit implementing
# a parametrized quantum teleportation
tele_qc.barrier()
# draw the quantum circuit implementing
# the 2nd step of a parametrized
# quantum teleportation
tele_qc.draw("mpl")
# operations for Alice perform on her qubits
# during the parametrized quantum teleportation
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on 1sr qubit
# and target on 2nd qubit
tele_qc.cx(0, 1)
# apply a Hadamard gate to
# the quantum circuit, on the 1st qubit
tele_qc.h(0)
# add a barrier to the quantum circuit implementing
# a parametrized quantum teleportation
tele_qc.barrier()
# draw the quantum circuit implementing
# the 3rd step of a parametrized
# quantum teleportation
tele_qc.draw("mpl")
# measurements performed by Alice on
# the qubit q and on her part of the Bell State,
# performing the entanglement swapping
tele_qc.measure( [ qr[0], bell[0] ], alice )
# draw the quantum circuit implementing
# the 4th step of a parametrized
# quantum teleportation
tele_qc.draw("mpl")
# create a copy of the quantum circuit defined before
# to initialize the quantum circuit implementing
# a parametrized quantum teleportation,
# and to be graded with dynamic operations
graded_qc = tele_qc.copy()
##############################
# add gates to graded_qc here
# Bob, who already has the qubit teleported,
# applies the following gates depending on
# the state of the classical bits:
# 00 -> Do nothing
# 01 -> Apply X gate
# 10 -> Apply Z gate
# 11 -> Apply ZX gate
# apply the Pauli-X (bit flip / not) gate on
# the 2nd qubit of the Bell state if
# the Alice's 2nd classical bit is 1
graded_qc.x( bell[1] ).c_if( alice[1], 1 )
# apply the Pauli-Z (phase flip) gate on
# the 2nd qubit of the Bell state if
# the Alice's 1st classical bit is 1
graded_qc.z( bell[1] ).c_if( alice[0], 1 )
##############################
# draw the quantum circuit implementing
# the parametrized quantum teleportation, to be graded
graded_qc.draw("mpl")
# add a barrier to the quantum circuit implementing
# a parametrized quantum teleportation, to be graded
graded_qc.barrier()
# measure the 2nd qubit of the Bell state to
# the Bob's classical register
graded_qc.measure( bell[1], bob )
# draw the quantum circuit implementing
# a parametrized quantum teleportation, to be graded
graded_qc.draw("mpl")
# import the grader for the exercise 3 of the lab 2
from qc_grader.challenges.qgss_2023 import grade_lab2_ex3
# grade the exercise 3 of the lab 2
grade_lab2_ex3( graded_qc, theta, 5 * ( np.pi / 7 ) )
# impor the Sampler from the IBM's Qiskit
# Aer primitives module
from qiskit_aer.primitives import Sampler
# define the pretended theta angle
angle = 5 * ( np.pi / 7 )
# create a Sampler object
sampler = Sampler()
# measure all the qubits on the quantum circuit
# implementing a parametrized quantum teleportation
qc.measure_all()
# create a job for the quantum circuit implementing
# a parametrized quantum teleportation,
# with a static quantum circuit and
# with the theta angle defined before
job_static = sampler.run( qc.bind_parameters({theta: angle}) )
# create a job for the quantum circuit implementing
# a parametrized quantum teleportation,
# with a dynamic quantum circuit and
# with the theta angle defined before
job_dynamic = sampler.run( graded_qc.bind_parameters({theta: angle}) )
# print the measurement distributions of the qubits from
# the parametrized quantum teleportation, with a static quantum circuit
print( f"Original Dists.: {job_static.result().quasi_dists[0].binary_probabilities()}" )
# print the measurement distributions of the qubits from
# the parametrized quantum teleportation, with a dynamic quantum circuit
print( f"Teleported Dists.: {job_dynamic.result().quasi_dists[0].binary_probabilities()}" )
# import the counts marginalization from
# the IBM's Qiskit result module
from qiskit.result import marginal_counts
# marginalize counts from the quasi-distributitions
# obtained from the parametrized quantum teleportation
tele_counts = marginal_counts( job_dynamic.result().quasi_dists[0]
.binary_probabilities(), [2] )
# create the legend for the two quantum states
# created before, namely the original quantum state to
# be teleported and the quantum state which was indeed teleported
legend = [ "Original State", "Teleported State" ]
# plot the histogram for the quasi-distributions
# for the two quantum states created before,
# namely the original quantum state to be teleported
# and the quantum state which was indeed teleported
plot_histogram( [ job_static.result().quasi_dists[0]
.binary_probabilities(), tele_counts ],
legend=legend, title="Measurement Results\n" )
# import the grader for the exercise 4 of the lab 2
from qc_grader.challenges.qgss_2023 import grade_lab2_ex4
# grade the exercise 4 of the lab 2
grade_lab2_ex4( tele_counts, job_dynamic.result() )
# import the IBM's Qiskit Jupyter Tools
import qiskit.tools.jupyter
# show the table of the IBM's Qiskit version
%qiskit_version_table
|
https://github.com/rubenandrebarreiro/ibm-qiskit-global-summer-school-2023
|
rubenandrebarreiro
|
# upgrade/update pip library
!pip install --upgrade pip
# install the last official version of the grader from IBM's Qiskit Community
!pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git@main
# import the quantum circuit, Aer,
# and execute instruction
# from the IBM' Qiskit library
from qiskit import QuantumCircuit, Aer, execute
# import the numpy library
import numpy as np
# import the plot histogram function
# from the IBM's Qiskit Visualization module
from qiskit.visualization import plot_histogram
# import the plotting from
# the Matplotlib's Pyplot module
import matplotlib.pyplot as plt
# import the GCD (Greatest Common Divisor)
# from the built-in mathematics module
from math import gcd
# define the function to genera the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
def qft(n):
# creates a quantum circuit with n qubits,
# implementing the Quantum Fourier Transform (QFT)
circuit = QuantumCircuit(n)
# define the function to perform the Swap gates
# on the quantum registers of the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
def swap_registers( circuit, n ):
# for a number of iterations equal to half of
# the number of qubits used on the quantum circuit
# for the Quantum Fourier Transform (QFT)
for qubit in range( n // 2 ):
# apply the Swap gate between the kth qubit and
# the (n - k)th qubit on the quantum register defined before
circuit.swap( qubit, ( n - qubit - 1 ) )
# return the quantum circuit with the Swap gates
# applied on the n qubits of the quantum register,
# to implement the Quantum Fourier Transform (QFT)
return circuit
# define the function to perform the Controlled-Phase gates
# on the quantum registers of the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
# (it is applied to the first n qubits,
# and without the Swap gates performed)
def qft_rotations( circuit, n ):
# if it is the last opposite iteration
if n == 0:
# return with the Controlled-Phase gates
# on the quantum registers of the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
# (it is applied to the first n qubits,
# and without the Swap gates performed)
return circuit
# iterates on the opposite direction,
# setting a new nth iteration
n -= 1
# apply the Hadamard gate to the kth qubit,
# on the quantum register defined before,
# and iterating on the opposite direction
circuit.h(n)
# for the remaining qubits to consider
# i the kth opposite iteration
for qubit in range(n):
# apply the Controlled-Phase gate for
# the theta angle equal to (pi / 2)^(n - k),
# with control on the nth qubit and target on the kth qubit
circuit.cp( ( np.pi / 2 )**( n - qubit ), qubit, n )
# call this fuction recursively for
# the next opposite iteration
qft_rotations( circuit, n )
# perform the Controlled-Phase gates
# on the quantum registers of the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
# (it is applied to the first n qubits,
# and without the Swap gates performed)
qft_rotations( circuit, n )
# perform the Swap gates on the quantum registers of
# the quantum circuit for the Quantum Fourier Transform (QFT) on n qubits
swap_registers( circuit, n )
# return the quantum circuit with n qubits,
# implementing the Quantum Fourier Transform (QFT)
return circuit
# define the function to genera the quantum circuit
# for the Inverse Quantum Fourier Transform (IQFT) on n qubits
def qft_dagger( circuit, n ):
# note: do not forget to apply again the Swap gates
# to peform its inverse operation
# for a number of iterations equal to half of
# the number of qubits used on the quantum circuit
# for the Inverse Quantum Fourier Transform (IQFT)
for qubit in range( n // 2 ):
# apply the Swap gate between the kth qubit and
# the (n - k)th qubit on the quantum register defined before
circuit.swap( qubit, ( n - qubit - 1 ) )
# for each number of qubits of the quantum register defined before,
# to consider in the current jth iteration
for j in range(n):
# for each mth qubit of the quantum register defined before,
# to consider in the current iteration
for m in range(j):
# apply the Controlled-Phase gate for
# the theta angle equal to -pi / ( 2^( j - m ) ),
# with control on the mth qubit and target on the jth qubit
qc.cp( -np.pi / float( 2**( j - m ) ), m, j )
# apply the Hadamard gate to the jth qubit
# on the quantum register defined before
qc.h(j)
# define the size n of the quantum register to
# store the phase information
phase_register_size = 4
# create a quantum circuit with a quantum register
# with n qubits and a classical register with n bits,
# to implement the Quantum Phase Estimation (QPE) for n = 4 qubits
qpe4 = QuantumCircuit( ( phase_register_size + 1 ),
phase_register_size )
####################################################
#### insert your code here ####
# define the function to perform the Quantum Hadamard Transform on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
def apply_quantum_hadamard_transform( circuit, n ):
# for each qubit of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE) for n qubits
for qubit_idx in range(n):
# apply the Hadamard gate to the current ith qubit
circuit.h(qubit_idx)
# define the function to perform the Controlled-Phase gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
def apply_controlled_phases( theta, circuit, n ):
# for each ith step according to
# the number of n qubits used
for step in range(n):
# compute the iteration parameter t
# as a power of 2, according to the current step
t = 2**step
# for each iteration according to
# the iteration parameter t
for _ in range(t):
# apply the Controlled-Phase gate for the theta angle,
# with control on the ith qubit and target on the last qubit
circuit.cp( theta, step, n )
# define the function to perform the Swap gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
def apply_swaps( circuit, n ):
# for a number of iterations equal to half of
# the number of phase counting qubits used
# on the resepective quantum circuit
# for the Quantum Fourier Transform (QFT)
for qubit_idx in range( phase_register_size // 2 ):
# apply the Swap gate between the kth qubit and
# the (n - k)th qubit on the quantum register defined before
circuit.swap( qubit_idx, ( n - qubit_idx - 1 ) )
# define the function to perform
# the Inverse Quantum Fourier Transform (IQFT) on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
def apply_quantum_fourier_transform_inverse( circuit, n ):
# for each qubit on the quantum register
for j in range(n):
# for each additional mth qubit ranging to
# the current jth qubit being iterated before
for m in range(j):
# apply the Controlled-Phase gate for
# the theta angle equal to -pi / ( 2^( j - m ) ),
# with control on the mth qubit and target on the jth qubit
circuit.cp( -np.pi / float( 2**( j - m ) ), m, j )
# apply the Hadamard gate to the jth qubit (system's qubit)
circuit.h(j)
# define the function to perform a measurement of
# all the n qubits on the quantum register of a quantum circuit,
# and storing the classical outcomes on the n bits of
# the classical register of that same quantum circuit
def measure_all_qubits(circuit, n):
# for each pair of qubits and bits
for j in range(n):
# measure the current qubit on the quantum register,
# and stores the classical outcome obtained
# in the current bit on the classical register
circuit.measure(j, j)
# define the function to perform the Quantum Phase Estimation (QPE)
# according to a theta angle given, on a quantum circuit of n qubits
def quantum_phase_estimation( theta, circuit, n ):
# perform the Quantum Hadamard Transform on
# the n qubits of the quantum register of
# the quantum circuit implementing
# the Quantum Phase Estimation (QPE)
apply_quantum_hadamard_transform( circuit, n )
# apply the Pauli-X gate to the last qubit on
# the quantum register of the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.x(n)
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.barrier()
# perform the Controlled-Phase gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_controlled_phases( theta, circuit, n )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.barrier()
# perform the Swap gates on the n qubits of
# the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_swaps( circuit, n )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.barrier()
# perform the Inverse Quantum Fourier Transform (IQFT) on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
apply_quantum_fourier_transform_inverse( circuit, n )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.barrier()
# perform a measurement of all the n qubits on
# the quantum register of the quantum circuit of
# the Quantum Phase Estimation (QPE) and storing
# the classical outcomes on the n bits of
# the classical register of that same quantum circuit
measure_all_qubits( circuit, n )
####################################################
# define the theta angle to be equal to (2 * pi) / 3
theta = ( 2 * np.pi ) / 3
# perform the Quantum Phase Estimation (QPE)
# according to the theta angle defined,
# on the quantum circuit of n qubits defined before
quantum_phase_estimation( theta, qpe4, phase_register_size )
# draw the quantum circuit implementing
# the Quantum Phase Estimation (QPE) defined before
qpe4.draw("mpl")
# run this cell to simulate 'qpe4' and
# to plot the histogram of the result
# create the Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 20000
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation
count_qpe4 = execute( qpe4, sim, shots=shots ).result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n = 4 counting qubits
plot_histogram( count_qpe4, figsize=(9,5) )
# submit your answer
# import the grader for the exercise 1 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex1
# grade the exercise 1 of the lab 3
grade_lab3_ex1( count_qpe4 )
# process the result count data to determine accuracy of
# the estimated phase and grab the highest probability measurement
# define the maximum number of counts which will be obtained
max_binary_counts = 0
# define the maximum binary value which will be obtained
max_binary_val = ""
# for each count obtained from the quantum simulation of
# the Quantum Phase Estimation (QPE)
for key, item in count_qpe4.items():
# if the current number of counts is greater than
# the current maximum number of counts obtained
if item > max_binary_counts:
# update the maximum number of counts obtained
max_binary_counts = item
# update the maximum binary value obtained
max_binary_val = key
#########################################
#### your function to convert a binary ####
#### string to a decimal number goes here ####
# define the function to convert
# a binary string to a decimal number
def bin_to_decimal( binary_string ):
# return a binary string
# converted to a decimal number
return int( binary_string, 2 )
# calculate the estimated phase obtained
# from the quantum simulation of
# the Quantum Phase Estimation (QPE)
estimated_phase = ( bin_to_decimal(max_binary_val) / 2**phase_register_size )
# calculate the phase accuracy
# which can be obtained from
# the quantum simulation of
# the Quantum Phase Estimation (QPE)
# with the quantum circuit defined before,
# inverse of the highest power of 2
# (i.e. smallest decimal) this quantum circuit can estimate
phase_accuracy_window = 2**( -phase_register_size )
# submit your answer
# import the grader for the exercise 2 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex2
# grade the exercise 2 of the lab 3
grade_lab3_ex2( [ estimated_phase, phase_accuracy_window ] )
# import the IBM's Provider from
# the Qiskit's IBM Provider module
from qiskit_ibm_provider import IBMProvider
# import the transpile function from
# the IBM's Qikist Compiler module
from qiskit.compiler import transpile
# create an IBM's Provider object
provider = IBMProvider()
# define the hub for the IBM's Provider
hub = "summer-school-6"
# define the group for the IBM's Provider
group = "group-3"
# define the project for the IBM's Provider
project = "7048813929"
# define the backend's name for the IBM's Provider
backend_name = "ibmq_manila"
# retrieve the backend from the IBM's Provider
backend = provider.get_backend( backend_name, instance=f"{hub}/{group}/{project}" )
##########################################
#### your code goes here ####
# define the initial maximum quantum circuit depth obtained
max_depth = 1e-20
# define the initial minimum quantum circuit depth obtained
min_depth = 1e20
# define the number of trials to transpile/optimize
# the quantum circuit for the Quantum Phase Estimation (QPE)
num_trials = 10
# for each trial to transpile/optimize the quantum circuit
# for the Quantum Phase Estimation (QPE)
for _ in range(num_trials):
# transpile/optimize the quantum circuit
# for the Quantum Phase Estimation (QPE),
# for the current considering trial
transpiled_qpe4 = transpile( qpe4, backend, optimization_level=3 )
# retrieve the quantum circuit depth of
# the transpiled/optimized quantum circuit
# for the Quantum Phase Estimation (QPE)
transpiled_qpe4_depth = transpiled_qpe4.depth()
# if the quantum circuit depth of
# the transpiled/optimized quantum circuit
# for the Quantum Phase Estimation (QPE)
# is greater than the current maximum
# quantum circuit depth obtained
if transpiled_qpe4_depth > max_depth:
# update the maximum quantum circuit depth
# obtained with the current quantum circuit depth
max_depth = transpiled_qpe4_depth
# update the quantum circuit with the maximum depth
# with the current quantum circuit transpiled/optimized
max_depth_qpe = transpiled_qpe4
# if the quantum circuit depth of
# the transpiled/optimized quantum circuit
# for the Quantum Phase Estimation (QPE)
# is lower than the current minimum
# quantum circuit depth obtained
if transpiled_qpe4_depth < min_depth:
# update the minimum quantum circuit depth
# obtained with the current quantum circuit depth
min_depth = transpiled_qpe4_depth
# update the quantum circuit with the minimum depth
# with the current quantum circuit transpiled/optimized
min_depth_qpe = transpiled_qpe4
##########################################
# submit your answer
# import the grader for the exercise 3 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex3
# grade the exercise 3 of the lab 3
grade_lab3_ex3( [ max_depth_qpe, min_depth_qpe ] )
# define the number of shots
#shots = 2000
# OPTIONAL: run the minimum depth quantum circuit for
# the Quantum Phase Estimation (QPE)
# execute and retrieve the job for the simulation
# for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the minimum quantum circuit depth
#job_min_qpe4 = backend.run( min_depth_qpe, sim, shots=shots )
# print the id of the job of the simulation
# for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the minimum quantum circuit depth
#print( job_min_qpe4.job_id() )
# gather the result counts data
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the minimum quantum circuit depth
#count_min_qpe4 = job_min_qpe4.result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n = 4 counting qubits,
# and using the minimum quantum circuit depth
#plot_histogram( count_min_qpe4, figsize=(9,5) )
# OPTIONAL: run the maximum depth quantum circuit for
# the Quantum Phase Estimation (QPE)
# execute and retrieve the job for the simulation
# for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the maximum quantum circuit depth
#job_max_qpe4 = backend.run( max_depth_qpe, sim, shots=shots )
# print the id of the job of the simulation
# for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the maximum quantum circuit depth
#print( job_max_qpe4.job_id() )
# gather the result counts data
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the maximum quantum circuit depth
#count_max_qpe4 = job_max_qpe4.result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n = 4 counting qubits,
# and using the maximum quantum circuit depth
#plot_histogram( count_max_qpe4, figsize=(9,5) )
# define the function to perform the Quantum Hadamard Transform on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
def apply_quantum_hadamard_transform( circuit, n ):
# for each qubit of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE) for n qubits
for qubit_idx in range(n):
# apply the Hadamard gate to the current ith qubit
circuit.h(qubit_idx)
# define the function to perform the Controlled-Phase gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
def apply_controlled_phases( theta, circuit, n ):
# for each ith step according to
# the number of n qubits used
for step in range(n):
# compute the iteration parameter t
# as a power of 2, according to the current step
t = 2**step
# for each iteration according to
# the iteration parameter t
for _ in range(t):
# apply the Controlled-Phase gate for the theta angle,
# with control on the ith qubit and target on the last qubit
circuit.cp( theta, step, n )
# define the function to perform the Swap gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
def apply_swaps( circuit, n ):
# for a number of iterations equal to half of
# the number of phase counting qubits used
# on the resepective quantum circuit
# for the Quantum Fourier Transform (QFT)
for qubit_idx in range( phase_register_size // 2 ):
# apply the Swap gate between the kth qubit and
# the (n - k)th qubit on the quantum register defined before
circuit.swap( qubit_idx, ( n - qubit_idx - 1 ) )
# define the function to perform
# the Inverse Quantum Fourier Transform (IQFT) on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
def apply_quantum_fourier_transform_inverse( circuit, n ):
# for each jth qubit on the quantum register
for j in range(n):
# for each additional mth qubit ranging to
# the current jth qubit being iterated before
for m in range(j):
# apply the Controlled-Phase gate for
# the theta angle equal to -pi / ( 2^( j - m ) ),
# with control on the mth qubit and target on the jth qubit
circuit.cp( -np.pi / float( 2**( j - m ) ), m, j )
# apply the Hadamard gate to the jth qubit
circuit.h(j)
# define the function to perform a measurement of
# all the n qubits on the quantum register of a quantum circuit,
# and storing the classical outcomes on the n bits of
# the classical register of that same quantum circuit
def measure_all_qubits( circuit, n ):
# for each pair of qubits and bits
for j in range(n):
# measure the current qubit on the quantum register,
# and stores the classical outcome obtained
# in the current bit on the classical register
circuit.measure(j, j)
# define the function to create a quantum circuit,
# implementing the Quantum Phase Estimation (QPE) on (n + 1) qubits
def qpe_circuit(register_size):
#########################################
#### your code goes here ####
# define the theta phase angle to estimate
theta = 1/7
# create the quantum circuit with a quantum register with (n + 1) qubits
# and a classical register with n bits, intended to implement
# the Quantum Phase Estimation (QPE) on n qubits
qpe = QuantumCircuit( ( register_size + 1 ), register_size )
# perform the Quantum Hadamard Transform on
# the n qubits of the quantum register of
# the quantum circuit implementing
# the Quantum Phase Estimation (QPE)
apply_quantum_hadamard_transform( qpe, register_size )
# apply the Pauli-X gate to the last qubit on
# the quantum register of the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.x(register_size)
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.barrier()
# perform the Controlled-Phase gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_controlled_phases( theta, qpe, register_size )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.barrier()
# perform the Swap gates on the n qubits of
# the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_swaps( qpe, register_size )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.barrier()
# perform the Inverse Quantum Fourier Transform (IQFT) on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
apply_quantum_fourier_transform_inverse( qpe, register_size )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.barrier()
# perform a measurement of all the n qubits on
# the quantum register of the quantum circuit of
# the Quantum Phase Estimation (QPE) and storing
# the classical outcomes on the n bits of
# the classical register of that same quantum circuit
measure_all_qubits( qpe, register_size )
# return the quantum circuit, implementing
# the Quantum Phase Estimation (QPE) on n qubits
return qpe
#########################################
# run this cell to simulate 'qpe' and
# to plot the histogram of the result
# define several quantum register sizes
# equal to n, allowing to vary them
#reg_size = 4
reg_size = 5
#reg_size = 6
#reg_size = 7
#reg_size = 8
# create a quantum circuit for
# the Quantum Phase Estimation (QPE),
# given the quantum register defined before,
# with n counting qubits
qpe_check = qpe_circuit( reg_size )
# create the Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 10000
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n counting qubits, and retrieve its result counts
count_qpe = execute( qpe_check, sim, shots=shots ).result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits
plot_histogram( count_qpe, figsize=(9,5) )
# process the result count data to determine accuracy of
# the estimated phase and grab the highest probability measurement
# define the maximum number of counts which will be obtained
max_binary_counts = 0
# define the maximum binary value which will be obtained
max_binary_val = ""
# for each count obtained from the quantum simulation of
# the Quantum Phase Estimation (QPE)
for key, item in count_qpe.items():
# if the current number of counts is greater than
# the current maximum number of counts obtained
if item > max_binary_counts:
# update the maximum number of counts obtained
max_binary_counts = item
# update the maximum binary value obtained
max_binary_val = key
#########################################
#### your function to convert a binary ####
#### string to a decimal number goes here ####
# define the function to convert
# a binary string to a decimal number
def bin_to_decimal( binary_string ):
# return a binary string
# converted to a decimal number
return int( binary_string, 2 )
# calculate the estimated phase obtained
# from the quantum simulation of
# the Quantum Phase Estimation (QPE)
estimated_phase = ( bin_to_decimal(max_binary_val) / 2**reg_size )
# print the estimated phase obtained
# from the quantum simulation of
# the Quantum Phase Estimation (QPE)
print("Estimated Phase:", estimated_phase)
# calculate the phase accuracy
# which can be obtained from
# the quantum simulation of
# the Quantum Phase Estimation (QPE)
# with the quantum circuit defined before,
# inverse of the highest power of 2
# (i.e. smallest decimal) this quantum circuit can estimate
phase_accuracy_window = 2**( -reg_size )
# print the phase accuracy
# which can be obtained from
# the quantum simulation of
# the Quantum Phase Estimation (QPE)
# with the quantum circuit defined before,
# inverse of the highest power of 2
# (i.e. smallest decimal) this quantum circuit can estimate
print("Phase Accuracy Window:", phase_accuracy_window)
# define the theta phase angle,
# which was pretended to be estimated
theta = 1 / 7
# compute the accuracy of the estimated phase,
# as the distance between the estimated phase
# and the theta phase angle, which was pretended to be estimated
accuracy_estimated_phase = abs( theta - estimated_phase )
# print the accuracy of the estimated phase,
# as the distance between the estimated phase
# and the theta phase angle, which was pretended to be estimated
print("Accuracy of the Estimated Phase:", accuracy_estimated_phase)
### put your answer here ###
# to estimate accurately the phase information to be within 2^(-6)
# we need n + 1 = 6 (=) n = 5 qubits to store the phase information
required_register_size = 5
### submit your answer ###
# import the grader for the exercise 4 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex4
# grade the exercise 4 of the lab 3
grade_lab3_ex4( required_register_size )
# create 7 mod 15 unitary operator
# for a quantum circuit
N = 15
# define the number of m qubits required
# for the 7 mod 15 operator to be executed
m = int( np.ceil( np.log2( N ) ) )
# create the quantum circuit with
# a quantum register of m qubits
# to implement the 7 mod 15 unitary operator
U_qc = QuantumCircuit( m )
# apply the Pauli-X gate to all the m qubits of
# the quantum register of the quantum circuit
# implementing the 7 mod 15 unitary operator
U_qc.x( range(m) )
# apply the Swap gate between the 2nd qubit and
# the 3rd qubit on the quantum register of
# the quantum circuit implementing
# the 7 mod 15 unitary operator
U_qc.swap(1, 2)
# apply the Swap gate between the 3rd qubit and
# the 4th qubit on the quantum register of
# the quantum circuit implementing
# the 7 mod 15 unitary operator
U_qc.swap(2, 3)
# apply the Swap gate between the 1st qubit and
# the 4th qubit on the quantum register of
# the quantum circuit implementing
# the 7 mod 15 unitary operator
U_qc.swap(0, 3)
# convert the quantum circuit implementing
# the 7 mod 15 unitary operator to
# a quantum unitary gate
U = U_qc.to_gate()
# define the name of the 7 mod 15
# unitary operator created before
U.name ="{}Mod{}".format(7, N)
# your code goes here
# print the number of qubits
print("Num. qubits: m =", m);
# define the quantum circuits for the inputs
# |1> = |0001>, |2> = |0010>, and |5> = |0101>
#########################################
# create the a quantum circuit with m qubits,
# for the input state |1> = |0001>
qcirc_input_1 = QuantumCircuit(m)
# apply the Pauli-X gate to
# the 1st qubit of the quantum register of
# the quantum circuit defined before
qcirc_input_1.x(0)
# apply the U gate to all
# the m qubits of the quantum register of
# the quantum circuit defined before
qcirc_input_1.append( U, range(m) )
# measure all the m qubits of
# the quantum register of
# the quantum circuit defined before
qcirc_input_1.measure_all()
#########################################
# create the a quantum circuit with m qubits,
# for input state |2> = |0010>
qcirc_input_2 = QuantumCircuit(m)
# apply the Pauli-X gate to
# the 2nd qubit of the quantum register of
# the quantum circuit defined before
qcirc_input_2.x(1)
# apply the U gate to all
# the m qubits of the quantum register of
# the quantum circuit defined before
qcirc_input_2.append( U, range(m) )
# measure all the m qubits of
# the quantum register of
# the quantum circuit defined before
qcirc_input_2.measure_all()
#########################################
# create the a quantum circuit with m qubits,
# for input state |5> = |0101>
qcirc_input_5 = QuantumCircuit(m)
# apply the Pauli-X gate to
# the 1st qubit of the quantum register of
# the quantum circuit defined before
qcirc_input_5.x(0)
# apply the Pauli-X gate to
# the 3rd qubit of the quantum register of
# the quantum circuit defined before
qcirc_input_5.x(2)
# apply the U gate to all
# the m qubits of the quantum register of
# the quantum circuit defined before
qcirc_input_5.append( U, range(m) )
# measure all the m qubits of
# the quantum register of
# the quantum circuit defined before
qcirc_input_5.measure_all()
#########################################
# run this cell to simulate 'qcirc' and to plot the histogram of the result
# create the Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 20000
# save the count data for the input state |1> = |0001>
input_1 = execute(qcirc_input_1, sim, shots=shots).result().get_counts()
# save the count data for the input state |2> = |0010>
input_2 = execute(qcirc_input_2, sim, shots=shots).result().get_counts()
# save the count data for the input state |5> = |0101>
input_5 = execute(qcirc_input_5, sim, shots=shots).result().get_counts()
# submit your answer
# import the grader for the exercise 5 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex5
# grade the exercise 5 of the lab 3
grade_lab3_ex5( [ input_1, input_2, input_5 ] )
# create an unitary quantum circuit
# with a quantum register of m qubits
unitary_circ = QuantumCircuit(m)
#### your code goes here ####
# for each iteration in a range of 2^2 = 4
for _ in range( 2**2 ):
# apply the U gate on all
# the m qubits on the quantum register
unitary_circ.append( U, range(m) )
# create a Unitary Simulator object
sim = Aer.get_backend("unitary_simulator")
# execute the quantum simulation of
# an unitary quantum circuit with
# a quantum register of m qubits,
# defined before, retrieving its unitary operator
unitary = execute( unitary_circ, sim ).result().get_unitary()
# submit your answer
# import the grader for the exercise 6 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex6
# grade the exercise 6 of the lab 3
grade_lab3_ex6( unitary, unitary_circ )
# define the function to built a 2^k-Controlled-U gate object,
# which repeats the action of the operator U, 2^k times
def cU_multi(k):
# define the size n of the system's quantum register
sys_register_size = 4
# create the quantum circuit with n qubits on
# the system's quantum register, to build
# a 2^k-Controlled-U gate object
circ = QuantumCircuit( sys_register_size )
# for each iteration ranging until 2^k
for _ in range(2**k):
# apply the U gate to all the n qubits on
# the system's quantum register of
# the quantum circuit to represent
# the 2^k-Controlled-U gate
circ.append(U, range(sys_register_size))
# convert the operator resulting from the construction of
# the quantum circuit defined before, to a quantum gate
U_multi = circ.to_gate()
# define the name of the 2^k-Controlled-U gate,
# as being a "7 Mod 15 gate"
U_multi.name = "7Mod15_[2^{}]".format(k)
# set this 2^k-Controlled-U gate as multi-qubit gate,
# depending on a given control qubit
cU_multi = U_multi.control()
# return the 2^k-Controlled-U gate object,
# which repeats the action of the operator U, 2^k times
return cU_multi
# define the size m of the quantum register
# for the phase counting of the qubits
phase_register_size = 8
# define the size n of the quantum register
# for the successive applications of
# the 2^k-Controlled-U gate defined before
cu_register_size = 4
# create the Quantum Circuit needed to run
# with m = 8 qubits for the phase counting
# and with n = 4 qubits for the successive
# applications of the 2^k-Controlled-U gate
# defined before, to implement the Shor's Algorithm
# for Factoring, based on Quantum Phase Estimation (QPE)
shor_qpe = QuantumCircuit( ( phase_register_size + cu_register_size ),
phase_register_size )
# perform the Quantum Hadamard Transform on
# the m qubits for the phase counting of
# the quantum register of the quantum circuit
# implementing the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_quantum_hadamard_transform( shor_qpe, phase_register_size )
# apply the Pauli-X gate to the last qubit on
# the quantum register of the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.x( phase_register_size )
# apply a barrier to the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.barrier()
# for each kth qubit on the quantum register
# for the phase counting of the qubits
for k in range( phase_register_size ):
# retrieve the 2^k-Controlled-U gate object,
# which repeats the action of the operator U,
# 2^k times, defined before
cU = cU_multi(k)
# apply the 2^k-Controlled-U gate object,
# which repeats the action of the operator U,
# 2^k times, defined before, for the kth iteration,
# to the quantum circuit to implement
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.append( cU, [k] + list( range( phase_register_size,
( phase_register_size + cu_register_size ) ) ) )
# apply a barrier to the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.barrier()
# perform the Swap gates on the n qubits of
# the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT),
# required to build the quantum circuit to implement
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_swaps(shor_qpe, phase_register_size)
# apply a barrier to the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.barrier()
# perform the Inverse Quantum Fourier Transform (IQFT) on
# the m qubits for the phase counting of
# the quantum register of the quantum circuit
# implementing the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_quantum_fourier_transform_inverse( shor_qpe, phase_register_size )
# apply a barrier to the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.barrier()
# perform a measurement of all
# the m qubits for the phase counting of
# the quantum register of the quantum circuit
# implementing the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.measure( range( phase_register_size ),
range( phase_register_size ) )
# draw the quantum circuit implementing
# the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.draw("mpl")
# run this cell to simulate 'shor_qpe' and
# to plot the histogram of the results
# create an Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 20000
# execute the quantum simulation for
# the quantum circuit for the Shor's Algorithm,
# based on Quantum Phase Estimation (QPE),
# with n phase counting qubits, and retrieve
# the result counts of this quantum simulation
shor_qpe_counts = execute(shor_qpe, sim, shots=shots).result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the quantum circuit for the Shor's Algorithm, based on
# Quantum Phase Estimation (QPE), with n phase counting qubits
plot_histogram( shor_qpe_counts, figsize=(9,5) )
# submit your answer
# import the grader for the exercise 7 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex7
# grade the exercise 7 of the lab 3
grade_lab3_ex7( shor_qpe_counts )
# import the Fraction object
# from the built-in fractions module
from fractions import Fraction
# print the number '0.666',
# as an unlimited Fraction object
print( "Unlimited Fraction(0.666):",
Fraction(0.666), '\n')
# print the number '0.666',
# as a limited Fraction object
# with the denominator of 15
print( "Limited Fraction(0.666), with a max. denominator of 15:",
Fraction(0.666).limit_denominator(15) )
# create a list with the estimated phases of the result counts
# obtained from the execution of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits
estimated_phases = [ bin_to_decimal(binary_val) / 2**phase_register_size
for binary_val in shor_qpe_counts ]
# print the list with the estimated phases of the result counts
# obtained from the execution of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits
print( "Estimated Phases:", estimated_phases )
# create a list of with the estimated phases of the result counts
# obtained from the execution of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits,
# represented as Fraction objects with the format s/r
shor_qpe_fractions = [ Fraction(estimated_phase).limit_denominator(15)
for estimated_phase in estimated_phases ]
# print the list of with the estimated phases of the result counts
# obtained from the execution of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits,
# represented as Fraction objects with the format s/r
print( "Estimated Fractions:", shor_qpe_fractions )
# submit your answer
# import the grader for the exercise 8 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex8
# grade the exercise 8 of the lab 3
grade_lab3_ex8( shor_qpe_fractions )
# define the function to create and execute
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits
def shor_qpe(k):
# define the co-prime a
a = 7
# define the number N to factor
N = 15
# compute the number m of
# additional qubits required
m = int( np.ceil( np.log2(N) ) )
#################################################
# step 1. Begin a while loop until a nontrivial guess is found
#### your code goes here ####
# define the boolean flag to determine
# if a non trivial guess was found, initially as False
non_trivial_guess_found = False
# while no trivial factor guess was found,
# execute the while loop
while( not non_trivial_guess_found ):
#################################################
# step 2a. construct a QPE quantum circuit
# with m phase counting qubits to guess
# the phase phi = s/r, using the function
# cU_multi() defined before
#### your code goes here ####
# create a quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc = QuantumCircuit( ( k + m ), k)
# perform the Quantum Hadamard Transform on
# the k phase counting qubits of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_quantum_hadamard_transform( qc, k )
# apply a Pauli-X gate to the last
# phase counting qubit of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
qc.x(k)
# apply a barrier to the quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc.barrier()
# for each kth qubit on the quantum register
# for the phase counting of the qubits
for k_i in range(k):
# retrieve the 2^k-Controlled-U gate object,
# which repeats the action of the operator U,
# 2^k times, defined before
cU = cU_multi(k_i)
# apply the 2^k-Controlled-U gate object,
# which repeats the action of the operator U,
# 2^k times, defined before, for the kth iteration,
# to the quantum circuit for the Shor's Algorithm
# for Factoring, based on Quantum Phase Estimation (QPE),
# with k phase counting qubits, and additional m qubits
# for the successive applications of
# the 2^k-Controlled-U gate defined before
qc.append( cU, [k_i] + list( range( k, ( k + m ) ) ) )
# apply a barrier to the quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc.barrier()
# perform the Swap gates on the k
# phase counting qubits of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_swaps( qc, k )
# apply a barrier to the quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc.barrier()
# perform the Inverse Quantum Fourier Transform (IQFT) on
# the k phase counting qubits of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_quantum_fourier_transform_inverse( qc, k )
# apply a barrier to the quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc.barrier()
# perform a measurement of all
# the k phase counting qubits of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
qc.measure( range(k), range(k) )
#################################################
# step 2b. run the QPE quantum circuit with a single shot,
# record the results and convert the estimated phase
# bitstring to a decimal format
#### your code goes here ####
# create an Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 1
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n counting qubits, and retrieve the result counts
# obtained from this quantum simulation
shor_qpe_counts = execute( qc, sim, shots=shots ).result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits
plot_histogram( shor_qpe_counts, figsize=(9,5) )
# compute the estimated phases from the result counts
# obtained from the quantum simulation of the quantum circuit
# implementing the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
estimated_phases = [ bin_to_decimal( binary_val ) / 2**k
for binary_val in shor_qpe_counts ]
#################################################
# step 3. use the Fraction object to find the guess for r
#### your code goes here ####
# convert the estimated phase to a fraction s/r format
fraction_s_r = [ Fraction(estimated_phase).limit_denominator(N)
for estimated_phase in estimated_phases ][0]
# retrieve the numerator s and the denominator r
# from the estimated phase represented as a fraction
s, r = fraction_s_r.numerator, fraction_s_r.denominator
#################################################
# step 4. now that r has been found, use the built-in
# greatest common divisor function to determine
# the guesses for a factor of N
# build the list of guesses for possible non-trivial factors of N
guesses = [ gcd( a**( r // 2 ) - 1, N ),
gcd( a**( r // 2 ) + 1, N ) ]
#################################################
# step 5. for each guess in guesses, check if
# at least one is a non-trivial factor,
# i.e., ( ( guess != 1 ) or ( guess != N ) )
# and ( N % guess == 0 )
#### your code goes here ####
# for each of the guesses computed before
for guess in guesses:
# if the current guess is not a trivial factor
if ( ( ( guess != 1 ) or ( guess != N ) )
and ( N % guess == 0 ) ):
# update the boolean flag to determine
# if a non trivial guess was found, as True
non_trivial_guess_found = True
# break the current for loop
break
#################################################
# step 6. if a non-trivial factor is found return
# the list 'guesses', otherwise
# continue the while loop
# return the list of the guesses,
# containing a non-trivial factor of N
return guesses
#################################################
# submit your circuit
# import the grader for the exercise 9 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex9
# grade the exercise 9 of the lab 3
grade_lab3_ex9( shor_qpe )
# import the IBM's Qiskit Jupyter Tools
import qiskit.tools.jupyter
# show the table of the IBM's Qiskit version
%qiskit_version_table
|
https://github.com/rubenandrebarreiro/ibm-qiskit-global-summer-school-2023
|
rubenandrebarreiro
|
# import the quantum circuit, quantum register, and classical register
# from the IBM's Qiskit library
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
# import the numpy library
import numpy as np
# define the function to generate the quantum circuit
# for the 1st step of the Iterative Phase Estimation (IPE) of the S gate
def step_1_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# notes:
# - qr is a quantum register with 2 qubits
# - cr is a classical register with 2 bits
# create a quantum circuit with the quantum register and with
# the classical register defined before, to implement
# the 1st step of the Iterative Phase Estimation (IPE) of the S gate
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# apply the Pauli-X gate to the 1st qubit (auxiliary qubit)
qc.x(1)
# apply the Controlled-Phase gate for the theta angle equal to pi,
# with control on the 1st qubit and target on the 2nd qubit
qc.cp( np.pi, 0, 1 )
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# measure the state of the 1st qubit (system's qubit),
# storing the classical outcome on the 1st bit of
# the classical register
qc.measure(0, 0)
# return the quantum circuit
# for the Iterative Phase Estimation (IPE) of the S gate
return qc
# create the quantum register for
# the quantum circuit to implement the 1st step of
# the Iterative Phase Estimation (IPE) of the S gate
qr = QuantumRegister(2, "q")
# create the classical register for
# the quantum circuit to implement the 1st step of
# the Iterative Phase Estimation (IPE) of the S gate
cr = ClassicalRegister(2, "c")
# create the quantum circuit to implement the 1st step of
# the Iterative Phase Estimation (IPE) of
# the S gate, with the quantum register
# and the classical register defined before
qc = QuantumCircuit(qr, cr)
# create the quantum circuit implementing the 1st step of
# the Iterative Phase Estimation (IPE) of the S gate
qc = step_1_circuit(qr, cr)
# draw the quantum circuit implementing the 1st step of
# the Iterative Phase Estimation (IPE) of the S gate
qc.draw("mpl")
# submit your circuit
# import the grader for the exercise 1 of the lab 4
from qc_grader.challenges.qgss_2023 import grade_lab4_ex1
# grade the exercise 1 of the lab 4
grade_lab4_ex1( qc )
# define the function to generate the quantum circuit
# for the 2nd step of the Iterative Phase Estimation (IPE) of the S gate
def step_2_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# notes:
# - qr is a quantum register with 2 qubits
# - cr is a classical register with 2 bits
# retrieve the quantum circuit implementing the 1st step of
# the Iterative Phase Estimation (IPE) of the S gate
qc = step_1_circuit(qr, cr)
####### your code goes here #######
# reset the state of the 1st qubit (system's qubit)
qc.reset(0)
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# if the 1st bit of the classical register of
# the dynamic quantum circuit has the classical state 1
with qc.if_test( ( cr[0], True ) ):
# apply the phase correction of -pi / 2 to
# the 1st qubit of the quantum register with a P gate
qc.p( -np.pi / 2, 0 )
# apply the Controlled-Phase gate for the theta angle equal to pi / 2,
# with control on the 1st qubit and target on the 2nd qubit
qc.cp( np.pi / 2, 0, 1 )
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# measure the state of the 1st qubit (system's qubit),
# storing the classical outcome on the 2nd bit of
# the classical register
qc.measure(0, 1)
# return the quantum circuit implementing the 2nd step of
# the Iterative Phase Estimation (IPE) of the S gate
return qc
# create the quantum register for
# the quantum circuit to implement the 2nd step of
# the Iterative Phase Estimation (IPE) of the S gate
qr = QuantumRegister(2, "q")
# create the classical register for
# the quantum circuit to implement the 2nd step of
# the Iterative Phase Estimation (IPE) of the S gate
cr = ClassicalRegister(2, "c")
# create the quantum circuit to implement the 2nd step of
# the Iterative Phase Estimation (IPE) of
# the S gate, with the quantum register
# and the classical register defined before
qc = QuantumCircuit(qr, cr)
# create the quantum circuit implementing the 2nd step of
# the Iterative Phase Estimation (IPE) of the S gate
qc = step_2_circuit(qr, cr)
# draw the quantum circuit implementing the 2nd step of
# the Iterative Phase Estimation (IPE) of the S gate
qc.draw("mpl")
# submit your circuit
# import the grader for the exercise 2 of the lab 4
from qc_grader.challenges.qgss_2023 import grade_lab4_ex2
# grade the exercise 2 of the lab 4
grade_lab4_ex2( qc )
# import the Aer Simulator from the IBM's Qiskit Aer module
from qiskit_aer import AerSimulator
# create an Aer Simulator object
sim = AerSimulator()
# create a job for the quantum circuit implementing
# the IPE for the S gate, running the Aer Simulator
job = sim.run(qc, shots=1000)
# retrieve the result counts of the quantum simulation
result = job.result()
# retrieve the result counts of the quantum simulation
counts = result.get_counts()
# show the result counts of the quantum simulation
counts
# import the quantum circuit, quantum register, and classical register
# from the IBM's Qiskit library
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
# import the numpy library
import numpy as np
# define the function to generate the quantum circuit
# for the Iterative Phase Estimation (IPE) of the T gate
def t_gate_ipe_circuit( qr: QuantumRegister, cr: ClassicalRegister ) -> QuantumCircuit:
# notes:
# - qr is a quantum register with 2 qubits
# - cr is a classical register with 3 bits
# create a quantum circuit with the quantum register and with
# the classical register defined before, to implement
# the Iterative Phase Estimation (IPE) of the T gate
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# apply the Pauli-X gate to the 1st qubit (auxiliary qubit)
qc.x(1)
# apply the Controlled-Phase gate for the theta angle equal to pi,
# with control on the 1st qubit and target on the 2nd qubit
qc.cp( np.pi, 0, 1 )
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# measure the state of the 1st qubit (system's qubit),
# storing the classical outcome on the 1st bit of
# the classical register
qc.measure(0, 0)
# reset the state of the 1st qubit (system's qubit)
qc.reset(0)
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# if the 1st bit of the classical register of
# the dynamic quantum circuit has the classical state 1
with qc.if_test( ( cr[0], True ) ):
# apply the phase correction of -pi / 2 to
# the 1st qubit of the quantum register with a P gate
qc.p( -np.pi / 2, 0 )
# apply the Controlled-Phase gate for the theta angle equal to pi / 2,
# with control on the 1st qubit and target on the 2nd qubit
qc.cp( np.pi / 2, 0, 1 )
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# measure the state of the 1st qubit (system's qubit),
# storing the classical outcome on the 2nd bit of
# the classical register
qc.measure(0, 1)
# reset the state of the 1st qubit (system's qubit)
qc.reset(0)
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# if the 1st bit of the classical register of
# the dynamic quantum circuit has the classical state 1
with qc.if_test( ( cr[0], True ) ):
# apply the phase correction of -pi / 2 to
# the 1st qubit of the quantum register with a P gate
qc.p(-np.pi / 4, 0)
# apply the Controlled-Phase gate for the theta angle equal to pi / ,
# with control on the 1st qubit and target on the 2nd qubit
qc.cp( np.pi / 4, 0, 1 )
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# measure the state of the 1st qubit (system's qubit),
# storing the classical outcome on the 3rd bit of
# the classical register
qc.measure(0, 2)
# return the quantum circuit
# for the Iterative Phase Estimation (IPE) of the T gate
return qc
# create the quantum register for the quantum circuit to
# implement the Iterative Phase Estimation (IPE) of the T gate
qr = QuantumRegister(2, "q")
# create the classical register for the quantum circuit to
# implement the Iterative Phase Estimation (IPE) of the T gate
cr = ClassicalRegister(3, "c")
# create the quantum circuit to implement
# the Iterative Phase Estimation (IPE) of
# the T gate, with the quantum register
# and the classical register defined before
qc = QuantumCircuit(qr, cr)
# create the quantum circuit implementing
# the Iterative Phase Estimation (IPE) of the T gate
qc = t_gate_ipe_circuit(qr, cr)
# draw the quantum circuit implementing
# the Iterative Phase Estimation (IPE) of the T gate
qc.draw("mpl")
# import the Aer Simulator from the IBM's Qiskit Aer module
from qiskit_aer import AerSimulator
# create an Aer Simulator object
sim = AerSimulator()
# create a job for the quantum circuit implementing
# the IPE for the T gate, running the Aer Simulator
job = sim.run(qc, shots=1000)
# retrieve the result counts of the quantum simulation
result = job.result()
# retrieve the result counts of the quantum simulation
counts = result.get_counts()
# show the result counts of the quantum simulation
counts
# submit your circuit
# import the grader for the exercise 3 of the lab 4
from qc_grader.challenges.qgss_2023 import grade_lab4_ex3
# grade the exercise 3 of the lab 4
grade_lab4_ex3( qc )
# import the quantum circuit, quantum register, and classical register
# from the IBM's Qiskit library
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
# import the numpy library
import numpy as np
# define the function to generate the quantum circuit
# for the Iterative Phase Estimation (IPE) of an U gate
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# notes:
# - qr is a quantum register with 2 qubits
# - cr is a classical register with 2 bits
# create a quantum circuit with the quantum register and with
# the classical register defined before, to implement
# the Iterative Phase Estimation (IPE) of the U gate
qc = QuantumCircuit(qr, cr)
# retrieve the two qubits of the quantum register
q0, q1 = qr
# retrieve the two bits of the classical register
c0, c1 = cr
####### your code goes here #######
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(q0)
# apply the Pauli-X gate to the 1st qubit (auxiliary qubit)
qc.x(q1)
# define the theta angle of the U gate as 2 * pi / 3
u_angle = 2 * np.pi / 3
# define the number of the current iteration for
# the Iterative Phase Estimation (IPE) of the U gate
k = 1
# define the theta angle of the Controlled-Phase gate,
# according to the current iteration of
# the Iterative Phase Estimation (IPE) of the U gate
cphase_angle = u_angle * 2**k
# apply the Controlled-Phase gate for the kth theta angle,
# with control on the 1st qubit and target on the 2nd qubit
qc.cp( cphase_angle, q0, q1 )
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(q0)
# measure the state of the 1st qubit (system's qubit),
# storing the classical outcome on the 1st bit of
# the classical register
qc.measure(q0, c0)
# reset the state of the 1st qubit (system's qubit)
qc.reset(q0)
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(q0)
# define the number of the current iteration for
# the Iterative Phase Estimation (IPE) of the U gate
k = 0
# define the theta angle of the Controlled-Phase gate,
# according to the current iteration of
# the Iterative Phase Estimation (IPE) of the U gate
cphase_angle = u_angle * 2**k
# if the 1st bit of the classical register of
# the dynamic quantum circuit has the classical state 1
with qc.if_test( ( cr[0], True ) ):
# apply the phase correction of the kth theta angle to
# the 1st qubit of the quantum register with a P gate
qc.p( -cphase_angle, q0 )
# apply the Controlled-Phase gate for the kth theta angle,
# with control on the 1st qubit and target on the 2nd qubit
qc.cp( cphase_angle, q0, q1 )
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(q0)
# measure the state of the 1st qubit (system's qubit),
# storing the classical outcome on the 2nd bit of
# the classical register
qc.measure(q0, c1)
# return the quantum circuit
# for the Iterative Phase Estimation (IPE) of an U gate
return qc
# create the quantum register for the quantum circuit to
# implement the Iterative Phase Estimation (IPE) of the U gate
qr = QuantumRegister(2, "q")
# create the classical register for the quantum circuit to
# implement the Iterative Phase Estimation (IPE) of the U gate
cr = ClassicalRegister(2, "c")
# create the quantum circuit to implement
# the Iterative Phase Estimation (IPE) of
# the U gate, with the quantum register
# and the classical register defined before
qc = QuantumCircuit(qr, cr)
# create the quantum circuit implementing
# the Iterative Phase Estimation (IPE) of the U gate
qc = u_circuit(qr, cr)
# draw the quantum circuit implementing
# the Iterative Phase Estimation (IPE) of the U gate
qc.draw("mpl")
# import the Aer Simulator from the IBM's Qiskit Aer module
from qiskit_aer import AerSimulator
# create an Aer Simulator object
sim = AerSimulator()
# create a job for the quantum circuit implementing
# the IPE for the U gate, running the Aer Simulator
job = sim.run(qc, shots=1000)
# retrieve the result counts of the quantum simulation
result = job.result()
# retrieve the result counts of the quantum simulation
counts = result.get_counts()
# print the result counts of the quantum simulation
print(counts)
# compute the success probability of the correct outcome
success_probability = counts["01"] / counts.shots()
# print the success probability of the correct outcome
print(f"Success probability: {success_probability}")
# import the quantum circuit, quantum register, and classical register
# from the IBM's Qiskit library
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
# import the numpy library
import numpy as np
# define the function to generate the quantum circuit
# for the Iterative Phase Estimation (IPE) of an U gate
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# notes:
# - qr is a quantum register with 2 qubits
# - cr is a classical register with 1 bit
# create a quantum circuit with the quantum register and with
# the classical register defined before, to implement
# the Iterative Phase Estimation (IPE) of the U gate
qc = QuantumCircuit(qr, cr)
# retrieve the two qubits of the quantum register
q0, q1 = qr
# retrieve bit of the classical register
c0 = cr
####### your code goes here #######
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(q0)
# apply the Pauli-X gate to the 1st qubit (auxiliary qubit)
qc.x(q1)
# define the theta angle of the U gate as 2 * pi / 3
u_angle = 2 * np.pi / 3
# define the number of the current iteration for
# the Iterative Phase Estimation (IPE) of the U gate
k = 1
# define the theta angle of the Controlled-Phase gate,
# according to the current iteration of
# the Iterative Phase Estimation (IPE) of the U gate
cphase_angle = u_angle * 2**k
# apply the Controlled-Phase gate for the kth theta angle,
# with control on the 1st qubit and target on the 2nd qubit
qc.cp( cphase_angle, q0, q1 )
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(q0)
# measure the state of the 1st qubit (system's qubit),
# storing the classical outcome on the 1st bit of
# the classical register
qc.measure(q0, c0)
# return the quantum circuit
# for the Iterative Phase Estimation (IPE) of an U gate
return qc
# create the quantum register for the quantum circuit to
# implement the Iterative Phase Estimation (IPE) of the U gate
qr = QuantumRegister(2, "q")
# create the classical register for the quantum circuit to
# implement the Iterative Phase Estimation (IPE) of the U gate
cr = ClassicalRegister(1, "c")
# create the quantum circuit to implement
# the Iterative Phase Estimation (IPE) of
# the U gate, with the quantum register
# and the classical register defined before
qc = QuantumCircuit(qr, cr)
# create the quantum circuit implementing
# the Iterative Phase Estimation (IPE) of the U gate
qc = u_circuit(qr, cr)
# draw the quantum circuit implementing
# the Iterative Phase Estimation (IPE) of the U gate
qc.draw("mpl")
# create a job for the quantum circuit implementing
# the IPE for the U gate, running the Aer Simulator
job = sim.run(qc, shots=15)
# retrieve the result counts of the quantum simulation
result = job.result()
# retrieve the result counts of the quantum simulation
counts = result.get_counts()
# print the result counts of the quantum simulation
print(counts)
# define the variable for
# the bit resulting from the 1st step of
# the Iterative Phase Estimation (IPE)
step1_bit: int
####### your code goes here #######
# define the bit resulting from the 1st step of
# the Iterative Phase Estimation (IPE)
step1_bit = 1
# print the bit resulting from the 1st step of
# the Iterative Phase Estimation (IPE)
print(step1_bit)
# submit your result
# import the grader for the exercise 4 of the lab 4
from qc_grader.challenges.qgss_2023 import grade_lab4_ex4
# grade the exercise 4 of the lab 4
grade_lab4_ex4( step1_bit )
# import the quantum circuit, quantum register, and classical register
# from the IBM's Qiskit library
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
# import the numpy library
import numpy as np
# define the function to generate the quantum circuit
# for the Iterative Phase Estimation (IPE) of an U gate,
# based on the classical bit obtained from the 1st step
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# notes:
# - qr is a quantum register with 2 qubits
# - cr is a classical register with 1 bit
# create a quantum circuit with the quantum register and with
# the classical register defined before, to implement
# the Iterative Phase Estimation (IPE) of the U gate
qc = QuantumCircuit(qr, cr)
# retrieve the two qubits of the quantum register
q0, q1 = qr
# retrieve the two bit of the classical register
c0, c1 = cr
####### your code goes here #######
# if the classical bit obtained from
# the 1st step is the classical state 1
with qc.if_test( ( step1_bit, True ) ):
# apply the Pauli-X gate to the 1st qubit (system's qubit)
qc.x(q0)
# apply the Pauli-X gate to the 2nd qubit (auxiliary qubit)
qc.x(q1)
# define the theta angle of the U gate as pi / 3
u_angle = np.pi / 3
# define the number of the current iteration for
# the Iterative Phase Estimation (IPE) of the U gate
k = 1
# define the theta angle of the Controlled-Phase gate,
# according to the current iteration of
# the Iterative Phase Estimation (IPE) of the U gate
cphase_angle = u_angle * 2**k
# apply the Controlled-Phase gate for the kth theta angle,
# with control on the 1st qubit and target on the 2nd qubit
qc.cp( cphase_angle, q0, q1 )
# measure the state of the 2nd qubit (auxiliary qubit),
# storing the classical outcome on the 1st bit of
# the classical register
qc.measure(q1, c0)
# return the quantum circuit
# for the Iterative Phase Estimation (IPE) of an U gate,
# based on the classical bit obtained from the 1st step
return qc
# create the quantum register for the quantum circuit to
# implement the Iterative Phase Estimation (IPE) of the U gate,
# based on the classical bit obtained from the 1st step
qr = QuantumRegister(2, "q")
# create the classical register for the quantum circuit to
# implement the Iterative Phase Estimation (IPE) of the U gate,
# based on the classical bit obtained from the 1st step
cr = ClassicalRegister(2, "c")
# create the quantum circuit to implement
# the Iterative Phase Estimation (IPE) of
# the U gate, based on the classical bit
# obtained from the 1st step,
# with the quantum register and
# the classical register defined before
qc = QuantumCircuit(qr, cr)
# create the quantum circuit implementing
# the Iterative Phase Estimation (IPE) of the U gate,
# based on the classical bit obtained from the 1st step
qc = u_circuit(qr, cr)
# draw the quantum circuit implementing
# the Iterative Phase Estimation (IPE) of the U gate,
# based on the classical bit obtained from the 1st step
qc.draw("mpl")
# submit your result
# import the grader for the exercise 5 of the lab 4
from qc_grader.challenges.qgss_2023 import grade_lab4_ex5
# grade the exercise 5 of the lab 4
grade_lab4_ex5( qc )
# import the Aer Simulator from the IBM's Qiskit Aer module
from qiskit_aer import AerSimulator
# create an Aer Simulator object
sim = AerSimulator()
# create a job for the quantum circuit implementing
# the IPE for the U gate, running the Aer Simulator
job = sim.run(qc, shots=1000)
# retrieve the result counts of the quantum simulation
result = job.result()
# retrieve the result counts of the quantum simulation
counts = result.get_counts()
# print the result counts of the quantum simulation
print(counts)
# compute the success probability of the correct outcome
success_probability = counts["01"] / counts.shots()
# print the success probability of the correct outcome
print(f"Success probability: {success_probability}")
# import the Gate from the IBM's Qiskit Circuit module
from qiskit.circuit import Gate
# define the function to generate the dynamic quantum circuit
# for a general Iterative Phase Estimation (IPE)
def iterative_phase_estimation(
qr: QuantumRegister,
cr: ClassicalRegister,
controlled_unitaries: list[Gate],
state_prep: Gate,
) -> QuantumCircuit:
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
# retrieve the number of the Controlled-U gates
m = len( controlled_unitaries )
# create a copy of the list of the Controlled-U gates
controlled_unitaries_reversed = controlled_unitaries.copy()
# retrieve the reverse list of the Controlled-U gates
controlled_unitaries_reversed.reverse()
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# initialize the preparation of the state
# with the eigenstate |1>
qc.append( state_prep, [1] )
# apply the Controlled-U gate for t = (m - 1)
qc.append( controlled_unitaries_reversed[0], [0, 1] )
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# measure the state of the 1st qubit (system's qubit),
# storing the classical outcome on the 1st bit
qc.measure(0, 0)
# for the remaining (m - 1) iterations
for k in range(1, m):
# reset the state of the 1st qubit (system's qubit)
qc.reset(0)
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# if the 1st bit of the classical register of
# the dynamic quantum circuit has the classical state 1
with qc.if_test( ( cr[0], 1 ) ):
# apply the phase correction to the 1st qubit of
# the quantum register with a P gate
qc.p( -controlled_unitaries[ ( m - k - 1 ) ].params[0], 0 )
# apply the Controlled-U gate for t = (m - k)
qc.append( controlled_unitaries_reversed[k], [0, 1] )
# apply the Hadamard gate to the 1st qubit (system's qubit)
qc.h(0)
# measure the state of the 1st qubit (system's qubit),
# storing the classical outcome on the kth bit
qc.measure(0, k)
# return the dynamic quantum circuit
# for a general Iterative Phase Estimation (IPE)
return qc
# import the Controlled-Phase and Pauli-X gates
# from the IBM's Qiskit Circuit Library module
from qiskit.circuit.library import CPhaseGate, XGate
# create the quantum register with two qubits
# for the quantum circuit to implement IPE on the Z gate
qr = QuantumRegister(2, "q")
# create the quantum register with three bits
# for the quantum circuit to implement IPE on the Z gate
cr = ClassicalRegister(1, "c")
# define the theta angle for the Z gate
z_angle = np.pi
# create the list of Controlled-U/Controlled-Phases gates,
# considering the theta angle for the Z gate
controlled_unitaries = [ CPhaseGate( z_angle * 2**k ) for k in range(1) ]
# generate the quantum circuit implementing
# the IPE for the Z gate
qc = iterative_phase_estimation( qr, cr, controlled_unitaries, XGate() )
# draw the quantum circuit implementing
# the IPE for the Z gate
qc.draw("mpl")
# create an Aer Simulator object
sim = AerSimulator()
# create a job for the quantum circuit implementing
# the IPE for the Z gate, running the Aer Simulator
job = sim.run(qc, shots=1000)
# retrieve the result counts of the quantum simulation
result = job.result()
# retrieve the result counts of the quantum simulation
counts = result.get_counts()
# show the result counts of the quantum simulation
counts
# import the Controlled-Phase and Pauli-X gates
# from the IBM's Qiskit Circuit Library module
from qiskit.circuit.library import CPhaseGate, XGate
# create the quantum register with two qubits
# for the quantum circuit to implement IPE on the S gate
qr = QuantumRegister(2, "q")
# create the quantum register with three bits
# for the quantum circuit to implement IPE on the S gate
cr = ClassicalRegister(2, "c")
# define the theta angle for the S gate
s_angle = np.pi / 2
# create the list of Controlled-U/Controlled-Phase gates,
# considering the theta angle for the S gate
controlled_unitaries = [ CPhaseGate( s_angle * 2**k ) for k in range(2) ]
# generate the quantum circuit implementing
# the IPE for the S gate
qc = iterative_phase_estimation( qr, cr, controlled_unitaries, XGate() )
# draw the quantum circuit implementing
# the IPE for the S gate
qc.draw("mpl")
# create an Aer Simulator object
sim = AerSimulator()
# create a job for the quantum circuit implementing
# the IPE for the S gate, running the Aer Simulator
job = sim.run(qc, shots=1000)
# retrieve the result counts of the quantum simulation
result = job.result()
# retrieve the result counts of the quantum simulation
counts = result.get_counts()
# show the result counts of the quantum simulation
counts
# import the Controlled-Phase and Pauli-X gates
# from the IBM's Qiskit Circuit Library module
from qiskit.circuit.library import CPhaseGate, XGate
# create the quantum register with two qubits
# for the quantum circuit to implement IPE on the T gate
qr = QuantumRegister(2, "q")
# create the quantum register with three bits
# for the quantum circuit to implement IPE on the T gate
cr = ClassicalRegister(3, "c")
# define the theta angle for the T gate
t_angle = np.pi / 4
# create the list of Controlled-U/Controlled-Phase gates,
# considering the theta angle for the T gate
controlled_unitaries = [ CPhaseGate( t_angle * 2**k ) for k in range(3) ]
# generate the quantum circuit implementing
# the IPE for the T gate
qc = iterative_phase_estimation( qr, cr, controlled_unitaries, XGate() )
# draw the quantum circuit implementing
# the IPE for the T gate
qc.draw("mpl")
# create an Aer Simulator object
sim = AerSimulator()
# create a job for the quantum circuit implementing
# the IPE for the T gate, running the Aer Simulator
job = sim.run(qc, shots=1000)
# retrieve the result counts of the quantum simulation
result = job.result()
# retrieve the result counts of the quantum simulation
counts = result.get_counts()
# show the result counts of the quantum simulation
counts
# import the IBMps Provider from Qiskit IBM Provider module
from qiskit_ibm_provider import IBMProvider
# create an IBM's Provider object
provider = IBMProvider()
# define the hub for the IBM's Provider
hub = "summer-school-6"
# define the group for the IBM's Provider
group = "group-3"
# define the project for the IBM's Provider
project = "7048813929"
# define the backend's name for the IBM's Provider
backend_name = "ibmq_manila"
# retrieve the backend from the IBM's Provider
backend = provider.get_backend( backend_name, instance=f"{hub}/{group}/{project}" )
# import the transpile feature
# from the IBM's Qiskit library
from qiskit import transpile
# create the quantum register with two qubits
# for the quantum circuit to implement IPE on the S gate
qr = QuantumRegister(2, "q")
# create a classical register with two bits
# for the quantum circuit to implement IPE on the S gate
cr = ClassicalRegister(2, "c")
# create the quantum circuit with
# the quantum and classical registers
# defined before to implement IPE on the S gate
qc = QuantumCircuit(qr, cr)
# perform the 2nd step of the IPE on the S gate to
# the quantum circuit created before
qc = step_2_circuit(qr, cr)
# create the transpiled quantum circuit
# to implement IPE on the S gate
qc_transpiled = transpile(qc, backend)
# draw the quantum circuit implementing
# an IPE on the S gate
qc_transpiled.draw("mpl")
# OPTIONAL: run the job of the IPE for the S gate
# run the transpiled dynamic quantum circuit of
# the IPE for the S gate
#job = backend.run(qc_transpiled, shots=1000, dynamic=True)
# retrieve the id of the job of the quantum simulation
# for the IPE for the S gate
#job_id = job.job_id()
# print the id of the job of the quantum simulation
# for the IPE for the S gate
#print(job_id)
# OPTIONAL: retrieve and show the job's status of the IPE for the S gate
# retrieve the job of the quantum simulation
# for the IPE for the S gate
#retrieve_job = provider.retrieve_job(job_id)
# show the job's status of the quantum simulation
# for the IPE for the S gate
#retrieve_job.status()
# OPTIONAL: plot the histogram of the results of the IPE for the S gate
# import the plot histogram from
# the IBM's Qiskit Tools' Visualization module
#from qiskit.tools.visualization import plot_histogram
# retrieve the counts of the results of the job
# for the quantum simulation for the IPE for the S gate
#counts = retrieve_job.result().get_counts()
# plot the historgram of the count results of
# the quantum simulation for the IPE for the S gate
#plot_histogram(counts)
# import the IBM's Qiskit Jupyter Tools
import qiskit.tools.jupyter
# show the table of the IBM's Qiskit version
%qiskit_version_table
|
https://github.com/rubenandrebarreiro/ibm-qiskit-global-summer-school-2023
|
rubenandrebarreiro
|
# import the quantum circuit and the quantum register
# from the IBM's Qiskit library
from qiskit import QuantumCircuit, QuantumRegister
# import the Sparse Pauli operator from
# the IBM's Qiskit quantum information module
from qiskit.quantum_info import SparsePauliOp
# defome the function to generate a Sparse Pauli operator
# for the Heisenberg's Hamiltonian
def heisenberg_hamiltonian(
length: int, jx: float = 1.0, jy: float = 0.0, jz: float = 0.0
) -> SparsePauliOp:
# create an empty list for the terms
terms = []
# for each index ranged for the number of qubits on
# the Heisenberg's Hamiltonian
for i in range( ( length - 1 ) ):
# if it is pretended to append a XX operator term to
# the Heisenberg's Hamiltonian operator
if jx:
# append a XX operator term to
# the Heisenberg's Hamiltonian operator
terms.append( ( "XX", [i, i + 1], jx ) )
# if it is pretended to append a YY operator term to
# the Heisenberg's Hamiltonian operator
if jy:
# append a YY operator term to
# the Heisenberg's Hamiltonian operator
terms.append( ( "YY", [i, i + 1], jy ) )
# if it is pretended to append a ZZ operator term to
# the Heisenberg's Hamiltonian operator
if jz:
# append a ZZ operator term to
# the Heisenberg's Hamiltonian operator
terms.append( ( "ZZ", [i, i + 1], jz ) )
# return the Sparse Pauli operator
# for the Heisenberg's Hamiltonian
return SparsePauliOp.from_sparse_list(terms, num_qubits=length)
# define a function to generate the quantum circuit for the state preparation
def state_prep_circuit( num_qubits: int, layers: int = 1 ) -> QuantumCircuit:
# create a quantum register with the number of qubits pretended
qubits = QuantumRegister(num_qubits, name="q")
# create a quantum circuit with the quantum register defined before
circuit = QuantumCircuit(qubits)
# apply a Hadamard gate to
# the quantum circuit, on all the qubits
circuit.h(qubits)
# for each layer of the quantum circuit
for _ in range(layers):
# for each 2n-th qubit
for i in range(0, ( num_qubits - 1 ), 2):
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on the current qubit
# and target on the next qubit
circuit.cx( qubits[i], qubits[ ( i + 1 ) ] )
# apply a RY (Rotation-Y) gate to
# the quantum circuit, on the 1st qubit,
# with the theta angle equal to 0.1
# on all the qubits
circuit.ry( 0.1, qubits )
# for each (2n + 1)-th qubit
for i in range(1, ( num_qubits - 1 ), 2):
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on the current qubit
# and target on the next qubit
circuit.cx( qubits[i], qubits[ ( i + 1 ) ] )
# apply a RY (Rotation-Y) gate to
# the quantum circuit, on the 1st qubit,
# with the theta angle equal to 0.1
# on all the qubits
circuit.ry(0.1, qubits)
# return the quantum circuit for the state preparation
return circuit
# define the number of qubits for
# the Heisenberg's Hamiltonian operator and
# for the state preparation quantum circuit
length = 5
# create the Heisenberg's Hamiltonian operator
# for the number of qubits defined before
hamiltonian = heisenberg_hamiltonian( length, 1.0, 1.0 )
# create the state preparation quantum circuit
# for the number of qubits defined before
circuit = state_prep_circuit( length, layers=2 )
# print the Heisenberg's Hamiltonian operator
print(hamiltonian)
# draw the quantum circuit implementing
# a state preparation
circuit.draw("mpl")
# import estimator from IBM's Qiskit
# Aer primitives module
from qiskit_aer.primitives import Estimator
# create an Estimator object with approximation
estimator = Estimator( approximation=True )
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=None )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the exact expectation value (energy)
# from the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
exact_value = result.values[0]
# print the exact expectation value (energy)
# from the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
print( f"Exact energy: {exact_value}" )
# import the IBM's Qiskit Runtime Service
# from the Qiskit IBM's Runtime
from qiskit_ibm_runtime import QiskitRuntimeService
# define the hub for the IBM's Qiskit
# Runtime Service
hub = "ibm-q-internal"
# define the group for the IBM's Qiskit
# Runtime Service
group = "deployed"
# define the project for the IBM's Qiskit
# Runtime Service
project = "default"
# create an IBM's Qiskit Runtime Service
service = QiskitRuntimeService(instance=f"{hub}/{group}/{project}")
# import the estimator, options and session
# for quantum simulations from the Qiskit IBM Runtime module
from qiskit_ibm_runtime import Estimator, Options, Session
# import the coupling map from
# the IBM's Qiskit Transpiler module
from qiskit.transpiler import CouplingMap
# define the backend to run the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime
backend = service.get_backend("simulator_statevector")
# set the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime
simulator = {
"basis_gates": ["id", "rz", "sx", "cx", "reset"],
"coupling_map": list(CouplingMap.from_line(length + 1)),
}
# define the number of shots for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime
shots = 10000
# import the built-in math module
import math
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 0 (zero)
options = Options(
simulator=simulator,
resilience_level=0,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# import the noise model and the readout error
# from the IBM's Qiskit Aer Noise module
from qiskit_aer.noise import NoiseModel, ReadoutError
# create a noise model
noise_model = NoiseModel()
##### your code here #####
# create the measurement miss-assignments and
# correct measurement probabilities
# create the measurement miss-assignment
# probabilities for the 1st qubit,
# for the erroneous measurement outcomes
qubit0_p0_given1 = 0.2
qubit0_p1_given0 = 0.5
# create the correct measurement
# probabilities for the 1st qubit
qubit0_p0_given0 = (1 - qubit0_p0_given1)
qubit0_p1_given1 = (1 - qubit0_p1_given0)
# create the measurement miss-assignment
# probabilities for the remaining qubits k_i,
# for the erroneous measurement outcomes
qubitk_p0_given1 = 0.02
qubitk_p1_given0 = 0.05
# create the correct measurement
# probabilities for the remaining qubits k_i
qubitk_p0_given0 = (1 - qubitk_p0_given1)
qubitk_p1_given1 = (1 - qubitk_p1_given0)
# create the readout error objects
# create a readout error for the 1st qubit
readout_error_qubit0 = ReadoutError( [ [ qubit0_p0_given0, qubit0_p0_given1 ],
[ qubit0_p1_given0, qubit0_p1_given1 ] ] )
# ceeate a readout error for the remaining qubits k_i
readout_error_qubitk = ReadoutError( [ [ qubitk_p0_given0, qubitk_p0_given1 ],
[ qubitk_p1_given0, qubitk_p1_given1 ] ] )
# add a readout error to the noise model for the 1st qubit
noise_model.add_readout_error( readout_error_qubit0, [0] )
# for each of the remaining qubits k_i
# note: recall that even though our circuit acts on 5 qubits,
# we will initialize a simulator with 6 qubits in order to
# later demonstrate the potential effects of qubit choice
for k in range( 1, ( length + 1 ) ):
# add a readout error to the noise model
# for the remaining qubits k_i
noise_model.add_readout_error( readout_error_qubitk, [k] )
# print the noise model created before
print(noise_model)
# submit your answer
# import the grader for the exercise 1 of the lab 5
from qc_grader.challenges.qgss_2023 import grade_lab5_ex1
# grade the exercise 1 of the lab 5
grade_lab5_ex1(noise_model)
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# considering the noise model defined before,
# and a resilience level of 0 (zero)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=0,
transpilation=dict( initial_layout=list( range(length) ) ),
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# considering the noise model defined before,
# and a resilience level of 0 (zero),
# but this time, with a layout where
# the 1st qubit is not considered
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=0,
transpilation=dict( initial_layout=list( range(1, ( length + 1 ) ) ) ),
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# considering the noise model defined before,
# and a resilience level of 1 (one),
# but this time, with a layout where
# the 1st qubit is not considered
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=1,
transpilation=dict( initial_layout=list( range( 1, ( length + 1 ) ) ) ),
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the variable for
# the new number of shots
new_shots: int
##### your code here #####
# define the new number of shots
new_shots = 20000
# submit your answer
# import the grader for the exercise 2 of the lab 5
from qc_grader.challenges.qgss_2023 import grade_lab5_ex2
# grade the exercise 2 of the lab 5
grade_lab5_ex2(new_shots)
# import the noise model and the depolarizing error
# from the IBM's Qiskit Aer Noise module
from qiskit_aer.noise import depolarizing_error
# creata a noise model
noise_model = NoiseModel()
##### your code here #####
# create the depolarizaation probability
depolarization_prob = 0.01
# create the depolarization error objects
# create a two-qubit depolarization error for two qubits
depolarizing_error_two_quits = depolarizing_error( depolarization_prob, 2 )
# add the two-qubit depolarization error after each CNOT/CX gate
noise_model.add_all_qubit_quantum_error( depolarizing_error_two_quits, ['cx'] )
# print the noise model created before
print(noise_model)
# submit your answer
# import the grader for the exercise 3 of the lab 5
from qc_grader.challenges.qgss_2023 import grade_lab5_ex3
# grade the exercise 3 of the lab 5
grade_lab5_ex3(noise_model)
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 1 (one)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=1,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 2 (two)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=2,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variances of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian,
# applying Zero-Noise Extrapolation with Noise Amplification
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
# print the statistics for the estimated energy,
# the energy error, and the variances
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
# import Pauli error from
# the IBM's Qiskit Aer Noise module
from qiskit_aer.noise import pauli_error
# create a noise model
noise_model = NoiseModel()
##### your code here #####
# create the Pauli error probability
pauli_error_prob = 0.1
# create the Pauli error objects
# create a bit flip error for a qubit
bit_flip_error = pauli_error( [ ( "X", pauli_error_prob ),
( "I", ( 1 - pauli_error_prob ) ) ] )
# add a bit flip error for a qubit,
# after each Pauli-X, Pauli-Y, Pauli-Z, and Hadamard gate
noise_model.add_all_qubit_quantum_error( bit_flip_error, ["x", "y", "z", "h"] )
# print the noise model created before
print(noise_model)
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 0 (zero)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=0,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 1 (one)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 2 (two)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variances of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian,
# applying Zero-Noise Extrapolation with Noise Amplification
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
# print the statistics for the estimated energy,
# the energy error, and the variances
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
# import Pauli error from
# the IBM's Qiskit Aer Noise module
from qiskit_aer.noise import pauli_error
# create a noise model
noise_model = NoiseModel()
##### your code here #####
# create the Pauli error probability
pauli_error_prob = 0.1
# create the Pauli error objects
# create a phase flip error for a qubit
phase_flip_error = pauli_error( [ ( "Z", pauli_error_prob ),
( "I", ( 1 - pauli_error_prob ) ) ] )
# add a phase flip error for a qubit,
# after each Pauli-X, Pauli-Y, Pauli-Z, and Hadamard gate
noise_model.add_all_qubit_quantum_error( phase_flip_error, ["x", "y", "z", "h"] )
# print the noise model created before
print(noise_model)
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 0 (zero)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=0,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 1 (one)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=1,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 2 (two)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variances of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian,
# applying Zero-Noise Extrapolation with Noise Amplification
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
# print the statistics for the estimated energy,
# the energy error, and the variances
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
# import Reset error from
# the IBM's Qiskit Aer Noise module
from qiskit_aer.noise import reset_error
# create a noise model
noise_model = NoiseModel()
##### your code here #####
# create the Reset error probabilities
reset_0_prob = 0.2
reset_1_prob = 0.33
# create the Reset error objects
# create a Reset error for a qubit
reset_0_1_error = reset_error( reset_0_prob, reset_1_prob )
# add a Reset error for a qubit,
# after each Pauli-X, Pauli-Y, Pauli-Z, and Hadamard gate
noise_model.add_all_qubit_quantum_error( reset_0_1_error, ["x", "y", "z", "h"] )
# print the noise model created before
print(noise_model)
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 0 (zero)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=0,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 1 (one)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=1,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 2 (two)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variances of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian,
# applying Zero-Noise Extrapolation with Noise Amplification
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
# print the statistics for the estimated energy,
# the energy error, and the variances
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
# import the IBM's Qiskit Jupyter Tools
import qiskit.tools.jupyter
# show the table of the IBM's Qiskit version
%qiskit_version_table
|
https://github.com/arthurfaria/Qiskit_certificate_prep
|
arthurfaria
|
import numpy as np
from qiskit import QuantumCircuit, BasicAer, execute, IBMQ, QuantumRegister, ClassicalRegister
from qiskit.visualization import plot_histogram
from qiskit.compiler import transpile
from qiskit.circuit.library import SGate, XGate
q = QuantumRegister(3, 'qubit')
c = ClassicalRegister(3, 'cbit')
ghz = QuantumCircuit(q,c)
ghz.h(q[0]) # or just 0
ghz.cx(q[0],q[1]) #por just 0,1
ghz.cx(1,2)
#Let us implement some barriers
ghz.barrier(0,2)
ghz.barrier(1)
ghz.barrier()
ghz.measure([0,1,2],[0,1,2])
ghz.draw('mpl',filename='fig.png')
ghz.draw('latex')
#'text' by default
ghz.draw()
ghz.draw('latex_source')
#'text' by default also
print(ghz)
q_a = QuantumRegister(2, 'q_a')
q_b = QuantumRegister(3, 'q_b')
c_a = ClassicalRegister(3,'c_a')
c_b = ClassicalRegister(2,'c_b')
qc_man = QuantumCircuit(q_a, q_b,c_a, c_b)
qc_man.x(0)
qc_man.h(1)
for i in range(4):
qc_man.cx(i,i+1)
qc_man.cx(i+1,i)
qc_man.barrier()
qc_man.cz(0,1)
qc_man.swap(1,4)
qc_man.ccx(0,3,4)
qc_man.barrier()
#q_a qubtis will be stored at c_b bits
qc_man.measure(q_a, c_b)
#q_b qubtis will be stored at c_a bits
qc_man.measure(q_b, c_a)
qc_man.draw('mpl')
#number of qubtis and classical registers
num_qubits = 5
num_bits = 5
#Tirst circuit
qc_comp1 = QuantumCircuit(num_qubits,num_bits)
qc_comp1.h(0)
for i in range(num_qubits-1):
qc_comp1.cx(i,i+1)
qc_comp1.barrier()
#Second circuit
qc_comp2 = QuantumCircuit(num_qubits,num_bits)
for i in reversed(range(num_qubits-1)):
qc_comp2.cx(i,i+1)
qc_comp2.h(0)
qc_comp2.barrier()
#Thid circuit
qc_comp3 = QuantumCircuit(num_qubits, num_bits)
for i in range(num_qubits-1):
qc_comp3.measure([i],[i])
new_circ = qc_comp1.compose(qc_comp2).compose(qc_comp3)
new_circ.draw('mpl')
from qiskit.circuit import Parameter
#theta = 2*np.pi
theta = Parameter('θ')
qc_param = QuantumCircuit(num_qubits-1)
qc_param.rz(theta, range(5-1))
qc_param.barrier()
param_circ = qc_comp1.compose(qc_param).compose(qc_comp2).compose(qc_comp3)
param_circ.draw('mpl')
new_circ2 = qc_comp1 + qc_comp2 + qc_comp3
new_circ2.draw('mpl')
new_circ2.draw(output ='mpl', plot_barriers=False, reverse_bits = True,
style={'backgroundcolor': 'lightblue'}, scale = 0.8)
param_circ.depth()
param_circ.barrier()
param_circ.h(0)
param_circ.depth()
qc_tr = QuantumCircuit(3)
qc_tr.mct([0,1],2)
qc_tr.cx(0,2)
for ii in range(3):
qc_tr.h(ii)
qc_tr.z(ii)
qc_tr.ccx(0,1,2)
qc_tr.p(np.pi/8, 0)
qc_tr.barrier()
qc_tr.tdg(1)
qc_tr.ry(np.pi/14,2)
qc_tr.barrier()
for ii in range(3):
qc_tr.u(np.pi/(ii+1), 0, np.pi, ii)
qc_tr.draw('mpl')
trans = transpile(qc_tr, basis_gates = ['u','cx','t','z'])
trans.draw('mpl')
from qiskit.circuit import Gate
from qiskit.circuit.library import HGate
cust_gate = Gate(name = ' Auf', num_qubits = 2, params =[])
cust_gate1 = Gate(name = 'geht`s', num_qubits = 3, params =[])
#Applying the gate
#lets rename the circuit
qc_gate = QuantumCircuit(6, name ='KoeMenor')
qc_gate.append(cust_gate, [0,1])
qc_gate.append(cust_gate1, [1,2,3])
qc_gate.draw('mpl')
#circuit
qc_aux = QuantumCircuit(4)
#It is possible to name a circuit!
qc_aux.name = "Junge"
lets_go_gate = qc_aux.to_gate()
#circuit to gate
qc_gate.append(lets_go_gate, [2,3,4,5]) #the first two are control
qc_gate.draw('mpl')
qc_to_gate = qc_gate.to_gate()
qc_to_gate.name = 'Wrapping up'
qc_comp = QuantumCircuit(6)
qc_comp.append(qc_to_gate, [0,1,2,3,4,5])
qc_comp.draw('mpl')
qc_decomp0 = qc_comp.decompose()
qc_decomp0.draw('mpl')
# converting to a gate and put it in arbitrary place in the other circuit
sub_inst = qc_gate.to_instruction()
# first circuit
qc_f = QuantumCircuit(num_qubits+1)
qc_f.h(0)
qc_f.x(1)
qc_f.z(2)
qc_f.s(3)
qc_f.y(4)
for i in range(num_qubits+1-1):
qc_f.cz(i,i+1)
qc_f.barrier()
# adding the other
qc_f.append(sub_inst, [0,1,2,3,4,5])
qc_f.draw('mpl')
# decomposing gates
qc_decomp = qc_f.decompose()
qc_decomp.draw('mpl')
#we can specify how many controls we want
gener_cnot = SGate().control(4)
qc_cnot = QuantumCircuit(5)
qc_cnot.append(gener_cnot, [0,1,2,3,4])
qc_cnot.draw('mpl')
#circuit
qc_aux = QuantumCircuit(3)
#of course you can wrap some gates into this genreal one
qc_aux.cx(0,1)
qc_aux.rz(np.pi/2,2)
# or also do not operate with any gate at all
qc_aux.name = "Ó o aue aí"
lets_go_gate = qc_aux.to_gate().control(2)
#circuit to gate
qc_contr = QuantumCircuit(6)
qc_contr.append(lets_go_gate, [0,5,1,3,4])
qc_contr.draw('mpl')
|
https://github.com/arthurfaria/Qiskit_certificate_prep
|
arthurfaria
|
import numpy as np
from qiskit import QuantumCircuit, Aer, IBMQ, assemble, execute, QuantumRegister, ClassicalRegister
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_histogram, plot_bloch_multivector
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
qc = QuantumCircuit(1)
qc.x(0)
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
qc = QuantumCircuit(1)
qc.h(0)
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0)
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
qcX = QuantumCircuit(1)
qcX.u(np.pi, 0, np.pi, 0)
qcX.draw('mpl')
qcZ = QuantumCircuit(1)
qcZ.u(0, 0, np.pi, 0)
qcZ.draw('mpl')
qcY = QuantumCircuit(1)
qcY.u(np.pi, np.pi/2, np.pi/2, 0)
qcY.draw('mpl')
qcH = QuantumCircuit(1)
qcH.u(np.pi/2, 0, np.pi, 0)
qcH.draw('mpl')
n_qubits = 1 #number of qubits
n_bits = 1 #number of bits
q = QuantumRegister(n_qubits, 'qbit' )
c = ClassicalRegister(n_bits, 'cbit' )
qc = QuantumCircuit(q,c)
qc.u(np.pi/4,np.pi/4,np.pi/4, q[0]) #or just 0
qc.measure(0,0)
qc.draw('mpl')
# we choose the simulator as our backend
backend = Aer.get_backend('qasm_simulator')
# we run the simulation and get the counts
Counts = execute(qc, backend, shots = 1024, seed_simulator=312).result().get_counts()
# let us plot a histogram to see the possible outcomes and corresponding probabilities
plot_histogram(Counts)
qc=QuantumCircuit(2,2)
qc.cx(0,1)
qc.draw('mpl')
qc=QuantumCircuit(2,2)
qc.x(0)
qc.cx(0,1)
qc.draw('mpl')
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
for i in range(2):
qc.measure(i,i)
qc.draw('mpl')
# we run the simulation and get the counts
# this will be better exaplained in the notebook 'qasm_simulator_and_visualization.ipynb'
counts = execute(qc, backend, shots = 1024).result().get_counts()
#plot histogram
plot_histogram(counts)
qc = QuantumCircuit(2,2)
qc.h(0)
qc.x(1)
qc.z(0)
qc.cx(0,1)
for i in range(2):
qc.measure(i,i)
qc.draw('mpl')
counts = execute(qc, backend, shots = 1024).result().get_counts()
plot_histogram(counts)
|
https://github.com/arthurfaria/Qiskit_certificate_prep
|
arthurfaria
|
import numpy as np
from qiskit import QuantumCircuit, BasicAer, execute
from qiskit.circuit.library import YGate
from qiskit.quantum_info import Operator, average_gate_fidelity, process_fidelity, state_fidelity
#we define a operator op_a = Ygate
op_a = Operator(YGate())
# we define also op_b=np.exp(1j / 2) * op_a which is essentially op_a but with a global phase np.exp(1j / 2)
op_b = np.exp(1j / 2) * op_a
#we run the fidelity for those gates
average_gate_fidelity(op_a,op_b)
process_fidelity(op_a, op_b)
# same here, but now with a general state
n = 1/np.sqrt(3)
desired_state = [n,np.sqrt(1-n**2)]
qc = QuantumCircuit(1)
qc.initialize(desired_state,0)
qc.draw('mpl')
# we run it with help of a simulator
back_sv = BasicAer.get_backend('statevector_simulator')
result = execute(qc, back_sv).result()
qc_sv = result.get_statevector(qc)
#Now, we run the fidelity for those states and we see they are the same
state_fidelity(desired_state, qc_sv)
|
https://github.com/arthurfaria/Qiskit_certificate_prep
|
arthurfaria
|
from qiskit import IBMQ, BasicAer, QuantumCircuit, execute
import qiskit.tools.jupyter
from qiskit.tools import job_monitor
from qiskit.visualization import plot_gate_map, plot_error_map
from qiskit.providers.ibmq import least_busy
provider = IBMQ.load_account()
%qiskit_version_table
print(qiskit.__qiskit_version__)
## qiskit terra version
print(qiskit.__version__)
%qiskit_copyright
BasicAer.backends()
# It works also for other simulators such as: Aer.backends()
%qiskit_backend_overview
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
print(backend)
# Plot gate map
plot_gate_map(backend, plot_directed = True)
# Plot error map
plot_error_map(backend)
qc_open = QuantumCircuit.from_qasm_file('myfile.qasm')
qc_open.draw('mpl')
temp = QuantumCircuit(2)
temp.h(0)
temp.h(1)
temp.s(0)
temp.s(1)
qasm_str = temp.qasm() #returning a qasm string, THIS SIMPLE
qasm_str
qc_open1 = QuantumCircuit.from_qasm_str(qasm_str)
qc_open1 == qc_open
%qiskit_job_watcher
backend_sim = BasicAer.get_backend('qasm_simulator')
job = execute(qc_open1, backend_sim, shots = 1024)
job_monitor(job)
# or
job.status()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.