repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/yaelbh/qiskit-projectq-provider
|
yaelbh
|
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Exception for errors raised by ProjectQ simulators.
"""
from qiskit import QISKitError
class ProjectQSimulatorError(QISKitError):
"""Class for errors raised by the ProjectQ simulators."""
def __init__(self, *message):
"""Set the error message."""
super().__init__(*message)
self.message = ' '.join(message)
def __str__(self):
"""Return the message."""
return repr(self.message)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.quantumcircuitdata import CircuitInstruction
from qiskit.circuit import Measure
from qiskit.circuit.library import HGate, CXGate
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
instructions = [
CircuitInstruction(HGate(), [qr[0]], []),
CircuitInstruction(CXGate(), [qr[0], qr[1]], []),
CircuitInstruction(Measure(), [qr[0]], [cr[0]]),
CircuitInstruction(Measure(), [qr[1]], [cr[1]]),
]
circuit = QuantumCircuit.from_instructions(instructions)
circuit.draw("mpl")
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
B4 = QuantumCircuit(2)
B4.x(0)
B4.h(0)
B4.cx(0,1)
B4.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(B4,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(B4,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(B4,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from IPython.display import IFrame
IFrame(src="http://www.youtube.com/embed/yuDxHJOKsVA", width=1920/2, height=1080/2)
from qiskit import *
nqubits = 3
circuit = QuantumCircuit(nqubits, nqubits)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(1,2)
circuit.measure([0,1,2], [0,1,2])
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
sim_result = execute(circuit, backend=simulator, shots=1024).result()
from qiskit.visualization import plot_histogram
plot_histogram(sim_result.get_counts(circuit))
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
device = provider.get_backend('ibmqx2')
job = execute(circuit, backend=device, shots=1024)
#print(job.job_id())
from qiskit.tools.monitor import job_monitor
job_monitor(job)
device_result = job.result()
plot_histogram(device_result.get_counts(circuit))
from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter)
cal_circuits, state_labels = complete_meas_cal(qr=circuit.qregs[0],
circlabel='measurement_calibration')
cal_circuits[7].draw(output='mpl')
len(cal_circuits)
cal_job = execute(cal_circuits,
backend=device,
shots=8192,
optimization_level=0)
#print(cal_job.job_id())
job_monitor(cal_job)
cal_results = cal_job.result()
plot_histogram(cal_results.get_counts(cal_circuits[3]))
meas_fitter = CompleteMeasFitter(cal_results, state_labels)
meas_fitter.plot_calibration()
meas_filter = meas_fitter.filter
mitigated_result = meas_filter.apply(device_result)
device_counts = device_result.get_counts(circuit)
mitigated_counts = mitigated_result.get_counts(circuit)
plot_histogram([device_counts, mitigated_counts],
legend=['device, noisy', 'device, mitigated'])
circuit2 = QuantumCircuit(3,3)
circuit2.x(1)
circuit2.h(0)
circuit2.cx(0,1)
circuit2.cx(1,2)
circuit2.measure([0,1,2], [0,1,2])
circuit2.draw(output='mpl')
plot_histogram(
execute(circuit2, backend=simulator, shots=1024).result().get_counts(circuit2)
)
device_counts_2 = execute(circuit2, backend=device, shots=1024).result().get_counts(circuit2)
plot_histogram(device_counts_2)
mitigated_counts_2 = meas_filter.apply(device_counts_2)
plot_histogram([device_counts_2, mitigated_counts_2], legend=['device, noisy','device, mitigated'])
import qiskit
qiskit.__qiskit_version__
import qiskit.tools.jupyter
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module
# pylint: disable=attribute-defined-outside-init,unsubscriptable-object
from qiskit import converters
from qiskit import qasm
from .utils import random_circuit
class ConverterBenchmarks:
params = ([1, 2, 5, 8, 14, 20, 32, 53], [8, 128, 2048, 8192])
param_names = ["n_qubits", "depth"]
timeout = 600
def setup(self, n_qubits, depth):
seed = 42
# NOTE: Remove the benchmarks larger than 20x2048 and 14x8192, this is
# a tradeoff for speed of benchmarking, creating circuits this size
# takes more time than is worth it for benchmarks that take a couple
# seconds
if n_qubits >= 20:
if depth >= 2048:
raise NotImplementedError
elif n_qubits == 14:
if depth > 2048:
raise NotImplementedError
self.qc = random_circuit(n_qubits, depth, measure=True, conditional=True, seed=seed)
self.dag = converters.circuit_to_dag(self.qc)
self.qasm = qasm.Qasm(data=self.qc.qasm()).parse()
def time_circuit_to_dag(self, *_):
converters.circuit_to_dag(self.qc)
def time_circuit_to_instruction(self, *_):
converters.circuit_to_instruction(self.qc)
def time_dag_to_circuit(self, *_):
converters.dag_to_circuit(self.dag)
def time_ast_to_circuit(self, *_):
converters.ast_to_dag(self.qasm)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Fermionic state tests."""
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit_cold_atom.exceptions import QiskitColdAtomError
from qiskit_cold_atom.fermions.fermion_circuit_solver import FermionicState
class TestFermionState(QiskitTestCase):
"""Class to test the fermion state class."""
def test_initialize(self):
"""Test the initialization of fermionic states."""
state = FermionicState([0, 1, 1, 0])
self.assertEqual(state.sites, 4)
self.assertEqual(state.num_species, 1)
with self.assertRaises(QiskitColdAtomError):
FermionicState([0, 2])
with self.assertRaises(QiskitColdAtomError):
FermionicState([[0, 1], [1, 0, 1]])
state = FermionicState([[0, 1, 0], [1, 0, 1]])
self.assertEqual(state.occupations_flat, [0, 1, 0, 1, 0, 1])
self.assertEqual(state.num_species, 2)
def test_string(self):
"""Test the string representation."""
state = FermionicState([0, 1])
self.assertEqual(str(state), "|0, 1>")
state = FermionicState([[0, 1], [1, 0]])
self.assertEqual(str(state), "|0, 1>|1, 0>")
def test_occupations(self):
"""Test that to get the fermionic occupations."""
state = FermionicState([0, 1])
self.assertEqual(state.occupations, [[0, 1]])
def test_from_flat_list(self):
"""Test the creation of fermionic states from flat lists."""
state = FermionicState.from_total_occupations([0, 1, 1, 0], 2)
self.assertEqual(state.occupations, [[0, 1], [1, 0]])
with self.assertRaises(QiskitColdAtomError):
FermionicState.from_total_occupations([0, 1, 1, 0], 3)
state = FermionicState.from_total_occupations([0, 1, 1, 0], 1)
self.assertEqual(state.occupations, [[0, 1, 1, 0]])
def test_from_initial_state(self):
"""Test that we can load an initial state from a circuit."""
circ = QuantumCircuit(4)
circ.fload(0)
circ.fload(2)
state = FermionicState.initial_state(circ, 2)
self.assertEqual(state.occupations, [[1, 0], [1, 0]])
self.assertEqual(state.occupations_flat, [1, 0, 1, 0])
state = FermionicState.initial_state(circ, 1)
self.assertEqual(state.occupations, [[1, 0, 1, 0]])
self.assertEqual(state.occupations_flat, [1, 0, 1, 0])
|
https://github.com/vindem/quantumMD
|
vindem
|
from qiskit import QuantumCircuit,Aer, execute
from qiskit.visualization import plot_histogram
import numpy as np
import matplotlib.pyplot as plt
def check_computational_basis(basis):
n = int(np.log2(len(basis)))
qc = QuantumCircuit(n,n)
initial_state = np.array(basis) / np.linalg.norm(basis)
qc.initialize(initial_state, reversed(range(n))) # Input : LSB -> MSB
qc.measure(range(n), reversed(range(n))) # Readout: LSB -> MSB
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc,backend).result().get_counts().keys()
return counts
def gen_bases(n):
return np.eye(2**n)
bases = gen_bases(3)
for i in range(bases.shape[0]):
basis = bases[i].tolist()
print(f"basis: {basis} -> {check_computational_basis(basis)}")
def convert_zbasis_to_cbasis(zbasis):
"""
Converts a basis state in the Z basis to the computational basis
Example:
Input: [0,0] -> Output: [1,0,0,0]
Input: [0,1] -> Output: [0,1,0,0]
Input: [1,0] -> Output: [0,0,1,0]
Input: [1,1] -> Output: [0,0,0,1]
"""
n = 2**len(zbasis)
# z basis to binary number
bin_str = "".join([str(x) for x in zbasis])
num = int(bin_str,2)
# binary number to computational basis
cbasis = np.zeros(n)
cbasis[num] = 1
return cbasis
def cswap_test(x):
qc = QuantumCircuit(len(x)+1, 1)
input_state = convert_zbasis_to_cbasis(x)
qc.initialize(input_state, reversed(range(1,len(x)+1)))
qc.barrier()
qc.h(0)
qc.cswap(0,1,2)
qc.h(0)
qc.measure(0,0)
backend = Aer.get_backend('qasm_simulator')
return qc, execute(qc,backend).result().get_counts()
qc, counts = cswap_test([0,1])
qc.draw(output='mpl', style='iqx')
plot_histogram(counts)
states = [
[0,0],
[0,1],
[1,0],
[1,1]
]
fig, ax = plt.subplots(1,4, figsize=(16,4))
for i, state in enumerate(states):
_, counts = cswap_test(state)
plot_histogram(counts, ax=ax[i])
ax[i].set_title(f"Input: {state}")
plt.tight_layout()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/alpine-quantum-technologies/qiskit-aqt-provider-rc
|
alpine-quantum-technologies
|
# This code is part of Qiskit.
#
# (C) Copyright Alpine Quantum Technologies GmbH 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import math
from dataclasses import dataclass
from typing import Final, List, Optional, Tuple
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import Gate, Instruction
from qiskit.circuit.library import RGate, RXGate, RXXGate, RZGate
from qiskit.circuit.tools import pi_check
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler import Target
from qiskit.transpiler.basepasses import BasePass, TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import Decompose, Optimize1qGatesDecomposition
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.passmanager_config import PassManagerConfig
from qiskit.transpiler.preset_passmanagers import common
from qiskit.transpiler.preset_passmanagers.plugin import PassManagerStagePlugin
from qiskit_aqt_provider.utils import map_exceptions
class UnboundParametersTarget(Target):
"""Target that disables passes that require bound parameters."""
def bound_pass_manager(target: Target) -> PassManager:
"""Transpilation passes to apply on circuits after the parameters are bound.
This assumes that a preset pass manager was applied to the unbound circuits
(by setting the target to an instance of `UnboundParametersTarget`).
Args:
target: transpilation target.
"""
return PassManager(
[
# wrap the Rxx angles
WrapRxxAngles(),
# decompose the substituted Rxx gates
Decompose([f"{WrapRxxAngles.SUBSTITUTE_GATE_NAME}*"]),
# collapse the single qubit runs as ZXZ
Optimize1qGatesDecomposition(target=target),
# wrap the Rx angles, rewrite as R
RewriteRxAsR(),
]
)
def rewrite_rx_as_r(theta: float) -> Instruction:
"""Instruction equivalent to Rx(θ) as R(θ, φ) with θ ∈ [0, π] and φ ∈ [0, 2π]."""
theta = math.atan2(math.sin(theta), math.cos(theta))
phi = math.pi if theta < 0.0 else 0.0
return RGate(abs(theta), phi)
class RewriteRxAsR(TransformationPass):
"""Rewrite Rx(θ) as R(θ, φ) with θ ∈ [0, π] and φ ∈ [0, 2π]."""
@map_exceptions(TranspilerError)
def run(self, dag: DAGCircuit) -> DAGCircuit:
for node in dag.gate_nodes():
if node.name == "rx":
(theta,) = node.op.params
dag.substitute_node(node, rewrite_rx_as_r(float(theta)))
return dag
class AQTSchedulingPlugin(PassManagerStagePlugin):
def pass_manager(
self,
pass_manager_config: PassManagerConfig,
optimization_level: Optional[int] = None, # noqa: ARG002
) -> PassManager:
if isinstance(pass_manager_config.target, UnboundParametersTarget):
return PassManager([])
passes: List[BasePass] = [
# The Qiskit Target declares RX/RZ as basis gates.
# This allows decomposing any run of rotations into the ZXZ form, taking
# advantage of the free Z rotations.
# Since the API expects R/RZ as single-qubit operations,
# we rewrite all RX gates as R gates after optimizations have been performed.
RewriteRxAsR(),
]
return PassManager(passes)
@dataclass(frozen=True)
class CircuitInstruction:
"""Substitute for `qiskit.circuit.CircuitInstruction`.
Contrary to its Qiskit counterpart, this type allows
passing the qubits as integers.
"""
gate: Gate
qubits: Tuple[int, ...]
def _rxx_positive_angle(theta: float) -> List[CircuitInstruction]:
"""List of instructions equivalent to RXX(θ) with θ >= 0."""
rxx = CircuitInstruction(RXXGate(abs(theta)), qubits=(0, 1))
if theta >= 0:
return [rxx]
return [
CircuitInstruction(RZGate(math.pi), (0,)),
rxx,
CircuitInstruction(RZGate(math.pi), (0,)),
]
def _emit_rxx_instruction(theta: float, instructions: List[CircuitInstruction]) -> Instruction:
"""Collect the passed instructions into a single one labeled 'Rxx(θ)'."""
qc = QuantumCircuit(2, name=f"{WrapRxxAngles.SUBSTITUTE_GATE_NAME}({pi_check(theta)})")
for instruction in instructions:
qc.append(instruction.gate, instruction.qubits)
return qc.to_instruction()
def wrap_rxx_angle(theta: float) -> Instruction:
"""Instruction equivalent to RXX(θ) with θ ∈ [0, π/2]."""
# fast path if -π/2 <= θ <= π/2
if abs(theta) <= math.pi / 2:
operations = _rxx_positive_angle(theta)
return _emit_rxx_instruction(theta, operations)
# exploit 2-pi periodicity of Rxx
theta %= 2 * math.pi
if abs(theta) <= math.pi / 2:
operations = _rxx_positive_angle(theta)
elif abs(theta) <= 3 * math.pi / 2:
corrected_angle = theta - np.sign(theta) * math.pi
operations = [
CircuitInstruction(RXGate(math.pi), (0,)),
CircuitInstruction(RXGate(math.pi), (1,)),
]
operations.extend(_rxx_positive_angle(corrected_angle))
else:
corrected_angle = theta - np.sign(theta) * 2 * math.pi
operations = _rxx_positive_angle(corrected_angle)
return _emit_rxx_instruction(theta, operations)
class WrapRxxAngles(TransformationPass):
"""Wrap Rxx angles to [-π/2, π/2]."""
SUBSTITUTE_GATE_NAME: Final = "Rxx"
@map_exceptions(TranspilerError)
def run(self, dag: DAGCircuit) -> DAGCircuit:
for node in dag.gate_nodes():
if node.name == "rxx":
(theta,) = node.op.params
if 0 <= float(theta) <= math.pi / 2:
continue
rxx = wrap_rxx_angle(float(theta))
dag.substitute_node(node, rxx)
return dag
class AQTTranslationPlugin(PassManagerStagePlugin):
def pass_manager(
self,
pass_manager_config: PassManagerConfig,
optimization_level: Optional[int] = None, # noqa: ARG002
) -> PassManager:
translation_pm = common.generate_translation_passmanager(
target=pass_manager_config.target,
basis_gates=pass_manager_config.basis_gates,
approximation_degree=pass_manager_config.approximation_degree,
coupling_map=pass_manager_config.coupling_map,
backend_props=pass_manager_config.backend_properties,
unitary_synthesis_method=pass_manager_config.unitary_synthesis_method,
unitary_synthesis_plugin_config=pass_manager_config.unitary_synthesis_plugin_config,
hls_config=pass_manager_config.hls_config,
)
if isinstance(pass_manager_config.target, UnboundParametersTarget):
return translation_pm
passes: List[BasePass] = [WrapRxxAngles()]
return translation_pm + PassManager(passes)
|
https://github.com/werefin/BIP-Poznan-QRW-Search-Algorithm
|
werefin
|
!pip install qiskit && pip install pylatexenc && pip install qiskit-aer && pip install qiskit-ibmq-provider
# Useful imports
import numpy as np
import warnings
# Qiskit components
from qiskit import IBMQ
from qiskit import Aer, ClassicalRegister, QuantumRegister, QuantumCircuit, execute
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info import random_unitary
from qiskit.tools.monitor import backend_overview, backend_monitor
# Visualization
from qiskit.visualization import plot_histogram, plot_state_city
import matplotlib.pyplot as plt
import matplotlib.patches as patch
from matplotlib.path import Path
from matplotlib.animation import FuncAnimation
from IPython.display import Image
# Filter all warnings from now on
warnings.filterwarnings("ignore")
# Define the states
states = ['|00>', '|01>', '|11>', '|10>']
# Define the coordinates of the square's vertices
x = [0, 1, 1, 0, 0]
y = [0, 0, 1, 1, 0]
# Create a plot and set axis limits
plt.figure(figsize=(5, 5))
plt.plot(x, y, 'k-')
plt.scatter(x, y, c='black', s=100)
# Add text labels with variable offset
label_offset = 0.05
for i, state in enumerate(states):
if i in [0, 1]:
plt.text(x[i], y[i] - (1.8 * label_offset), state, fontsize=12, ha='center')
elif i in [2, 3]:
plt.text(x[i], y[i] + label_offset, state, fontsize=12, ha='center')
# Set axis limits and labels
plt.xlim(-0.25, 1.25)
plt.ylim(-0.25, 1.25)
# Add a title
plt.title('QRW - 2D hypercube')
# Show the plot
plt.grid(False)
plt.show()
# 1 flip of the Grover coin
q = QuantumRegister(6, name='q') # 6 quantum bits, 2 for the coin, 4 for the hypercube
q_circ = QuantumCircuit(q)
for i in range(1):
q_circ.h([4, 5])
q_circ.z([4, 5])
q_circ.cz(4, 5)
q_circ.h([4, 5])
q_circ.draw('mpl')
# 1 step in the process - a Grover coin toss and a shift operation
q = QuantumRegister(6, name='q') # same setup as before
q_circ = QuantumCircuit(q)
for i in range(1): # we are simulating one shift operation
q_circ.h([4, 5])
q_circ.z([4, 5])
q_circ.cz(4, 5)
q_circ.h([4, 5])
for i in range(0, 4): # here starts the shift operator, switching one of the four bits according to the rules mentioned above
q_circ.x(4)
if i % 2 == 0:
q_circ.x(5)
q_circ.ccx(4, 5, i)
q_circ.draw('mpl')
# In this algorithm we have a dimension of n for the state space, then we have log_2(n) states in the coin space --> define the dimensions of the quantum circuit
class QRW_Reg:
"""
QRW_Reg initializes a Quantum Random Walk registry --> it inputs the variable dim which is the number of qubits in the state space
dim: number of qubits
c: the number of coin qubits
"""
def __init__(self, dim):
c = (np.log2(dim))
if c.is_integer() != 1:
raise TypeError("The number of qubits n have to satisfy the condition that log_2(n) is an integer!")
self.c = int(c)
self.dim = dim
n = int(dim + c)
self.n = n
q_r = QuantumRegister(n, 'q')
cl_r = ClassicalRegister(n, "c")
self.qr = q_r
self.cl = cl_r
q_circuit = QuantumCircuit(self.qr, self.cl)
self.circuit = q_circuit
# Define the QRW search algorithm as a subclass of the QRW registry
class QRW_Search(QRW_Reg):
"""
QRW_Search is an implementation of the quantum random walk search algorithm
based on the paper by N. Shenvi et alter (see References paragraph for more details).
This class ineherits the QRW_Reg class
dim: number of qubits in the state space
state_search: the state that the algorithm searches for
"""
def __init__(self, dim, state_search):
QRW_Reg.__init__(self, dim)
self.circuit = QRW_Reg(dim).circuit
quantum_reg = QRW_Reg(dim).qr
classical_reg = QRW_Reg(dim).cl
self.search = state_search
circ = self.circuit
# Hadamards on all of the states
circ.h(quantum_reg[0:self.n])
# Operating U_prime pi/2 sqrt(2) times
times = np.ceil(0.5 * np.pi * np.sqrt(2**(self.dim)))
for i in range(int(times)):
circ.unitary(self.U_prime(), quantum_reg, label="U'")
# Measure the registry onto the classical bits
circ.measure(quantum_reg, classical_reg)
# Define all of the operators for the QRW search: S, C, U, U'
def S(self, display_matrix=False):
coin = self.c
num_dir = int(2**coin)
state = self.dim
S = np.zeros((2**(coin + state), 2**(coin + state)))
for i in range(num_dir):
for j in range(2**state):
# Perform the bit flip using a XOR
j_bin = int(j)
e_i = int(i + 1)
xor = j_bin ^ e_i
row = xor + (i * (2**state))
S[row][j + (i * (2**state))] = 1
if display_matrix:
print('Matrix for the shift operator:')
print(S)
return Operator(S)
def C(self, display_matrix=False):
# Definition of the C operator as an outer product in the coin space --> tensor product with the identity in state space
coin = self.c
num_dir = int(2**coin)
state = self.dim
num_state = int(2**state)
# Define the operator in just the coin space
s_c = np.zeros((2**(coin), 2**(coin)))
I_c = np.zeros((2**(coin), 2**(coin)))
for i in range(num_dir):
I_c[i][i] = 1
for j in range(num_dir):
s_c[i][j] = num_dir**(-1)
s_c = 2 * s_c
s_c = Operator(s_c)
I_c = Operator(I_c)
G = s_c - I_c
# Define the identity in the state space
I_s = np.zeros((2**(state), 2**(state)))
for i in range(num_state):
I_s[i][i] = 1
I = Operator(I_s)
C = G.tensor(I)
if display_matrix:
print('Matrix for the quantum coin operator:')
print(np.real(C.data))
return C
def U(self, display_matrix=False):
S_= self.S()
C_ = self.C()
U = C_.compose(S_)
if display_matrix:
print('Matrix for U:')
print(np.real(U.data))
return U
def U_prime(self, display_matrix=False):
# state_search is the state we are searching for --> focus on the second term
# Note: the state search must be in decimal!
if self.search >= 2**self.dim:
raise TypeError("search_state parameter is outside of state space values.")
elif self.search < 0:
raise TypeError("search_state parameter is outside of state space values.")
else:
# Focus on the second term of U_prime
coin = self.c
num_dir = int(2**coin)
state = self.dim
num_state = int(2**state)
search_array = np.zeros((num_state, num_state))
search_array[self.search][self.search] = 1
search = Operator(search_array)
s_c = np.zeros((2**(coin), 2**(coin)))
for i in range(num_dir):
for j in range(num_dir):
s_c[i][j] = num_dir**(-1)
coin_ = Operator(s_c)
search_op = coin_.tensor(search)
S_ = self.S()
second_term = search_op.compose(S_)
U_ = self.U()
U_prime = U_ - (2 * second_term)
if display_matrix:
print("Matrix for U':")
print(np.real(U_prime.data))
return U_prime
# Visualization
def draw_circuit(self):
return self.circuit.draw(output='mpl')
# Plots by actually measuring the circuit
def plot_states_hist(self):
backend = Aer.get_backend('qasm_simulator')
shots = 1024 # number of times circuit is run (for sampling)
results = execute(self.circuit, backend=backend, shots=shots).result()
counts = results.get_counts()
return plot_histogram(counts, figsize=(5, 5), sort='value_desc')
# Define the QRW algorithm as a subclass of the QRW registry
class QRW(QRW_Reg):
"""
The QRW class is an arbitrary implementation of a QRW
dim: number of qubits in the state space
c_label: string that determines what coin operator to use on the coin space
- hadamard = Hadamard operator --> tensor product with the identity
- random = random unitary operator
step: number of 'steps' the QRW completes which corresponds to the number of times the operator U is called
"""
def __init__(self, dim, c_label, step):
QRW_Reg.__init__(self, dim)
self.circuit = QRW_Reg(dim).circuit
quantum_reg = QRW_Reg(dim).qr
classical_reg = QRW_Reg(dim).cl
circ = self.circuit
# Hadamards on all of the states
circ.h(quantum_reg[0:self.n])
for i in range(int(step)):
circ.unitary(self.U(c_label), quantum_reg, label="step")
# Measure the registry onto the classical bits
circ.measure(quantum_reg, classical_reg)
# Defining all of the operators for the QRW search: S, C, U
def S(self):
coin = self.c
num_dir = int(2**coin)
state = self.dim
S = np.zeros((2**(coin + state), 2**(coin + state)))
for i in range(num_dir):
for j in range(2**state):
# Perform the bit flip using a XOR
j_bin = int(j)
e_i = int(i + 1)
xor = j_bin ^ e_i
row = xor + (i * (2**state))
S[row][j + (i * (2**state))] = 1
return Operator(S)
def C(self, c_label):
coin = self.c
state = self.dim
# Create the identity in the S space
I = np.zeros((2**state, 2**state))
for i in range(2**state):
I[i][i] = 1
I = Operator(I)
if c_label == "hadamard":
result= np.zeros((2**coin, 2**coin))
for i in range(2**coin):
for j in range(2**coin):
if i >= 2 and j >= 2:
result[i][j] = (-1) * (-1)**(i * j) * (2**((-1) * (0.5 * coin)))
else:
result[i][j] = (-1)**(i * j) * (2**((-1) * (0.5 * coin)))
res_op = (Operator(result))
C_final = res_op.tensor(I)
return C_final
elif c_label == "random":
dim = []
for i in range(coin):
dim.append(2)
res_op = random_unitary(tuple(dim))
C_final = res_op.tensor(I)
return C_final
else:
raise TypeError("Label string for C is not a valid input!")
def U(self, c_label):
S_= self.S()
C_ = self.C(c_label)
U = C_.compose(S_)
return U
# Visualization
def draw_circuit(self):
return self.circuit.draw()
# Plot by actually measuring the circuit
def plot_states_hist(self):
backend = Aer.get_backend('qasm_simulator')
print(backend)
shots = 1024 # number of times circuit is run (for sampling)
results = execute(self.circuit, backend=backend, shots=shots).result()
counts = results.get_counts()
return plot_histogram(counts, figsize=(5, 5), sort='value_desc')
# Control the circuit
def execute(self):
backend = Aer.get_backend('qasm_simulator')
results = execute(self.circuit, backend=backend, shots=1).result()
answer = results.get_counts()
# One execution means that there will be one state in the answer dictionary
state = list(answer.keys())
return state[0]
# Define the QRW search circuit
search_circuit = QRW_Search(2, 2)
search_circuit.draw_circuit()
search_circuit.plot_states_hist()
n_steps = 1
q = QuantumRegister(3, name='q') # 3 qubits register
c = ClassicalRegister(3, name='c') # 3 bits classical register
q_circ = QuantumCircuit(q, c) # quantum circuit
for i in range(n_steps):
q_circ.h(0)
q_circ.ccx(0, 2, 1)
q_circ.ccx(1, 2, 0)
q_circ.x(0)
q_circ.ccx(0, 1, 2)
q_circ.x(0)
q_circ.x(2)
q_circ.ccx(1, 2, 0)
q_circ.ccx(0, 2, 1)
q_circ.x(1)
q_circ.ccx(1, 2, 0)
q_circ.x(1)
q_circ.x(2)
q_circ.ccx(1, 2, 0)
q_circ.x(0)
q_circ.ccx(0, 1, 2)
q_circ.x(0)
q_circ.x(2)
q_circ.ccx(1, 2, 0)
q_circ.x(2)
q_circ.ccx(0, 2, 1)
q_circ.ccx(1, 2, 0)
q_circ.x(0)
q_circ.ccx(0, 1, 2)
q_circ.x(0)
q_circ.x(1)
q_circ.ccx(1, 2, 0)
q_circ.x(1)
q_circ.ccx(0, 2, 1)
q_circ.ccx(1, 2, 0)
q_circ.barrier()
q_circ.measure([q[0], q[1], q[2]], [c[0], c[1], c[2]])
q_circ.draw('mpl')
backend = Aer.get_backend('qasm_simulator')
shots = 1024 # number of times circuit is run (for sampling)
results = execute(q_circ, backend=backend, shots=shots).result()
counts = results.get_counts()
# Normalize counts to obtain probabilities
total_counts = sum(counts.values())
probabilities = {state: count / total_counts for state, count in counts.items()}
plot_histogram(probabilities, figsize=(5, 5), sort='value_desc')
n_steps = 4
q = QuantumRegister(3, name='q') # 3 qubits register
c = ClassicalRegister(3, name='c') # 3 bits classical register
q_circ = QuantumCircuit(q, c) # quantum circuit
for i in range(n_steps):
q_circ.h(q[0]) # coin
q_circ.ccx(q[0], q[1], q[2]) # Toffoli
q_circ.cx (q[0], q[1]) # CNOT
q_circ.x(q[0])
q_circ.x(q[1])
q_circ.ccx(q[0], q[1], q[2])
q_circ.x(q[1])
q_circ.cx(q[0], q[1])
q_circ.barrier()
q_circ.measure([q[0], q[1], q[2]], [c[0], c[1], c[2]])
q_circ.draw('mpl')
backend = Aer.get_backend('qasm_simulator')
shots = 1024 # number of times circuit is run (for sampling)
results = execute(q_circ, backend=backend, shots=shots).result()
counts = results.get_counts()
# Normalize counts to obtain probabilities
total_counts = sum(counts.values())
probabilities = {state: count / total_counts for state, count in counts.items()}
plot_histogram(probabilities, figsize=(5, 5), sort='value_desc')
# IBMQ.save_account needs to be run only once
IBMQ.save_account(API_KEY, overwrite=True)
# Load the saved IBMQ account
provider = IBMQ.load_account()
# Get a list of available backends
backend_overview()
# Get a specific backend device by its name
backend_device = provider.get_backend('ibm_brisbane')
print("Running on: "+str(backend_device))
# Monitor the status of the selected backend device
backend_monitor(backend_device)
shots = 1024 # number of times circuit is run (for sampling)
# Execute the quantum circuit on the selected backend
results_r = execute(q_circ, backend_device, shots=shots).result()
counts_r = results_r.get_counts()
# Normalize counts to obtain probabilities
total_counts = sum(counts_r.values())
probabilities_r = {state: count_r / total_counts for state, count_r in counts_r.items()}
plot_histogram([probabilities_r, probabilities], legend=['ibm_brisbane', 'qasm_simulator'], color=['#061727', '#82cfff'], sort='value_desc')
# Animate the 2D 'mapping' for the QRW it inherits the QRW class
class QRW_Automata(QRW):
"""
QRW_Automata is a class that inherits the QRW class --> it animates multiple executions of the QRW algorithm into a cellular automata board
Note: this algorithm has only been defined for the cases of 2 and 4 state qubits!
dim: number of qubits in the state space
c_label: string that determines what coin operator to use on the coin space
- hadamard = Hadamard operator --> tensor product with the identity
- random = random unitary operator
steps: number of 'steps' the QRW completes which corresponds to the number of times the operator U is called
iters: number of times the circuit is executed (also determines the number of frames in the animation)
"""
def __init__(self, dim, c_label, steps, iters):
QRW.__init__(self, dim, c_label, steps)
self.n = QRW(dim, c_label, steps).n
self.c = QRW(dim, c_label, steps).c
self.circ = QRW(dim, c_label, steps).circuit
state = []
for i in range(iters):
state.append(QRW(dim, c_label, steps).execute())
self.state = state
print("State:")
print(state)
c_state = []
s_state = []
for i in state:
c_state.append(i[0:self.c])
s_state.append(i[self.c:])
self.c_state = c_state
self.s_state = s_state
if (dim/2).is_integer() != True:
raise ValueError("The half of the number of qubits in the state space has to be an integer!")
# Divide up the board according to number of bits
# n: number of rows and columns --> we are going to implement only the case for n=4!
if int(self.dim) != 4 and int(self.dim) != 2:
raise ValueError("Grid is implemented only for the cases where n=2 and n=4 in the state space!")
figure, axes = plt.subplots(nrows=2, ncols=1)
axes[0].set_facecolor((0, 0, 0))
axes[0].get_xaxis().set_ticks([])
axes[0].get_yaxis().set_ticks([])
axes[1].get_xaxis().set_ticks([])
axes[1].get_yaxis().set_ticks([])
self.fig = figure
self.ax = axes
self.circuit.draw('mpl', scale=0.9, ax=axes[1])
n_v = (2 * self.dim)
if self.c % 2 != 0:
n_h = self.dim
else:
n_h = n_v
v_lines = np.arange(0, 1, 1/n_v)
h_lines = np.arange(0, 1, 1/n_h)
# Draw the frames for the board
for i in v_lines:
axes[0].axvline(x=i, ymin=0, ymax=1, color='r')
for i in h_lines:
axes[0].axhline(y=i, xmin=0, xmax=1, color='r')
anim = FuncAnimation(self.fig, self.animate, frames=int(len(state)), interval=1300)
anim.save("QRW_{n}qubits_{op}_{st}steps.gif".format(n=self.dim, op=c_label, st=steps),)
def animate(self, i):
# Plot the state space
if self.dim == 2:
c_ = self.c_state[i]
s_ = self.s_state[i]
n_v = (2 * self.dim)
n_h = self.dim
verts = [
(0. + int(s_[-1]) * (1/n_v) + 0.5 * int(c_), 1. - int(s_[0]) * (1/n_h) - (1/n_h)), # left, bottom
(0. + int(s_[-1]) * (1/n_v)+ 0.5 * int(c_), 1. - int(s_[0]) * (1/n_h)), # left, top
((1/n_v) + int(s_[-1]) * (1/n_v) + 0.5 * int(c_), 1. - int(s_[0]) * (1/n_h)), # right, top
((1/n_v) + int(s_[-1]) * (1/n_v) + 0.5 * int(c_), 1. - int(s_[0]) * (1/n_h) - (1/n_h)), # right, bottom
(0. + int(s_[-1]) * (1/n_v) + 0.5 * int(c_), 1. - int(s_[0]) * (1/n_h) - (1/n_h)), # ignored
]
codes = [
Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.CLOSEPOLY,
]
path = Path(verts, codes)
cell = patch.PathPatch(path, facecolor='w')
self.ax[0].set_xlabel("Measured state: {state_}".format(state_=self.state[i]))
self.ax[0].add_patch(cell)
return patch
elif self.dim == 4:
c_ = self.c_state[i]
s_ = self.s_state[i]
n_v = (2 * self.dim)
n_h = (2 * self.dim)
verts = [
(0. + int(s_[-1]) * (1/n_v) + int(s_[-2]) * (2/n_v) + 0.5 * int(c_[1]), 1. - int(s_[0])* 2 *(1/n_h) - int(s_[1]) * (1/n_h) - (1/n_h) - 0.5 * int(c_[0])), # left, bottom
(0. + int(s_[-1]) * (1/n_v) + int(s_[-2]) * (2/n_v) + 0.5 * int(c_[1]), 1. - int(s_[0])* 2 *(1/n_h) - int(s_[1]) * (1/n_h) - 0.5 * int(c_[0])), # left, top
((1/n_v) + int(s_[-1]) * (1/n_v) + int(s_[-2]) * (2/n_v) + 0.5 * int(c_[1]), 1. - int(s_[0])* 2 *(1/n_h) - int(s_[1]) * (1/n_h) - 0.5 * int(c_[0])), # right, top
((1/n_v) + int(s_[-1]) * (1/n_v) + int(s_[-2]) * (2/n_v) + 0.5 * int(c_[1]), 1. - int(s_[0])* 2 *(1/n_h) - int(s_[1]) * (1/n_h) - (1/n_h) - 0.5 * int(c_[0])), # right, bottom
(0. + int(s_[-1]) * (1/n_v) + int(s_[-2]) * (2/n_v) + 0.5 * int(c_[1]), 1. - int(s_[0])* 2 *(1/n_h) - int(s_[1]) * (1/n_h) - (1/n_h) - 0.5 * int(c_[0])), # ignored
]
codes = [
Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.CLOSEPOLY,
]
path = Path(verts, codes)
cell = patch.PathPatch(path, facecolor='w')
self.ax[0].set_xlabel("Measured state: {state_}".format(state_=self.state[i]))
self.ax[0].add_patch(cell)
return patch
QRW_Automata(4, "hadamard", 4, 16)
QRW_Automata(4, "random", 4, 16)
display(Image(data=open('/content/QRW_4qubits_hadamard_4steps.gif','rb').read(), format='gif'))
display(Image(data=open('/content/QRW_4qubits_random_4steps.gif','rb').read(), format='gif'))
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
"""Test the CNS transformation on a circuit DAG."""
# from qiskit import QuantumCircuit
# from qiskit.converters import circuit_to_dag, dag_to_circuit
# from qiskit.quantum_info import Operator
# from mirror_gates.cns_transform import cns_transform
# def generate_circuit():
# """Generate a circuit to test the CNS transformation."""
# qc = QuantumCircuit(3)
# qc.t(2)
# qc.iswap(0, 2)
# qc.s(0)
# qc.h(1)
# qc.swap(0, 1)
# qc.h(1)
# qc.cx(1, 2)
# qc.t(1)
# qc.rzz(0.5, 2, 0)
# qc.cx(0, 2)
# qc.h(1)
# qc.h(2)
# return qc
# def test_single_nodecns_transform():
# """Test the CNS transformation on a single node."""
# # Generate the original circuit and calculate its operator
# qc_original = generate_circuit()
# dag_original = circuit_to_dag(qc_original)
# op_original = Operator(qc_original)
# # Identify the node to be transformed
# node_to_transform = dag_original.two_qubit_ops()[0]
# # Apply the CNS transformation
# dag_transformed = cns_transform(
# dag_original, node_to_transform, preserve_layout=True
# )
# qc_transformed = dag_to_circuit(dag_transformed)
# # Test equivalence of original and transformed circuits
# assert op_original.equiv(Operator(qc_transformed))
# def test_multiple_nodescns_transform():
# """Test the CNS transformation on multiple nodes."""
# # Generate the original circuit and calculate its operator
# qc_original = generate_circuit()
# dag_original = circuit_to_dag(qc_original)
# op_original = Operator(qc_original)
# # Identify the nodes to be transformed
# # should test the function works if passed neither a CX nor an iSWAP
# nodes_to_transform = dag_original.op_nodes()
# # Apply the CNS transformation
# dag_transformed = cns_transform(
# dag_original, *nodes_to_transform, preserve_layout=True
# )
# qc_transformed = dag_to_circuit(dag_transformed)
# # Test equivalence of original and transformed circuits
# assert op_original.equiv(Operator(qc_transformed))
# if __name__ == "__main__":
# test_single_nodecns_transform()
# test_multiple_nodescns_transform()
|
https://github.com/mistryiam/IBM-Qiskit-Machine-Learning
|
mistryiam
|
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear')
ansatz.draw('mpl', style='iqx')
from qiskit.opflow import Z, I
hamiltonian = Z ^ Z
from qiskit.opflow import StateFn
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
import numpy as np
point = np.random.random(ansatz.num_parameters)
index = 2
from qiskit import Aer
from qiskit.utils import QuantumInstance
backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718)
from qiskit.circuit import QuantumCircuit
from qiskit.opflow import Z, X
H = X ^ X
U = QuantumCircuit(2)
U.h(0)
U.cx(0, 1)
# YOUR CODE HERE
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
matmult_result =expectation.eval()
from qc_grader import grade_lab4_ex1
# Note that the grading function is expecting a complex number
grade_lab4_ex1(matmult_result)
from qiskit.opflow import CircuitSampler, PauliExpectation
sampler = CircuitSampler(q_instance)
# YOUR CODE HERE
sampler = CircuitSampler(q_instance) # q_instance is the QuantumInstance from the beginning of the notebook
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
in_pauli_basis = PauliExpectation().convert(expectation)
shots_result = sampler.convert(in_pauli_basis).eval()
from qc_grader import grade_lab4_ex2
# Note that the grading function is expecting a complex number
grade_lab4_ex2(shots_result)
from qiskit.opflow import PauliExpectation, CircuitSampler
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
in_pauli_basis = PauliExpectation().convert(expectation)
sampler = CircuitSampler(q_instance)
def evaluate_expectation(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(in_pauli_basis, params=value_dict).eval()
return np.real(result)
eps = 0.2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps)
print(finite_difference)
from qiskit.opflow import Gradient
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('fin_diff', analytic=False, epsilon=eps)
grad = shifter.convert(expectation, params=ansatz.parameters[index])
print(grad)
value_dict = dict(zip(ansatz.parameters, point))
sampler.convert(grad, value_dict).eval().real
eps = np.pi / 2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2
print(finite_difference)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient() # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('lin_comb') # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
# initial_point = np.random.random(ansatz.num_parameters)
initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341])
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
gradient = Gradient().convert(expectation)
gradient_in_pauli_basis = PauliExpectation().convert(gradient)
sampler = CircuitSampler(q_instance)
def evaluate_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here!
return np.real(result)
# Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import GradientDescent
from qc_grader.gradient_descent import GradientDescent
gd_loss = []
def gd_callback(nfevs, x, fx, stepsize):
gd_loss.append(fx)
gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback)
x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters
evaluate_expectation, # function to minimize
gradient_function=evaluate_gradient, # function to evaluate the gradient
initial_point=initial_point) # initial point
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size'] = 14
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, label='vanilla gradient descent')
plt.axhline(-1, ls='--', c='tab:red', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend();
from qiskit.opflow import NaturalGradient
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
natural_gradient = NaturalGradient(regularization='ridge').convert(expectation)
natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient)
sampler = CircuitSampler(q_instance, caching="all")
def evaluate_natural_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(natural_gradient, params=value_dict).eval()
return np.real(result)
print('Vanilla gradient:', evaluate_gradient(initial_point))
print('Natural gradient:', evaluate_natural_gradient(initial_point))
qng_loss = []
def qng_callback(nfevs, x, fx, stepsize):
qng_loss.append(fx)
qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback)
x_opt, fx_opt, nfevs = qng.optimize(initial_point.size,
evaluate_expectation,
gradient_function=evaluate_natural_gradient,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
from qc_grader.spsa import SPSA
spsa_loss = []
def spsa_callback(nfev, x, fx, stepsize, accepted):
spsa_loss.append(fx)
spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback)
x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
# Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import QNSPSA
from qc_grader.qnspsa import QNSPSA
qnspsa_loss = []
def qnspsa_callback(nfev, x, fx, stepsize, accepted):
qnspsa_loss.append(fx)
fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation())
qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback)
x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
autospsa_loss = []
def autospsa_callback(nfev, x, fx, stepsize, accepted):
autospsa_loss.append(fx)
autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback)
x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X)
from qc_grader import grade_lab4_ex3
# Note that the grading function is expecting a Hamiltonian
grade_lab4_ex3(H_tfi)
from qiskit.circuit.library import EfficientSU2
efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2)
tfi_sampler = CircuitSampler(q_instance)
def evaluate_tfi(parameters):
exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2))
value_dict = dict(zip(efficient_su2.parameters, parameters))
result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval()
return np.real(result)
# target energy
tfi_target = -3.4939592074349326
# initial point for reproducibility
tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282,
0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126,
0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325,
0.48311132, 0.43623886, 0.6371297 ])
tfi_result = SPSA(maxiter=300, learning_rate=None, perturbation=None)
tfi_result = tfi_result.optimize(tfi_init.size, evaluate_tfi, initial_point=tfi_init)
tfi_minimum = tfi_result[1]
print("Error:", np.abs(tfi_result[1] - tfi_target))
from qc_grader import grade_lab4_ex4
# Note that the grading function is expecting a floating point number
grade_lab4_ex4(tfi_minimum)
from qiskit_machine_learning.datasets import ad_hoc_data
training_features, training_labels, test_features, test_labels = ad_hoc_data(
training_size=20, test_size=10, n=2, one_hot=False, gap=0.5
)
# the training labels are in {0, 1} but we'll use {-1, 1} as class labels!
training_labels = 2 * training_labels - 1
test_labels = 2 * test_labels - 1
def plot_sampled_data():
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label in zip(test_features, test_labels):
marker = 's'
plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k')
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_sampled_data()
from qiskit.circuit.library import ZZFeatureMap
dim = 2
feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple!
feature_map.draw('mpl', style='iqx')
ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here!
ansatz.draw('mpl', style='iqx')
circuit = feature_map.compose(ansatz)
circuit.draw('mpl', style='iqx')
hamiltonian = Z ^ Z # global Z operators
gd_qnn_loss = []
def gd_qnn_callback(*args):
gd_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback)
from qiskit_machine_learning.neural_networks import OpflowQNN
qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
exp_val=PauliExpectation(),
gradient=Gradient(), # <-- Parameter-Shift gradients
quantum_instance=q_instance)
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
#initial_point = np.array([0.2, 0.1, 0.3, 0.4])
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)
classifier.fit(training_features, training_labels);
predicted = classifier.predict(test_features)
def plot_predicted():
from matplotlib.lines import Line2D
plt.figure(figsize=(12, 6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label, pred in zip(test_features, test_labels, predicted):
marker = 's'
color = 'tab:green' if pred == -1 else 'tab:blue'
if label != pred: # mark wrongly classified
plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5,
facecolor='none', edgecolor='tab:red')
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10),
Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10),
Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_predicted()
qng_qnn_loss = []
def qng_qnn_callback(*args):
qng_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients!
quantum_instance=q_instance)
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point)
classifier.fit(training_features, training_labels);
def plot_losses():
plt.figure(figsize=(12, 6))
plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients')
plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients')
plt.xlabel('iterations')
plt.ylabel('loss')
plt.legend(loc='best')
plot_losses()
from qiskit.opflow import I
def sample_gradients(num_qubits, reps, local=False):
"""Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions.
We sample 100 times for random parameters and compute the gradient of the first RY rotation gate.
"""
index = num_qubits - 1
# you can also exchange this for a local operator and observe the same!
if local:
operator = Z ^ Z ^ (I ^ (num_qubits - 2))
else:
operator = Z ^ num_qubits
# real amplitudes ansatz
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
# construct Gradient we want to evaluate for different values
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = Gradient().convert(expectation, params=ansatz.parameters[index])
# evaluate for 100 different, random parameter values
num_points = 100
grads = []
for _ in range(num_points):
# points are uniformly chosen from [0, pi]
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
from qiskit.opflow import NaturalGradient
def sample_natural_gradients(num_qubits, reps):
index = num_qubits - 1
operator = Z ^ num_qubits
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``.
# Hint: Check the ``sample_gradients`` function, this one is almost the same.
grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index])
num_points = 100
grads = []
for _ in range(num_points):
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients')
plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = 6
operator = Z ^ Z ^ (I ^ (num_qubits - 4))
def minimize(circuit, optimizer):
initial_point = np.random.random(circuit.num_parameters)
exp = StateFn(operator, is_measurement=True) @ StateFn(circuit)
grad = Gradient().convert(exp)
# pauli basis
exp = PauliExpectation().convert(exp)
grad = PauliExpectation().convert(grad)
sampler = CircuitSampler(q_instance, caching="all")
def loss(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(exp, values_dict).eval())
def gradient(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(grad, values_dict).eval())
return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point)
circuit = RealAmplitudes(4, reps=1, entanglement='linear')
circuit.draw('mpl', style='iqx')
circuit.reps = 5
circuit.draw('mpl', style='iqx')
def layerwise_training(ansatz, max_num_layers, optimizer):
optimal_parameters = []
fopt = None
for reps in range(1, max_num_layers):
ansatz.reps = reps
# bind already optimized parameters
values_dict = dict(zip(ansatz.parameters, optimal_parameters))
partially_bound = ansatz.bind_parameters(values_dict)
xopt, fopt, _ = minimize(partially_bound, optimizer)
print('Circuit depth:', ansatz.depth(), 'best value:', fopt)
optimal_parameters += list(xopt)
return fopt, optimal_parameters
ansatz = RealAmplitudes(4, entanglement='linear')
optimizer = GradientDescent(maxiter=50)
np.random.seed(12)
fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
The HHL algorithm.
"""
import logging
import numpy as np
from copy import deepcopy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.aqua.algorithms import QuantumAlgorithm
from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class
from qiskit.ignis.verification.tomography import state_tomography_circuits, \
StateTomographyFitter
from qiskit.converters import circuit_to_dag
logger = logging.getLogger(__name__)
class HHL(QuantumAlgorithm):
"""The HHL algorithm.
The quantum circuit for this algorithm is returned by `generate_circuit`.
Running the algorithm will execute the circuit and return the result
vector, measured (real hardware backend) or derived (qasm_simulator) via
state tomography or calculated from the statevector (statevector_simulator).
"""
CONFIGURATION = {
'name': 'HHL',
'description': 'The HHL Algorithm for Solving Linear Systems of '
'equations',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'hhl_schema',
'type': 'object',
'properties': {
'truncate_powerdim': {
'type': 'boolean',
'default': False
},
'truncate_hermitian': {
'type': 'boolean',
'default': False
},
'orig_size': {
'type': ['integer', 'null'],
'default': None
}
},
'additionalProperties': False
},
'problems': ['linear_system'],
'depends': [
{'pluggable_type': 'initial_state',
'default': {
'name': 'CUSTOM',
}
},
{'pluggable_type': 'eigs',
'default': {
'name': 'EigsQPE',
'num_ancillae': 6,
'num_time_slices': 50,
'expansion_mode': 'suzuki',
'expansion_order': 2
}
},
{'pluggable_type': 'reciprocal',
'default': {
'name': 'Lookup'
}
}
],
}
def __init__(
self,
matrix=None,
vector=None,
truncate_powerdim=False,
truncate_hermitian=False,
eigs=None,
init_state=None,
reciprocal=None,
num_q=0,
num_a=0,
orig_size=None
):
"""
Constructor.
Args:
matrix (np.array): the input matrix of linear system of equations
vector (np.array): the input vector of linear system of equations
truncate_powerdim (bool): flag indicating expansion to 2**n matrix to be truncated
truncate_hermitian (bool): flag indicating expansion to hermitian matrix to be truncated
eigs (Eigenvalues): the eigenvalue estimation instance
init_state (InitialState): the initial quantum state preparation
reciprocal (Reciprocal): the eigenvalue reciprocal and controlled rotation instance
num_q (int): number of qubits required for the matrix Operator instance
num_a (int): number of ancillary qubits for Eigenvalues instance
orig_size (int): The original dimension of the problem (if truncate_powerdim)
"""
super().__init__()
super().validate(locals())
if matrix.shape[0] != matrix.shape[1]:
raise ValueError("Input matrix must be square!")
if matrix.shape[0] != len(vector):
raise ValueError("Input vector dimension does not match input "
"matrix dimension!")
if not np.allclose(matrix, matrix.conj().T):
raise ValueError("Input matrix must be hermitian!")
if np.log2(matrix.shape[0]) % 1 != 0:
raise ValueError("Input matrix dimension must be 2**n!")
if truncate_powerdim and orig_size is None:
raise ValueError("Truncation to {} dimensions is not "
"possible!".format(self._original_dimension))
self._matrix = matrix
self._vector = vector
self._truncate_powerdim = truncate_powerdim
self._truncate_hermitian = truncate_hermitian
self._eigs = eigs
self._init_state = init_state
self._reciprocal = reciprocal
self._num_q = num_q
self._num_a = num_a
self._circuit = None
self._io_register = None
self._eigenvalue_register = None
self._ancilla_register = None
self._success_bit = None
self._original_dimension = orig_size
self._ret = {}
@classmethod
def init_params(cls, params, algo_input):
"""Initialize via parameters dictionary and algorithm input instance
Args:
params: parameters dictionary
algo_input: LinearSystemInput instance
"""
if algo_input is None:
raise AquaError("LinearSystemInput instance is required.")
matrix = algo_input.matrix
vector = algo_input.vector
if not isinstance(matrix, np.ndarray):
matrix = np.asarray(matrix)
if not isinstance(vector, np.ndarray):
vector = np.asarray(vector)
if matrix.shape[0] != matrix.shape[1]:
raise ValueError("Input matrix must be square!")
if matrix.shape[0] != len(vector):
raise ValueError("Input vector dimension does not match input "
"matrix dimension!")
hhl_params = params.get(Pluggable.SECTION_KEY_ALGORITHM)
truncate_powerdim = hhl_params.get('truncate_powerdim')
truncate_hermitian = hhl_params.get('truncate_hermitian')
orig_size = hhl_params.get('orig_size')
if orig_size is None:
orig_size = len(vector)
is_powerdim = np.log2(matrix.shape[0]) % 1 == 0
if not is_powerdim:
logger.warning("Input matrix does not have dimension 2**n. It "
"will be expanded automatically.")
matrix, vector = cls.expand_to_powerdim(matrix, vector)
truncate_powerdim = True
is_hermitian = np.allclose(matrix, matrix.conj().T)
if not is_hermitian:
logger.warning("Input matrix is not hermitian. It will be "
"expanded to a hermitian matrix automatically.")
matrix, vector = cls.expand_to_hermitian(matrix, vector)
truncate_hermitian = True
# Initialize eigenvalue finding module
eigs_params = params.get(Pluggable.SECTION_KEY_EIGS)
eigs = get_pluggable_class(PluggableType.EIGENVALUES,
eigs_params['name']).init_params(params, matrix)
num_q, num_a = eigs.get_register_sizes()
# Initialize initial state module
tmpvec = vector
init_state_params = params.get(Pluggable.SECTION_KEY_INITIAL_STATE)
init_state_params["num_qubits"] = num_q
init_state_params["state_vector"] = tmpvec
init_state = get_pluggable_class(PluggableType.INITIAL_STATE,
init_state_params['name']).init_params(params)
# Initialize reciprocal rotation module
reciprocal_params = params.get(Pluggable.SECTION_KEY_RECIPROCAL)
reciprocal_params["negative_evals"] = eigs._negative_evals
reciprocal_params["evo_time"] = eigs._evo_time
reci = get_pluggable_class(PluggableType.RECIPROCAL,
reciprocal_params['name']).init_params(params)
return cls(matrix, vector, truncate_powerdim, truncate_hermitian, eigs,
init_state, reci, num_q, num_a, orig_size)
def construct_circuit(self, measurement=False):
"""Construct the HHL circuit.
Args:
measurement (bool): indicate whether measurement on ancillary qubit
should be performed
Returns:
the QuantumCircuit object for the constructed circuit
"""
q = QuantumRegister(self._num_q, name="io")
qc = QuantumCircuit(q)
# InitialState
qc += self._init_state.construct_circuit("circuit", q)
# EigenvalueEstimation (QPE)
qc += self._eigs.construct_circuit("circuit", q)
a = self._eigs._output_register
# Reciprocal calculation with rotation
qc += self._reciprocal.construct_circuit("circuit", a)
s = self._reciprocal._anc
# Inverse EigenvalueEstimation
qc += self._eigs.construct_inverse("circuit", self._eigs._circuit)
# Measurement of the ancilla qubit
if measurement:
c = ClassicalRegister(1)
qc.add_register(c)
qc.measure(s, c)
self._success_bit = c
self._io_register = q
self._eigenvalue_register = a
self._ancilla_register = s
self._circuit = qc
return qc
@staticmethod
def expand_to_powerdim(matrix, vector):
""" Expand a matrix to the next-larger 2**n dimensional matrix with
ones on the diagonal and zeros on the off-diagonal and expand the
vector with zeros accordingly.
Args:
matrix (np.array): the input matrix
vector (np.array): the input vector
Returns:
matrix (np.array): the expanded matrix
vector (np.array): the expanded vector
"""
mat_dim = matrix.shape[0]
next_higher = int(np.ceil(np.log2(mat_dim)))
new_matrix = np.identity(2 ** next_higher)
new_matrix = np.array(new_matrix, dtype=complex)
new_matrix[:mat_dim, :mat_dim] = matrix[:, :]
matrix = new_matrix
new_vector = np.zeros((1, 2 ** next_higher))
new_vector[0, :vector.shape[0]] = vector
vector = new_vector.reshape(np.shape(new_vector)[1])
return matrix, vector
@staticmethod
def expand_to_hermitian(matrix, vector):
""" Expand a non-hermitian matrix A to a hermitian matrix by
[[0, A.H], [A, 0]] and expand vector b to [b.conj, b].
Args:
matrix (np.array): the input matrix
vector (np.array): the input vector
Returns:
matrix (np.array): the expanded matrix
vector (np.array): the expanded vector
"""
#
half_dim = matrix.shape[0]
full_dim = 2 * half_dim
new_matrix = np.zeros([full_dim, full_dim])
new_matrix = np.array(new_matrix, dtype=complex)
new_matrix[0:half_dim, half_dim:full_dim] = matrix[:, :]
new_matrix[half_dim:full_dim, 0:half_dim] = matrix.conj().T[:, :]
matrix = new_matrix
new_vector = np.zeros((1, full_dim))
new_vector = np.array(new_vector, dtype=complex)
new_vector[0, :vector.shape[0]] = vector.conj()
new_vector[0, vector.shape[0]:] = vector
vector = new_vector.reshape(np.shape(new_vector)[1])
return matrix, vector
def _resize_vector(self, vec):
if self._truncate_hermitian:
half_dim = int(vec.shape[0] / 2)
vec = vec[:half_dim]
if self._truncate_powerdim:
vec = vec[:self._original_dimension]
return vec
def _resize_matrix(self, matrix):
if self._truncate_hermitian:
full_dim = matrix.shape[0]
half_dim = int(full_dim / 2)
new_matrix = np.ndarray(shape=(half_dim, half_dim), dtype=complex)
new_matrix[:, :] = matrix[0:half_dim, half_dim:full_dim]
matrix = new_matrix
if self._truncate_powerdim:
new_matrix = np.ndarray(shape=(self._original_dimension, self._original_dimension), dtype=complex)
new_matrix[:, :] = matrix[:self._original_dimension, :self._original_dimension]
matrix = new_matrix
return matrix
def _statevector_simulation(self):
"""The statevector simulation.
The HHL result gets extracted from the statevector. Only for
statevector simulator available.
"""
res = self._quantum_instance.execute(self._circuit)
sv = np.asarray(res.get_statevector(self._circuit))
# Extract solution vector from statevector
vec = self._reciprocal.sv_to_resvec(sv, self._num_q)
# remove added dimensions
self._ret['probability_result'] = np.real(self._resize_vector(vec).dot(self._resize_vector(vec).conj()))
vec = vec/np.linalg.norm(vec)
self._hhl_results(vec)
def _state_tomography(self):
"""The state tomography.
The HHL result gets extracted via state tomography. Available for
qasm simulator and real hardware backends.
"""
# Preparing the state tomography circuits
tomo_circuits = state_tomography_circuits(self._circuit,
self._io_register)
tomo_circuits_noanc = deepcopy(tomo_circuits)
ca = ClassicalRegister(1)
for circ in tomo_circuits:
circ.add_register(ca)
circ.measure(self._reciprocal._anc, ca[0])
# Extracting the probability of successful run
results = self._quantum_instance.execute(tomo_circuits)
probs = []
for circ in tomo_circuits:
counts = results.get_counts(circ)
s, f = 0, 0
for k, v in counts.items():
if k[0] == "1":
s += v
else:
f += v
probs.append(s/(f+s))
probs = self._resize_vector(probs)
self._ret["probability_result"] = np.real(probs)
# Filtering the tomo data for valid results with ancillary measured
# to 1, i.e. c1==1
results_noanc = self._tomo_postselect(results)
tomo_data = StateTomographyFitter(results_noanc, tomo_circuits_noanc)
rho_fit = tomo_data.fit()
vec = np.diag(rho_fit) / np.sqrt(sum(np.diag(rho_fit) ** 2))
self._hhl_results(vec)
def _tomo_postselect(self, results):
new_results = deepcopy(results)
for resultidx, _ in enumerate(results.results):
old_counts = results.get_counts(resultidx)
new_counts = {}
# change the size of the classical register
new_results.results[resultidx].header.creg_sizes = [
new_results.results[resultidx].header.creg_sizes[0]]
new_results.results[resultidx].header.clbit_labels = \
new_results.results[resultidx].header.clbit_labels[0:-1]
new_results.results[resultidx].header.memory_slots = \
new_results.results[resultidx].header.memory_slots - 1
for reg_key in old_counts:
reg_bits = reg_key.split(' ')
if reg_bits[0] == '1':
new_counts[reg_bits[1]] = old_counts[reg_key]
new_results.results[resultidx].data.counts = \
new_results.results[resultidx]. \
data.counts.from_dict(new_counts)
return new_results
def _hhl_results(self, vec):
res_vec = self._resize_vector(vec)
in_vec = self._resize_vector(self._vector)
matrix = self._resize_matrix(self._matrix)
self._ret["output"] = res_vec
# Rescaling the output vector to the real solution vector
tmp_vec = matrix.dot(res_vec)
f1 = np.linalg.norm(in_vec)/np.linalg.norm(tmp_vec)
f2 = sum(np.angle(in_vec*tmp_vec.conj()-1+1))/(np.log2(matrix.shape[0])) # "-1+1" to fix angle error for -0.-0.j
self._ret["solution"] = f1*res_vec*np.exp(-1j*f2)
def _run(self):
if self._quantum_instance.is_statevector:
self.construct_circuit(measurement=False)
self._statevector_simulation()
else:
self.construct_circuit(measurement=False)
self._state_tomography()
# Adding a bit of general result information
self._ret["matrix"] = self._resize_matrix(self._matrix)
self._ret["vector"] = self._resize_vector(self._vector)
self._ret["circuit_info"] = circuit_to_dag(self._circuit).properties()
return self._ret
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
import binascii
from math import sqrt
from qiskit import execute, QuantumCircuit, transpile, assemble
from qiskit.quantum_info import Statevector
from qiskit.extensions import Initialize
from crypto.rsa_substitute.sender import Sender
from crypto.rsa_substitute.receiver import Receiver
RSA_SUBSTITUTE_SIMULATOR = 'RSA SUBSTITUTE SIMULATOR'
## An implementation of the RSA substitute protocol
## @see https://journals.aijr.org/index.php/ajgr/article/view/699/168
class RsaSubstituteAlgorithm:
## Run the implementation of RSA substitute protocol
def run(self, measure_zero_prob, n_shots, backend, verbose):
bob = Receiver('Bob', 6, 5)
alice = Sender('Alice', 4, bob.p)
message = self.generate_message(measure_zero_prob)
alice_encoded_message = alice.encode(message)
alice_bob_encoded_message = bob.encode(alice_encoded_message)
bob_encoded_message = alice.decode(alice_bob_encoded_message)
decoded_message = bob.decode(bob_encoded_message)
decoded_message.measure(0, 0)
test = transpile(decoded_message, backend)
qobj = assemble(test)
counts = backend.run(qobj, shots=n_shots).result().get_counts()
if not '0' in counts.keys():
counts['0'] = 0
obtained_prob = counts['0'] / n_shots
EPSILON = 5
relative_error = abs(measure_zero_prob - obtained_prob)
check_probability = relative_error <= 0.01 * EPSILON
if verbose:
print('\nOutput: ' + str(counts))
print('\nInitial Message:')
print(message)
print('\nAlice-Encoded Message:')
print(alice_encoded_message)
print('\nAlice-and-Bob-Encoded Message:')
print(alice_bob_encoded_message)
print('\nBob-Encoded Message:')
print(bob_encoded_message)
print('\n💡 Decoded Message:')
print(decoded_message)
print('\nInput Probability:')
print(measure_zero_prob)
print('\nObtained Probability:')
print(obtained_prob)
print('\nRelative Error: ' + str(relative_error) + ' %')
if check_probability:
print('\n✅ The expected probability is obtained within an error range of ±' + str(EPSILON) + '%')
else:
print('\n❌ The expected probability is obtained with an error greater than ±' + str(EPSILON) + '%')
return check_probability, relative_error
def generate_message(self, measure_zero_prob):
a1 = sqrt(measure_zero_prob)
a2 = sqrt(1 - measure_zero_prob)
psi = Statevector([complex(a1, 0), complex(a2, 0)])
init_gate = Initialize(psi)
init_gate.label = 'Init'
qc = QuantumCircuit(1, 1)
qc.append(init_gate, [0])
qc.barrier()
return qc
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver()
problem = driver.run()
fermionic_op = problem.hamiltonian.second_q_op()
from qiskit_nature.second_q.mappers import JordanWignerMapper
mapper = JordanWignerMapper()
qubit_jw_op = mapper.map(fermionic_op)
print(qubit_jw_op)
from qiskit_nature.second_q.mappers import ParityMapper
mapper = ParityMapper()
qubit_p_op = mapper.map(fermionic_op)
print(qubit_p_op)
mapper = ParityMapper(num_particles=problem.num_particles)
qubit_op = mapper.map(fermionic_op)
print(qubit_op)
tapered_mapper = problem.get_tapered_mapper(mapper)
print(type(tapered_mapper))
qubit_op = tapered_mapper.map(fermionic_op)
print(qubit_op)
from qiskit_nature.second_q.circuit.library import HartreeFock
hf_state = HartreeFock(2, (1, 1), JordanWignerMapper())
hf_state.draw()
from qiskit_nature.second_q.mappers import InterleavedQubitMapper
interleaved_mapper = InterleavedQubitMapper(JordanWignerMapper())
hf_state = HartreeFock(2, (1, 1), interleaved_mapper)
hf_state.draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/VicentePerezSoloviev/QAOA_BNSL_IBM
|
VicentePerezSoloviev
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from QAOA_gen import QAOA
import pandas as pd
import random
import numpy as np
from qiskit import Aer, execute
progress = []
def random_init_parameters(layers):
random_float_list = []
for i in range(2*layers):
x = random.uniform(0, np.pi)
random_float_list.append(x)
return random_float_list
def get_qaoa_circuit(p, n, beta, gamma, alpha1, alpha2, weights):
qaoa = QAOA(n=n, alpha1=alpha1, alpha2=alpha2, weights=weights)
qaoa.add_superposition_layer()
qaoa.add_layer(p, beta, gamma)
qaoa.measure()
# dt = pd.DataFrame(columns=['state', 'prob', 'cost'])
# my_circuit = qaoa.my_program.to_circ() # Export this program into a quantum circuit
# my_circuit = qaoa.circuit
# print(my_circuit.parameters)
'''for i in range(p):
my_circuit = my_circuit.bind_parameters({"g" + str(i): gamma[i], "b" + str(i): beta[i]})'''
# qaoa.circuit.bind_parameters({})
return qaoa.circuit, qaoa
def get_black_box_objective(p, n, alpha1, alpha2, weights, nbshots, alpha, noise=None):
def f(theta):
beta = theta[:p]
gamma = theta[p:]
global progress
my_circuit, qaoa = get_qaoa_circuit(p, n, beta, gamma, alpha1, alpha2, weights)
dt = pd.DataFrame(columns=['state', 'prob', 'cost'])
# Create a job
# job = my_circuit.to_job(nbshots=nbshots)
backend = Aer.get_backend('qasm_simulator')
# Execute
if noise is not None:
# qpu_predef = NoisyQProc(hardware_model=noise)
# result = qpu_predef.submit(job)
# print('ei')
job = execute(my_circuit, backend, shots=nbshots, noise_model=noise)
else:
# print('ei')
# result = get_default_qpu().submit(job)
job = execute(my_circuit, backend, shots=nbshots)
result = job.result().get_counts()
avr_c = 0
for sample in result:
cost = qaoa.evaluate_solution(str(sample))
dt = dt.append({'state': str(sample),
'prob': float(result[sample]/nbshots),
'cost': cost}, ignore_index=True)
# avr_c = avr_c + (sample.probability * cost)
# Conditional Value at Risk (CVaR)
aux = int(len(dt) * alpha)
dt = dt.sort_values(by=['prob'], ascending=False).head(aux)
# dt = dt.nlargest(aux, 'cost')
dt = dt.reset_index()
# print(dict(dt.loc[0]))
sum_parc = dt['cost'].sum()
for i in range(len(dt)):
avr_c = avr_c + (float(dt.loc[i, 'prob'])*float(dt.loc[i, 'cost'])/sum_parc)
# print(dt.loc[i, 'prob'], dt.loc[i, 'cost'], avr_c)
progress.append(avr_c)
# print(avr_c)
return avr_c # negative when we want to maximize
# return min(dt['cost'])
return f
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
secretnumber = '11100011'
circuit = QuantumCircuit(len(secretnumber)+1,len(secretnumber))
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.h(len(secretnumber))
circuit.barrier()
for ii, yesno in enumerate(reversed(secretnumber)):
if yesno == '1':
circuit.cx(ii,len(secretnumber))
circuit.barrier()
circuit.h(range(len(secretnumber)))
circuit.barrier()
circuit.measure(range(len(secretnumber)),range(len(secretnumber)))
circuit.draw(output = 'mpl')
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests discrete sampled pulse functions."""
import numpy as np
from qiskit.test import QiskitTestCase
from qiskit.pulse import SamplePulse
import qiskit.pulse.pulse_lib as pulse_lib
import qiskit.pulse.pulse_lib.continuous as continuous
class TestDiscretePulses(QiskitTestCase):
"""Test discreted sampled pulses."""
def test_constant(self):
"""Test discrete sampled constant pulse."""
amp = 0.5j
duration = 10
times = np.arange(0, duration)
constant_ref = continuous.constant(times, amp=amp)
constant_pulse = pulse_lib.constant(duration, amp=amp)
self.assertIsInstance(constant_pulse, SamplePulse)
np.testing.assert_array_almost_equal(constant_pulse.samples, constant_ref)
def test_zero(self):
"""Test discrete sampled constant pulse."""
duration = 10
times = np.arange(0, duration)
zero_ref = continuous.zero(times)
zero_pulse = pulse_lib.zero(duration)
self.assertIsInstance(zero_pulse, SamplePulse)
np.testing.assert_array_almost_equal(zero_pulse.samples, zero_ref)
def test_square(self):
"""Test discrete sampled square wave."""
amp = 0.5
period = 5
duration = 10
times = np.arange(0, duration)
square_ref = continuous.square(times, amp=amp, period=period)
square_pulse = pulse_lib.square(duration, amp=amp, period=period)
self.assertIsInstance(square_pulse, SamplePulse)
np.testing.assert_array_almost_equal(square_pulse.samples, square_ref)
# test single cycle
cycle_period = duration
square_cycle_ref = continuous.square(times, amp=amp, period=cycle_period)
square_cycle_pulse = pulse_lib.square(duration, amp=amp)
np.testing.assert_array_almost_equal(square_cycle_pulse.samples, square_cycle_ref)
def test_sawtooth(self):
"""Test discrete sampled sawtooth wave."""
amp = 0.5
period = 5
duration = 10
times = np.arange(0, duration)
sawtooth_ref = continuous.sawtooth(times, amp=amp, period=period)
sawtooth_pulse = pulse_lib.sawtooth(duration, amp=amp, period=period)
self.assertIsInstance(sawtooth_pulse, SamplePulse)
np.testing.assert_array_equal(sawtooth_pulse.samples, sawtooth_ref)
# test single cycle
cycle_period = duration
sawtooth_cycle_ref = continuous.sawtooth(times, amp=amp, period=cycle_period)
sawtooth_cycle_pulse = pulse_lib.sawtooth(duration, amp=amp)
np.testing.assert_array_almost_equal(sawtooth_cycle_pulse.samples, sawtooth_cycle_ref)
def test_triangle(self):
"""Test discrete sampled triangle wave."""
amp = 0.5
period = 5
duration = 10
times = np.arange(0, duration)
triangle_ref = continuous.triangle(times, amp=amp, period=period)
triangle_pulse = pulse_lib.triangle(duration, amp=amp, period=period)
self.assertIsInstance(triangle_pulse, SamplePulse)
np.testing.assert_array_almost_equal(triangle_pulse.samples, triangle_ref)
# test single cycle
cycle_period = duration
triangle_cycle_ref = continuous.triangle(times, amp=amp, period=cycle_period)
triangle_cycle_pulse = pulse_lib.triangle(duration, amp=amp)
np.testing.assert_array_equal(triangle_cycle_pulse.samples, triangle_cycle_ref)
def test_cos(self):
"""Test discrete sampled cosine wave."""
amp = 0.5
period = 5
freq = 1/period
duration = 10
times = np.arange(0, duration)
cos_ref = continuous.cos(times, amp=amp, freq=freq)
cos_pulse = pulse_lib.cos(duration, amp=amp, freq=freq)
self.assertIsInstance(cos_pulse, SamplePulse)
np.testing.assert_array_almost_equal(cos_pulse.samples, cos_ref)
# test single cycle
cycle_freq = 1/duration
cos_cycle_ref = continuous.cos(times, amp=amp, freq=cycle_freq)
cos_cycle_pulse = pulse_lib.cos(duration, amp=amp)
np.testing.assert_array_almost_equal(cos_cycle_pulse.samples, cos_cycle_ref)
def test_sin(self):
"""Test discrete sampled sine wave."""
amp = 0.5
period = 5
freq = 1/period
duration = 10
times = np.arange(0, duration)
sin_ref = continuous.sin(times, amp=amp, freq=freq)
sin_pulse = pulse_lib.sin(duration, amp=amp, freq=freq)
self.assertIsInstance(sin_pulse, SamplePulse)
np.testing.assert_array_equal(sin_pulse.samples, sin_ref)
# test single cycle
cycle_freq = 1/duration
sin_cycle_ref = continuous.sin(times, amp=amp, freq=cycle_freq)
sin_cycle_pulse = pulse_lib.sin(duration, amp=amp)
np.testing.assert_array_almost_equal(sin_cycle_pulse.samples, sin_cycle_ref)
def test_gaussian(self):
"""Test gaussian pulse."""
amp = 0.5
sigma = 2
duration = 10
center = duration/2
times = np.arange(0, duration)
gaussian_ref = continuous.gaussian(times, amp, center, sigma,
zeroed_width=2*(center+1), rescale_amp=True)
gaussian_pulse = pulse_lib.gaussian(duration, amp, sigma)
self.assertIsInstance(gaussian_pulse, SamplePulse)
np.testing.assert_array_almost_equal(gaussian_pulse.samples, gaussian_ref)
def test_gaussian_deriv(self):
"""Test discrete sampled gaussian derivative pulse."""
amp = 0.5
sigma = 2
duration = 10
center = duration/2
times = np.arange(0, duration)
gaussian_deriv_ref = continuous.gaussian_deriv(times, amp, center, sigma)
gaussian_deriv_pulse = pulse_lib.gaussian_deriv(duration, amp, sigma)
self.assertIsInstance(gaussian_deriv_pulse, SamplePulse)
np.testing.assert_array_almost_equal(gaussian_deriv_pulse.samples, gaussian_deriv_ref)
def test_gaussian_square(self):
"""Test discrete sampled gaussian square pulse."""
amp = 0.5
sigma = 0.1
risefall = 2
duration = 10
center = duration/2
width = duration-2*risefall
center = duration/2
times = np.arange(0, duration)
gaussian_square_ref = continuous.gaussian_square(times, amp, center, width, sigma)
gaussian_square_pulse = pulse_lib.gaussian_square(duration, amp, sigma, risefall)
self.assertIsInstance(gaussian_square_pulse, SamplePulse)
np.testing.assert_array_almost_equal(gaussian_square_pulse.samples, gaussian_square_ref)
def test_drag(self):
"""Test discrete sampled drag pulse."""
amp = 0.5
sigma = 0.1
beta = 0
duration = 10
center = 10/2
times = np.arange(0, duration)
# reference drag pulse
drag_ref = continuous.drag(times, amp, center, sigma, beta=beta,
zeroed_width=2*(center+1), rescale_amp=True)
drag_pulse = pulse_lib.drag(duration, amp, sigma, beta=beta)
self.assertIsInstance(drag_pulse, SamplePulse)
np.testing.assert_array_almost_equal(drag_pulse.samples, drag_ref)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
# from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2*dt,0)
qc.rz(2*dt,1)
qc.h(1)
qc.cx(1,0)
qc.rz(-2*dt, 0)
qc.rx(-2*dt, 1)
qc.rz(2*dt, 1)
qc.cx(1,0)
qc.h(1)
qc.rz(2*dt, 0)
return qc.to_instruction() if to_instruction else qc
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
Trot_gate = trotter_gate(dt)
# Number of trotter steps
trotter_steps = 15 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, [qr[3], qr[5]])
qc.cx(qr[3], qr[1])
qc.cx(qr[5], qr[3])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time/trotter_steps})
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw("mpl") # only view trotter gates
st_qcs[13].draw("mpl")
# Pauli Twirling
# TODO: 一度挙動を調べる
def pauli_twirling(circ: str) -> QuantumCircuit:
"""
そのまま使う: 修正は後回し
"""
#! qasm ベタ書き
def apply_pauli(num: int, qb: int) -> str:
if (num == 0):
return f'id q[{qb}];\n'
elif (num == 1):
return f'x q[{qb}];\n'
elif (num == 2):
return f'y q[{qb}];\n'
else:
return f'z q[{qb}];\n'
paulis = [(i,j) for i in range(0,4) for j in range(0,4)]
paulis.remove((0,0))
paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)]
new_circ = ''
ops = circ.qasm().splitlines(True) #! 生のqasmコードを持ってきてる: オペレータに分解
for op in ops:
if (op[:2] == 'cx'): # can add for cz, etc.
num = random.randrange(len(paulis)) #! permute paulis
qbs = re.findall('q\[(.)\]', op)
new_circ += apply_pauli(paulis[num][0], qbs[0])
new_circ += apply_pauli(paulis[num][1], qbs[1])
new_circ += op
new_circ += apply_pauli(paulis_map[num][0], qbs[0])
new_circ += apply_pauli(paulis_map[num][1], qbs[1])
else:
new_circ += op
return qiskit.circuit.QuantumCircuit.from_qasm_str(new_circ)
# ZNE
# 3種類の実行方法
# 1. state tomography回路全体をzne
# 2. state tomography前の回路をzne
# 3. 2-qubitの状態だけzne
# 今回は1を実装する
def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0]):
"""
"""
folded_qcs = [] #! ZNE用の回路
for qc in qcs:
folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用
folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化
folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] #! 後からPauli Twirlingを施す!
return folded_qcs
# subspace expansion
# TODO: 実装はとりあえず後回し
def se_wrapper(qcs):
"""
"""
folded_qcs = []
for qc in qcs:
pass
return folded_qcs
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# backend = provider.get_backend("ibmq_jakarta")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3)
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
def make_basis(n):
basis = np.zeros((1 << n, n), dtype="int")
return basis
def measurement_basis(v):
I = np.array([[1,0],[0,1]], dtype="complex")
X = np.array([[0,1],[1,0]], dtype="complex")
Y = np.array([[0,-1j],[1j,0]], dtype="complex")
Z = np.array([[1,0],[0,-1]], dtype="complex")
ret = I
for i in v:
if i == 0:
ret = np.kron(ret, I)
elif i == 1:
ret = np.kron(ret, X)
elif i == 2:
ret = np.kron(ret, Y)
elif i == 3:
ret = np.kron(ret, Z)
else:
raise Exception
return ret
def state_tomography(n, expvals, vs):
rho = np.zeros((1 << n, 1 << n), dtype="complex")
for i, v in enumerate(vs):
rho += expvals[i] * measurement_basis(v)
return rho / (1 << n)
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(expvals, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
stf = StateTomographyFitter(job.result(), st_qcs)
stf._data
from IPython.core.debugger import Pdb; Pdb().set_trace()
data, basis_matrix, weights = stf._fitter_data(True, 0.5)
next(iter(stf._data))
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
fids = []
for job in jobs:
fid = state_tomo(job.result(), st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/drobiu/quantum-project
|
drobiu
|
import os
import math
from getpass import getpass
from coreapi.auth import TokenAuthentication
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from quantuminspire.credentials import get_authentication
from quantuminspire.qiskit import QI
QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')
QI.set_authentication()
qi_backend = QI.get_backend('QX single-node simulator')
q = QuantumRegister(4, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2, name="uneven dice")
qc.h(q[0:3])
# If q_0 is 1, set q_3 to 1
qc.cnot(q[0], q[3])
# Swap q_0 with q_2 if q_3 is 1
qc.fredkin(q[3], q[0], q[2])
# Not q_0 if q_2 and q_1 were 1 (75% of the shots)
qc.toffoli(q[1], q[2], q[0])
qc.measure(q[0], c0)
qc.measure(q[1], c1)
qc.measure(q[2], c2)
qi_job = execute(qc, backend=qi_backend, shots=1024)
qi_result = qi_job.result()
histogram = qi_result.get_counts(qc)
print("\nResult from the remote Quantum Inspire backend:\n")
print('State\tCounts')
[print('{0}\t{1}'.format(state, counts)) for state, counts in histogram.items()]
print("\nResult from the local Qiskit simulator backend:\n")
backend = BasicAer.get_backend("qasm_simulator")
job = execute(qc, backend=backend, shots=1024)
result = job.result()
print(result.get_counts(qc))
qc.draw(output="mpl")
|
https://github.com/abbarreto/qiskit3
|
abbarreto
| |
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"Circuit operation representing a ``for`` loop."
import warnings
from typing import Iterable, Optional, Union
from qiskit.circuit.parameter import Parameter
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit.quantumcircuit import QuantumCircuit
from .control_flow import ControlFlowOp
class ForLoopOp(ControlFlowOp):
"""A circuit operation which repeatedly executes a subcircuit
(``body``) parameterized by a parameter ``loop_parameter`` through
the set of integer values provided in ``indexset``.
Parameters:
indexset: A collection of integers to loop over.
loop_parameter: The placeholder parameterizing ``body`` to which
the values from ``indexset`` will be assigned.
body: The loop body to be repeatedly executed.
label: An optional label for identifying the instruction.
**Circuit symbol:**
.. parsed-literal::
┌───────────┐
q_0: ┤0 ├
│ │
q_1: ┤1 ├
│ for_loop │
q_2: ┤2 ├
│ │
c_0: ╡0 ╞
└───────────┘
"""
def __init__(
self,
indexset: Iterable[int],
loop_parameter: Union[Parameter, None],
body: QuantumCircuit,
label: Optional[str] = None,
):
num_qubits = body.num_qubits
num_clbits = body.num_clbits
super().__init__(
"for_loop", num_qubits, num_clbits, [indexset, loop_parameter, body], label=label
)
@property
def params(self):
return self._params
@params.setter
def params(self, parameters):
indexset, loop_parameter, body = parameters
if not isinstance(loop_parameter, (Parameter, type(None))):
raise CircuitError(
"ForLoopOp expects a loop_parameter parameter to "
"be either of type Parameter or None, but received "
f"{type(loop_parameter)}."
)
if not isinstance(body, QuantumCircuit):
raise CircuitError(
"ForLoopOp expects a body parameter to be of type "
f"QuantumCircuit, but received {type(body)}."
)
if body.num_qubits != self.num_qubits or body.num_clbits != self.num_clbits:
raise CircuitError(
"Attempted to assign a body parameter with a num_qubits or "
"num_clbits different than that of the ForLoopOp. "
f"ForLoopOp num_qubits/clbits: {self.num_qubits}/{self.num_clbits} "
f"Supplied body num_qubits/clbits: {body.num_qubits}/{body.num_clbits}."
)
if (
loop_parameter is not None
and loop_parameter not in body.parameters
and loop_parameter.name in (p.name for p in body.parameters)
):
warnings.warn(
"The Parameter provided as a loop_parameter was not found "
"on the loop body and so no binding of the indexset to loop "
"parameter will occur. A different Parameter of the same name "
f"({loop_parameter.name}) was found. If you intended to loop "
"over that Parameter, please use that Parameter instance as "
"the loop_parameter.",
stacklevel=2,
)
# Consume indexset into a tuple unless it was provided as a range.
# Preserve ranges so that they can be exported as OpenQASM3 ranges.
indexset = indexset if isinstance(indexset, range) else tuple(indexset)
self._params = [indexset, loop_parameter, body]
@property
def blocks(self):
return (self._params[2],)
def replace_blocks(self, blocks):
(body,) = blocks
return ForLoopOp(self.params[0], self.params[1], body, label=self.label)
class ForLoopContext:
"""A context manager for building up ``for`` loops onto circuits in a natural order, without
having to construct the loop body first.
Within the block, a lot of the bookkeeping is done for you; you do not need to keep track of
which qubits and clbits you are using, for example, and a loop parameter will be allocated for
you, if you do not supply one yourself. All normal methods of accessing the qubits on the
underlying :obj:`~QuantumCircuit` will work correctly, and resolve into correct accesses within
the interior block.
You generally should never need to instantiate this object directly. Instead, use
:obj:`.QuantumCircuit.for_loop` in its context-manager form, i.e. by not supplying a ``body`` or
sets of qubits and clbits.
Example usage::
import math
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 1)
with qc.for_loop(range(5)) as i:
qc.rx(i * math.pi/4, 0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.break_loop().c_if(0, True)
This context should almost invariably be created by a :meth:`.QuantumCircuit.for_loop` call, and
the resulting instance is a "friend" of the calling circuit. The context will manipulate the
circuit's defined scopes when it is entered (by pushing a new scope onto the stack) and exited
(by popping its scope, building it, and appending the resulting :obj:`.ForLoopOp`).
.. warning::
This is an internal interface and no part of it should be relied upon outside of Qiskit
Terra.
"""
# Class-level variable keep track of the number of auto-generated loop variables, so we don't
# get naming clashes.
_generated_loop_parameters = 0
__slots__ = (
"_circuit",
"_generate_loop_parameter",
"_loop_parameter",
"_indexset",
"_label",
"_used",
)
def __init__(
self,
circuit: QuantumCircuit,
indexset: Iterable[int],
loop_parameter: Optional[Parameter] = None,
*,
label: Optional[str] = None,
):
self._circuit = circuit
self._generate_loop_parameter = loop_parameter is None
self._loop_parameter = loop_parameter
# We can pass through `range` instances because OpenQASM 3 has native support for this type
# of iterator set.
self._indexset = indexset if isinstance(indexset, range) else tuple(indexset)
self._label = label
self._used = False
def __enter__(self):
if self._used:
raise CircuitError("A for-loop context manager cannot be re-entered.")
self._used = True
self._circuit._push_scope()
if self._generate_loop_parameter:
self._loop_parameter = Parameter(f"_loop_i_{self._generated_loop_parameters}")
type(self)._generated_loop_parameters += 1
return self._loop_parameter
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
# If we're leaving the context manager because an exception was raised, there's nothing
# to do except restore the circuit state.
self._circuit._pop_scope()
return False
scope = self._circuit._pop_scope()
# Loops do not need to pass any further resources in, because this scope itself defines the
# extent of ``break`` and ``continue`` statements.
body = scope.build(scope.qubits, scope.clbits)
# We always bind the loop parameter if the user gave it to us, even if it isn't actually
# used, because they requested we do that by giving us a parameter. However, if they asked
# us to auto-generate a parameter, then we only add it if they actually used it, to avoid
# using unnecessary resources.
if self._generate_loop_parameter and self._loop_parameter not in body.parameters:
loop_parameter = None
else:
loop_parameter = self._loop_parameter
self._circuit.append(
ForLoopOp(self._indexset, loop_parameter, body, label=self._label),
tuple(body.qubits),
tuple(body.clbits),
)
return False
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""Qobj tests."""
import copy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler import assemble
from qiskit.qobj import (
QasmQobj,
PulseQobj,
QobjHeader,
PulseQobjInstruction,
PulseQobjExperiment,
PulseQobjConfig,
QobjMeasurementOption,
PulseLibraryItem,
QasmQobjInstruction,
QasmQobjExperiment,
QasmQobjConfig,
QasmExperimentCalibrations,
GateCalibration,
)
from qiskit.test import QiskitTestCase
class TestQASMQobj(QiskitTestCase):
"""Tests for QasmQobj."""
def setUp(self):
super().setUp()
self.valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
]
)
],
)
self.valid_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.2.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
]
}
],
}
self.bad_qobj = copy.deepcopy(self.valid_qobj)
self.bad_qobj.experiments = []
def test_from_dict_per_class(self):
"""Test Qobj and its subclass representations given a dictionary."""
test_parameters = {
QasmQobj: (self.valid_qobj, self.valid_dict),
QasmQobjConfig: (
QasmQobjConfig(shots=1, memory_slots=2),
{"shots": 1, "memory_slots": 2},
),
QasmQobjExperiment: (
QasmQobjExperiment(
instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])]
),
{"instructions": [{"name": "u1", "qubits": [1], "params": [0.4]}]},
),
QasmQobjInstruction: (
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
{"name": "u1", "qubits": [1], "params": [0.4]},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict))
def test_snapshot_instruction_to_dict(self):
"""Test snapshot instruction to dict."""
valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
QasmQobjInstruction(
name="snapshot",
qubits=[1],
snapshot_type="statevector",
label="my_snap",
),
]
)
],
)
res = valid_qobj.to_dict()
expected_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.3.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
{
"name": "snapshot",
"qubits": [1],
"snapshot_type": "statevector",
"label": "my_snap",
},
],
"config": {},
"header": {},
}
],
}
self.assertEqual(expected_dict, res)
def test_snapshot_instruction_from_dict(self):
"""Test snapshot instruction from dict."""
expected_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
QasmQobjInstruction(
name="snapshot",
qubits=[1],
snapshot_type="statevector",
label="my_snap",
),
]
)
],
)
qobj_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.2.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
{
"name": "snapshot",
"qubits": [1],
"snapshot_type": "statevector",
"label": "my_snap",
},
]
}
],
}
self.assertEqual(expected_qobj, QasmQobj.from_dict(qobj_dict))
def test_change_qobj_after_compile(self):
"""Test modifying Qobj parameters after compile."""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
qc1 = QuantumCircuit(qr, cr)
qc2 = QuantumCircuit(qr, cr)
qc1.h(qr[0])
qc1.cx(qr[0], qr[1])
qc1.cx(qr[0], qr[2])
qc2.h(qr)
qc1.measure(qr, cr)
qc2.measure(qr, cr)
circuits = [qc1, qc2]
qobj1 = assemble(circuits, shots=1024, seed=88)
qobj1.experiments[0].config.shots = 50
qobj1.experiments[1].config.shots = 1
self.assertTrue(qobj1.experiments[0].config.shots == 50)
self.assertTrue(qobj1.experiments[1].config.shots == 1)
self.assertTrue(qobj1.config.shots == 1024)
def test_gate_calibrations_to_dict(self):
"""Test gate calibrations to dict."""
pulse_library = [PulseLibraryItem(name="test", samples=[1j, 1j])]
valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2, pulse_library=pulse_library),
experiments=[
QasmQobjExperiment(
instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])],
config=QasmQobjConfig(
calibrations=QasmExperimentCalibrations(
gates=[
GateCalibration(
name="u1", qubits=[1], params=[0.4], instructions=[]
)
]
)
),
)
],
)
res = valid_qobj.to_dict()
expected_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.3.0",
"header": {},
"config": {
"memory_slots": 2,
"shots": 1024,
"pulse_library": [{"name": "test", "samples": [1j, 1j]}],
},
"experiments": [
{
"instructions": [{"name": "u1", "params": [0.4], "qubits": [1]}],
"config": {
"calibrations": {
"gates": [
{"name": "u1", "qubits": [1], "params": [0.4], "instructions": []}
]
}
},
"header": {},
}
],
}
self.assertEqual(expected_dict, res)
class TestPulseQobj(QiskitTestCase):
"""Tests for PulseQobj."""
def setUp(self):
super().setUp()
self.valid_qobj = PulseQobj(
qobj_id="12345",
header=QobjHeader(),
config=PulseQobjConfig(
shots=1024,
memory_slots=2,
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[
PulseLibraryItem(name="pulse0", samples=[0.0 + 0.0j, 0.5 + 0.0j, 0.0 + 0.0j])
],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
experiments=[
PulseQobjExperiment(
instructions=[
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=1.57),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=0.0),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase="P1"),
PulseQobjInstruction(name="setp", t0=10, ch="d0", phase=3.14),
PulseQobjInstruction(name="setf", t0=10, ch="d0", frequency=8.0),
PulseQobjInstruction(name="shiftf", t0=10, ch="d0", frequency=4.0),
PulseQobjInstruction(
name="acquire",
t0=15,
duration=5,
qubits=[0],
memory_slot=[0],
kernels=[
QobjMeasurementOption(
name="boxcar", params={"start_window": 0, "stop_window": 5}
)
],
),
]
)
],
)
self.valid_dict = {
"qobj_id": "12345",
"type": "PULSE",
"schema_version": "1.2.0",
"header": {},
"config": {
"memory_slots": 2,
"shots": 1024,
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0, 0.5, 0]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
"experiments": [
{
"instructions": [
{"name": "pulse0", "t0": 0, "ch": "d0"},
{"name": "fc", "t0": 5, "ch": "d0", "phase": 1.57},
{"name": "fc", "t0": 5, "ch": "d0", "phase": 0},
{"name": "fc", "t0": 5, "ch": "d0", "phase": "P1"},
{"name": "setp", "t0": 10, "ch": "d0", "phase": 3.14},
{"name": "setf", "t0": 10, "ch": "d0", "frequency": 8.0},
{"name": "shiftf", "t0": 10, "ch": "d0", "frequency": 4.0},
{
"name": "acquire",
"t0": 15,
"duration": 5,
"qubits": [0],
"memory_slot": [0],
"kernels": [
{"name": "boxcar", "params": {"start_window": 0, "stop_window": 5}}
],
},
]
}
],
}
def test_from_dict_per_class(self):
"""Test converting to Qobj and its subclass representations given a dictionary."""
test_parameters = {
PulseQobj: (self.valid_qobj, self.valid_dict),
PulseQobjConfig: (
PulseQobjConfig(
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
{
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
),
PulseLibraryItem: (
PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]),
{"name": "pulse0", "samples": [0.1 + 0j]},
),
PulseQobjExperiment: (
PulseQobjExperiment(
instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")]
),
{"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]},
),
PulseQobjInstruction: (
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
{"name": "pulse0", "t0": 0, "ch": "d0"},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict))
def test_to_dict_per_class(self):
"""Test converting from Qobj and its subclass representations given a dictionary."""
test_parameters = {
PulseQobj: (self.valid_qobj, self.valid_dict),
PulseQobjConfig: (
PulseQobjConfig(
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
{
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
),
PulseLibraryItem: (
PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]),
{"name": "pulse0", "samples": [0.1 + 0j]},
),
PulseQobjExperiment: (
PulseQobjExperiment(
instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")]
),
{"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]},
),
PulseQobjInstruction: (
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
{"name": "pulse0", "t0": 0, "ch": "d0"},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item.to_dict(), expected_dict)
def _nop():
pass
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Statevector
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.estimation import EuropeanCallPricing
from qiskit_finance.circuit.library import NormalDistribution
# Set upper and lower data values
bounds = np.array([0.0, 7.0])
# Set number of qubits used in the uncertainty model
num_qubits = 3
# Load the trained circuit parameters
g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225]
# Set an initial state for the generator circuit
init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds)
# construct the variational form
var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1)
# keep a list of the parameters so we can associate them to the list of numerical values
# (otherwise we need a dictionary)
theta = var_form.ordered_parameters
# compose the generator circuit, this is the circuit loading the uncertainty model
g_circuit = init_dist.compose(var_form)
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2
# set the approximation scaling for the payoff function
c_approx = 0.25
# Evaluate trained probability distribution
values = [
bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits)
]
uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params)))
amplitudes = Statevector.from_instruction(uncertainty_model).data
x = np.array(values)
y = np.abs(amplitudes) ** 2
# Sample from target probability distribution
N = 100000
log_normal = np.random.lognormal(mean=1, sigma=1, size=N)
log_normal = np.round(log_normal)
log_normal = log_normal[log_normal <= 7]
log_normal_samples = []
for i in range(8):
log_normal_samples += [np.sum(log_normal == i)]
log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples))
# Plot distributions
plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue")
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.plot(
log_normal_samples,
"-o",
color="deepskyblue",
label="target distribution",
linewidth=4,
markersize=12,
)
plt.legend(loc="best")
plt.show()
# Evaluate payoff for different distributions
payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5])
ep = np.dot(log_normal_samples, payoff)
print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep)
ep_trained = np.dot(y, payoff)
print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained)
# Plot exact payoff function (evaluated on the grid of the trained uncertainty model)
x = np.array(values)
y_strike = np.maximum(0, x - strike_price)
plt.plot(x, y_strike, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# construct circuit for payoff function
european_call_pricing = EuropeanCallPricing(
num_qubits,
strike_price=strike_price,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=uncertainty_model,
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_pricing.to_estimation_problem()
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % ep_trained)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the merge.py module.
"""
import unittest
import numpy as np
from qiskit import QuantumCircuit
from qclib.state_preparation import MergeInitialize
from qclib.util import get_state, build_state_dict
from qiskit import transpile
from scipy.sparse import random
# pylint: disable=missing-function-docstring
# pylint: disable=missing-class-docstring
class TestMergeInitialize(unittest.TestCase):
""" Teste MergeInitialize Gate"""
def test_two_states_uniform(self):
state_vector = 1 / np.sqrt(2) * np.array([1, 0, 0, 0, 0, 1, 0, 0])
state_dict = build_state_dict(state_vector)
initialize = MergeInitialize.initialize
circ = QuantumCircuit(3)
initialize(circ, state_dict)
state = get_state(circ)
self.assertTrue(np.allclose(state_vector, state))
def test_three_states_superposition(self):
state_vector = 1 / np.sqrt(168) * np.array([0, 2, 0, 0, 8, 0, 0, 10])
state_dict = build_state_dict(state_vector)
initialize = MergeInitialize.initialize
circ = QuantumCircuit(3)
initialize(circ, state_dict)
state = get_state(circ)
self.assertTrue(np.allclose(state_vector, state))
def test_three_states_uniform_superposition(self):
state_vector = 1 / np.sqrt(3) * np.array([0, 1, 0, 0, 1, 0, 0, 1])
state_dict = build_state_dict(state_vector)
initialize = MergeInitialize.initialize
circ = QuantumCircuit(3)
initialize(circ, state_dict)
state = get_state(circ)
self.assertTrue(np.allclose(state_vector, state))
def test_three_states_superposition_with_complex_features(self):
state_vector = np.array([0, complex(np.sqrt(0.1), np.sqrt(0.1)), 0, 0,
complex(np.sqrt(0.1), np.sqrt(0.2)), 0, 0, np.sqrt(0.5)])
state_dict = build_state_dict(state_vector)
initialize = MergeInitialize.initialize
circ = QuantumCircuit(3)
initialize(circ, state_dict)
state = get_state(circ)
self.assertTrue(np.allclose(state_vector, state))
def test_raises_error_input_not_dict(self):
initialize = MergeInitialize.initialize
circ = QuantumCircuit()
with self.assertRaises(Exception):
initialize(circ, [])
def test_8qb_sparse(self):
state_dict = {
'01100000': 0.11496980229422502,
'10010000': 0.2012068017595738,
'11110000': 0.2552406117427385,
'11001000': 0.24483730989689545,
'00011000': 0.08064396530053637,
'01111000': 0.06609205232425505,
'10000100': 0.2567251902135311,
'00100010': 0.279179786457501,
'11110010': 0.14972323818181424,
'00000110': 0.054570286103576615,
'10101110': 0.1953959409811345,
'00011110': 0.2476316976925628,
'00111110': 0.2460713287965397,
'00010001': 0.2880964575493704,
'00011001': 0.11697558413298771,
'11100101': 0.15657582325155645,
'00101101': 0.05059343291713247,
'10011101': 0.21260965910383026,
'11100011': 0.16144719592639006,
'01110011': 0.24224885089395568,
'10011011': 0.07542653172823867,
'01111011': 0.2840232568261471,
'00100111': 0.2719803407586484,
'01100111': 0.14940066988379283,
'11010111': 0.2025293455684502,
'01001111': 0.06045929196877916
}
initialize = MergeInitialize.initialize
qc = QuantumCircuit(8)
initialize(qc, state_dict)
t_circuit = transpile(qc, basis_gates=['cx', 'u'])
def test_several_qubit_sizes(self):
for n_qubits in range(4, 12):
state_vector = random(1, 2 ** n_qubits, density=0.1, random_state=42).A.reshape(-1)
state_vector = state_vector / np.linalg.norm(state_vector)
state_dict = build_state_dict(state_vector)
initialize = MergeInitialize.initialize
qc = QuantumCircuit(n_qubits)
initialize(qc, state_dict)
state = get_state(qc)
self.assertTrue(np.allclose(state_vector, state))
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
# importing the QISKit
from qiskit import QuantumCircuit, QuantumProgram
import Qconfig
# import tomography library
import qiskit.tools.qcvv.tomography as tomo
#visualization packages
from qiskit.tools.visualization import plot_wigner_function, plot_wigner_data
density_matrix = np.matrix([[0.5, 0, 0, 0.5],[0, 0, 0, 0],[0, 0, 0, 0],[0.5, 0, 0, 0.5]])
print(density_matrix)
plot_wigner_function(density_matrix, res=200)
import sympy as sym
from sympy.physics.quantum import TensorProduct
num = int(np.log2(len(density_matrix)))
harr = sym.sqrt(3)
Delta_su2 = sym.zeros(2)
Delta = sym.ones(1)
for qubit in range(num):
phi = sym.Indexed('phi', qubit)
theta = sym.Indexed('theta', qubit)
costheta = harr*sym.cos(2*theta)
sintheta = harr*sym.sin(2*theta)
Delta_su2[0,0] = (1+costheta)/2
Delta_su2[0,1] = -(sym.exp(2j*phi)*sintheta)/2
Delta_su2[1,0] = -(sym.exp(-2j*phi)*sintheta)/2
Delta_su2[1,1] = (1-costheta)/2
Delta = TensorProduct(Delta,Delta_su2)
W = sym.trace(density_matrix*Delta)
print(sym.latex(W))
Q_program = QuantumProgram()
number_of_qubits = 2
backend = 'local_qasm_simulator'
shots = 1024
bell_qubits = [0, 1]
qr = Q_program.create_quantum_register('qr',2)
cr = Q_program.create_classical_register('cr',2)
bell = Q_program.create_circuit('bell', [qr], [cr])
bell.h(qr[0])
bell.cx(qr[0],qr[1])
bell_tomo_set = tomo.state_tomography_set([0, 1])
bell_tomo_circuits = tomo.create_tomography_circuits(Q_program, 'bell', qr, cr, bell_tomo_set)
bell_tomo_result = Q_program.execute(bell_tomo_circuits, backend=backend, shots=shots)
bell_tomo_data = tomo.tomography_data(bell_tomo_result, 'bell', bell_tomo_set)
rho_fit_sim = tomo.fit_tomography_data(bell_tomo_data)
plot_wigner_function(np.matrix(rho_fit_sim),res=200)
Delta_su2 = sym.zeros(2)
Delta = sym.ones(1)
for qubit in range(num):
phi = sym.Indexed('phi', qubit)
theta = sym.Indexed('theta', qubit)
costheta = harr*sym.cos(2*theta)
sintheta = harr*sym.sin(2*theta)
Delta_su2[0,0] = (1+costheta)/2
Delta_su2[0,1] = -(sym.exp(2j*phi)*sintheta)/2
Delta_su2[1,0] = -(sym.exp(-2j*phi)*sintheta)/2
Delta_su2[1,1] = (1-costheta)/2
Delta = TensorProduct(Delta,Delta_su2)
W = sym.trace(np.matrix(rho_fit_sim)*Delta)
print(sym.latex(W))
Q_program.set_api(Qconfig.APItoken, Qconfig.config['url'])
backend = 'ibmqx2'
max_credits = 8
shots = 1024
bell_qubits = [0, 1]
bell_tomo_set = tomo.state_tomography_set(bell_qubits)
bell_tomo_circuits = tomo.create_tomography_circuits(Q_program, 'bell', qr, cr, bell_tomo_set)
bell_tomo_result = Q_program.execute(bell_tomo_circuits, backend=backend, shots=shots,
max_credits=max_credits, timeout=300)
bell_tomo_data = tomo.tomography_data(bell_tomo_result, 'bell', bell_tomo_set)
rho_fit_ibmqx = tomo.fit_tomography_data(bell_tomo_data)
plot_wigner_function(np.matrix(rho_fit_ibmqx), res=100)
print(rho_fit_ibmqx)
Delta_su2 = sym.zeros(2)
Delta = sym.ones(1)
for qubit in range(num):
phi = sym.Indexed('phi', qubit)
theta = sym.Indexed('theta', qubit)
costheta = harr*sym.cos(2*theta)
sintheta = harr*sym.sin(2*theta)
Delta_su2[0,0] = (1+costheta)/2
Delta_su2[0,1] = -(sym.exp(2j*phi)*sintheta)/2
Delta_su2[1,0] = -(sym.exp(-2j*phi)*sintheta)/2
Delta_su2[1,1] = (1-costheta)/2
Delta = TensorProduct(Delta,Delta_su2)
W = sym.trace(np.matrix(rho_fit_ibmqx)*Delta)
print(sym.latex(W))
theta1_points = 8
theta2_points = 8
number_of_points = theta1_points*theta2_points
the1 = [0]*number_of_points
the2 = [0]*number_of_points #initialize theta values
phis = [[0]*number_of_points]*number_of_qubits #set phi values to 0
point = 0
for i in range(theta1_points):
for k in range(theta2_points):
the1[point] = 2*i*np.pi/theta1_points
the2[point] = 2*k*np.pi/theta2_points #create the values of theta for all points on plot
point += 1
thetas = np.vstack((the1,the2))
bell_circuits = tomo.build_wigner_circuits(Q_program, 'bell', phis, thetas,
bell_qubits, qr, cr)
backend = 'local_qasm_simulator'
shots = 1024
bell_result = Q_program.execute(bell_circuits, backend=backend, shots=shots)
print(bell_result)
wdata = tomo.wigner_data(bell_result, bell_qubits,
bell_circuits, shots=shots)
wdata = np.matrix(wdata)
wdata = wdata.reshape(theta1_points,theta2_points)
plot_wigner_data(wdata, method='plaquette')
equator_points = 64
theta = [np.pi/2]*equator_points
phi = [0]*equator_points
point = 0
for i in range(equator_points):
phi[i] = 2*i*np.pi/equator_points
thetas = np.vstack((theta,theta))
phis = np.vstack((phi,phi))
bell_eq_circuits = tomo.build_wigner_circuits(Q_program, 'bell', phis, thetas,
bell_qubits, qr, cr)
bell_eq_result = Q_program.execute(bell_eq_circuits, backend=backend, shots=shots)
wdata_eq = tomo.wigner_data(bell_eq_result, bell_qubits,
bell_eq_circuits, shots=shots)
plot_wigner_data(wdata_eq, method='curve')
Q_program = QuantumProgram()
number_of_qubits = 5
backend = 'local_qasm_simulator'
shots = 1024
ghz_qubits = [0, 1, 2, 3, 4]
qr = Q_program.create_quantum_register('qr',5)
cr = Q_program.create_classical_register('cr',5)
ghz = Q_program.create_circuit('ghz', [qr], [cr])
ghz.h(qr[0])
ghz.h(qr[1])
ghz.x(qr[2])
ghz.h(qr[3])
ghz.h(qr[4])
ghz.cx(qr[0],qr[2])
ghz.cx(qr[1],qr[2])
ghz.cx(qr[3],qr[2])
ghz.cx(qr[4],qr[2])
ghz.h(qr[0])
ghz.h(qr[1])
ghz.h(qr[2])
ghz.h(qr[3])
ghz.h(qr[4])
equator_points = 64
thetas = [[np.pi/2]*equator_points]*number_of_qubits
phi = [0]*equator_points
point = 0
for i in range(equator_points):
phi[i] = 2*i*np.pi/equator_points
phis = np.vstack((phi,phi,phi,phi,phi))
ghz_eq_circuits = tomo.build_wigner_circuits(Q_program, 'ghz', phis, thetas,
ghz_qubits, qr, cr)
ghz_eq_result = Q_program.execute(ghz_eq_circuits, backend=backend, shots=shots, timeout = 300)
wghzdata_eq = tomo.wigner_data(ghz_eq_result, ghz_qubits,
ghz_eq_circuits, shots=shots)
plot_wigner_data(wghzdata_eq, method='curve')
import matplotlib.pyplot as plt
plt.plot(phi, wghzdata_eq, 'o')
plt.axis([0, 2*np.pi, -0.6, 0.6])
plt.show()
density_matrix = np.zeros((32,32))
density_matrix[0][0] = 0.5
density_matrix[0][31] = -0.5
density_matrix[31][0] = -0.5
density_matrix[31][31] = 0.5
plot_wigner_function(density_matrix, res=200)
|
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/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Simulator command to snapshot internal simulator representation.
"""
import warnings
from qiskit import QuantumCircuit
from qiskit.circuit import CompositeGate
from qiskit import QuantumRegister
from qiskit.circuit import Instruction
from qiskit.extensions.exceptions import ExtensionError
class Snapshot(Instruction):
"""Simulator snapshot instruction."""
def __init__(self,
label,
snapshot_type='statevector',
num_qubits=0,
num_clbits=0,
params=None):
"""Create new snapshot instruction.
Args:
label (str): the snapshot label for result data.
snapshot_type (str): the type of the snapshot.
num_qubits (int): the number of qubits for the snapshot type [Default: 0].
num_clbits (int): the number of classical bits for the snapshot type [Default: 0].
params (list or None): the parameters for snapshot_type [Default: None].
Raises:
ExtensionError: if snapshot label is invalid.
"""
if not isinstance(label, str):
raise ExtensionError('Snapshot label must be a string.')
self._label = label
self._snapshot_type = snapshot_type
if params is None:
params = []
super().__init__('snapshot', num_qubits, num_clbits, params)
def assemble(self):
"""Assemble a QasmQobjInstruction"""
instruction = super().assemble()
instruction.label = self._label
instruction.snapshot_type = self._snapshot_type
return instruction
def inverse(self):
"""Special case. Return self."""
return Snapshot(self.num_qubits, self.num_clbits, self.params[0],
self.params[1])
@property
def snapshot_type(self):
"""Return snapshot type"""
return self._snapshot_type
@property
def label(self):
"""Return snapshot label"""
return self._label
@label.setter
def label(self, name):
"""Set snapshot label to name
Args:
name (str or None): label to assign unitary
Raises:
TypeError: name is not string or None.
"""
if isinstance(name, str):
self._label = name
else:
raise TypeError('label expects a string')
def snapshot(self,
label,
snapshot_type='statevector',
qubits=None,
params=None):
"""Take a statevector snapshot of the internal simulator representation.
Works on all qubits, and prevents reordering (like barrier).
For other types of snapshots use the Snapshot extension directly.
Args:
label (str): a snapshot label to report the result
snapshot_type (str): the type of the snapshot.
qubits (list or None): the qubits to apply snapshot to [Default: None].
params (list or None): the parameters for snapshot_type [Default: None].
Returns:
QuantumCircuit: with attached command
Raises:
ExtensionError: malformed command
"""
# Convert label to string for backwards compatibility
if not isinstance(label, str):
warnings.warn(
"Snapshot label should be a string, "
"implicit conversion is depreciated.", DeprecationWarning)
label = str(label)
# If no qubits are specified we add all qubits so it acts as a barrier
# This is needed for full register snapshots like statevector
if isinstance(qubits, QuantumRegister):
qubits = qubits[:]
if not qubits:
tuples = []
if isinstance(self, QuantumCircuit):
for register in self.qregs:
tuples.append(register)
if not tuples:
raise ExtensionError('no qubits for snapshot')
qubits = []
for tuple_element in tuples:
if isinstance(tuple_element, QuantumRegister):
for j in range(tuple_element.size):
qubits.append((tuple_element, j))
else:
qubits.append(tuple_element)
return self.append(
Snapshot(
label,
snapshot_type=snapshot_type,
num_qubits=len(qubits),
params=params), qubits)
# Add to QuantumCircuit and CompositeGate classes
QuantumCircuit.snapshot = snapshot
CompositeGate.snapshot = snapshot
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
for _ in range(100):
depths.append(
transpile(
ghz,
backend,
layout_method='trivial' # Fixed layout mapped in circuit order
).depth()
)
plt.figure(figsize=(8, 6))
plt.hist(depths, align='left', color='#AC557C')
plt.xlabel('Depth', fontsize=14)
plt.ylabel('Counts', fontsize=14);
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the svd.py module.
"""
from unittest import TestCase
import numpy as np
from qiskit import QuantumCircuit
from qclib.state_preparation.svd import SVDInitialize
from qclib.util import get_state
# pylint: disable=missing-function-docstring
# pylint: disable=missing-class-docstring
class TestSVDInitialize(TestCase):
def _test_initialize(self, n_qubits):
state_vector = np.random.rand(2**n_qubits) + np.random.rand(2**n_qubits) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
circuit = QuantumCircuit(n_qubits)
SVDInitialize.initialize(circuit, state_vector)
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
def test_initialize_6(self):
self._test_initialize(6)
def test_initialize_5(self):
self._test_initialize(5)
|
https://github.com/HypsoHypso/QuantumComputingScripts
|
HypsoHypso
|
##############################################################
# Imports #
##############################################################
# %matplotlib inline ### to be enabled on qiskit notebook
import qiskit
from qiskit import (
IBMQ,
ClassicalRegister,
QuantumCircuit,
QuantumRegister,
QuantumCircuit,
execute,
Aer,
)
from qiskit.visualization import plot_histogram
##############################################################
# Circuit #
##############################################################
circuit = QuantumCircuit(2, 2) # 2 quantum bits and 2 classical bits
circuit.h(0) # Hadamard Gate
circuit.cx(0, 1) # CNOT Gate
circuit.measure([0, 1], [0, 1]) # Measurement
circuit.draw()
print(circuit)
# circuit.draw(output="mpl", filename="circuit.png") # to be enabled on qiskit notebook
##############################################################
# Second Section : #
# Execution on a quantum simulator #
# Perfectly quantum results #
# Maximum entanglement #
##############################################################
simulator = Aer.get_backend("qasm_simulator") # Setting up the simulator
job = execute(circuit, simulator, shots=1000) # Runs on 1000 trials
result = job.result() # Get the result
counts = result.get_counts(circuit) # Get the result
print("\nResults :", counts)
plot_histogram(counts)
for qubit, percentage in counts.items():
percentage *= 0.1
print(f"Qubit : {qubit} => Percentage : {round(percentage, 3)}%")
print(("Non-maximal entanglement", "Maximum entanglement")[counts.get("01") == counts.get("10")])
##############################################################
# Third Section : #
# Execution on a real quantum computer #
# Only executable on IBM Quantum Lab #
# Some result errors #
##############################################################
provider = IBMQ.get_provider(group="open")
device = provider.get_backend(
"""YOUR CHOSEN QUANTUM COMPUTER NAME"""
) # Declaration of a quantum computer located at a certain place
job_exp = execute(circuit, device, shots=1024) # Runs on 1024 trials
result_exp = job_exp.result() # Get the result
counts_exp = result_exp.get_counts(circuit) # Get the result (qubits, percentage)
print("\nExperimental Results :", counts_exp)
plot_histogram(counts_exp)
for qubit, percentage in counts_exp.items():
percentage *= 0.1
print(f"Qubit : {qubit} => Percentage : {round(percentage, 3)}%")
print(("Non-maximal entanglement", "Maximum entanglement")[counts_exp.get("01") == counts_exp.get("10")])
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
import time
import numpy as np
import qiskit
from qiskit.opflow import X,Z,I
from qiskit.opflow.state_fns import StateFn, CircuitStateFn
from qiskit.providers.aer import StatevectorSimulator, AerSimulator
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA
import matplotlib.pyplot as plt
from scipy import sparse
import scipy.sparse.linalg.eigen.arpack as arp
from modules.utils import *
from tenpy.networks.mps import MPS
from tenpy.models.hubbard import BoseHubbardChain
from tenpy.algorithms import dmrg
from tenpy.linalg import np_conserved
def DMRG_EBH(L, V, t_list, chi_max=30, bc_MPS='infinite'):
model_params = dict(n_max=1, filling=0.5, bc_MPS=bc_MPS, t=t_list,
L=L, V=V, mu=0, conserve='N', verbose=0)
M = BoseHubbardChain(model_params)
vector=[]
for i in range(M.lat.N_sites):
if i%2:
vector.append(1)
else:
vector.append(0)
psi = MPS.from_product_state(M.lat.mps_sites(), vector, bc=M.lat.bc_MPS)
dmrg_params = {
'mixer': True,
'trunc_params': {
'chi_max': chi_max,
},
'max_E_err': 1.e-16,
'verbose': 0
}
info = dmrg.run(psi, M, dmrg_params)
return info['E'], psi
chi = 50
V_list = np.logspace(-2,2,50)
deltat_list = np.linspace(-0.95,0.95,50)
L = 12
mu = 0
site = 0
psi_array = []
for deltat in deltat_list:
print('deltat', deltat)
t_list = np.ones(L-1)
for i in range(len(t_list)):
t_list[i] -= deltat*(-1)**i
psi_0 = []
for V in V_list:
print('V', V)
E0, psi0 = DMRG_EBH(L, V, t_list, chi_max=chi, bc_MPS='finite')
psi_0 = np.append(psi_0, psi0)
psi_array.append(psi_0)
np.save('data/BH_MPS_L%.0f_logV_50x50.npy' %L, psi_array)
wf_array = []
V_array = []
deltat_array = []
for i, deltat in enumerate(deltat_list):
for j, V in enumerate(V_list):
psi = psi_array[i][j]
wf = psi.get_theta(0,L).to_ndarray().reshape(-1)
wf_array.append(wf)
V_array.append(V)
deltat_array.append(deltat)
np.savez(f'data/wf_BH_L%.0f_logV_50x50.npz' %(L), deltat_array=deltat_array, V_array=V_array, wf_array = wf_array)
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.circuit import Gate
# Define no. of message qubits
n = 10
# Alice's end
alice_prepare = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
alice_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
circ = QuantumCircuit(n, n)
# Preparation
circ.reset(range(n))
for i in range(n):
if alice_prepare[i] == 1:
circ.x(i)
circ.barrier()
# Hadamard Transform
for i in range(n):
if alice_hadamard[i] == 1:
circ.h(i)
circ.barrier()
# Eavesdropper
circ.append(Gate(name="$Eve$", num_qubits=n, params=[]), range(n))
# Bob's end
bob_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
circ.barrier()
# Hadamard Transform
for i in range(n):
if bob_hadamard[i] == 1:
circ.h(i)
circ.barrier()
# Measurement
circ.measure(range(n), range(n))
circ.draw('mpl', reverse_bits=True, scale=0.45)
# Alice's end
alice_prepare = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
alice_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
circ = QuantumCircuit(n, n)
# Preparation
circ.reset(range(n))
for i in range(n):
if alice_prepare[i] == 1:
circ.x(i)
circ.barrier()
# Hadamard Transform
for i in range(n):
if alice_hadamard[i] == 1:
circ.h(i)
circ.barrier()
# Bob's end
bob_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
# Hadamard Transform
for i in range(n):
if bob_hadamard[i] == 1:
circ.h(i)
circ.barrier()
# Measurement
circ.measure(range(n), range(n))
circ.draw('mpl', reverse_bits=True, scale=0.45)
# Execute Circuit
backend = Aer.get_backend('qasm_simulator')
job = execute(circ, backend, shots=1)
counts = job.result().get_counts(circ)
bob_measure = list(counts.keys())[0][::-1]
# Print Data
print("".join(["Alice Prepared: ","".join([str(i) for i in alice_prepare])]))
print("".join(["Alice H Transforms: ","".join([str(i) for i in alice_hadamard])]))
print("".join(["Bob H Transforms: ","".join([str(i) for i in bob_hadamard])]))
print("".join(["Bob Measurements: ", bob_measure]))
# Extract Key
alice_key = []
bob_key = []
for i in range(n):
if alice_hadamard[i]==bob_hadamard[i]:
alice_key.append(int(alice_prepare[i]))
bob_key.append(int(bob_measure[i]))
# Print Keys
print("".join(["Alice extracts key as: ","".join([str(i) for i in alice_key])]))
print("".join(["Bob extracts key as: ","".join([str(i) for i in bob_key])]))
# Alice's end
alice_prepare = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
alice_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
circ = QuantumCircuit(n, 2*n)
# Preparation
circ.reset(range(n))
for i in range(n):
if alice_prepare[i] == 1:
circ.x(i)
circ.barrier()
# Hadamard Transform
for i in range(n):
if alice_hadamard[i] == 1:
circ.h(i)
circ.barrier()
# Eavesdropper
circ.measure(range(n), range(n))
# Bob's end
bob_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5])
circ.barrier()
# Hadamard Transform
for i in range(n):
if bob_hadamard[i] == 1:
circ.h(i)
circ.barrier()
# Measurement
circ.measure(range(n), range(n,2*n))
circ.draw('mpl', reverse_bits=True, scale=0.45)
# Execute Circuit
backend = Aer.get_backend('qasm_simulator')
job = execute(circ, backend, shots=1)
counts = job.result().get_counts(circ)
measure_data = list(counts.keys())[0][::-1]
eve_measure = measure_data[0:n]
bob_measure = measure_data[n:2*n]
# Print Data
print("".join(["Alice Prepared: ","".join([str(i) for i in alice_prepare])]))
print("".join(["Alice H Transforms: ","".join([str(i) for i in alice_hadamard])]))
print("".join(["Eve Measurements: ", eve_measure]))
print("".join(["Bob H Transforms: ","".join([str(i) for i in bob_hadamard])]))
print("".join(["Bob Measurements: ", bob_measure]))
# Extract Key
alice_key = []
bob_key = []
for i in range(n):
if alice_hadamard[i]==bob_hadamard[i]:
alice_key.append(int(alice_prepare[i]))
bob_key.append(int(bob_measure[i]))
# Print Keys
print("".join(["Alice extracts key as: ","".join([str(i) for i in alice_key])]))
print("".join(["Bob extracts key as: ","".join([str(i) for i in bob_key])]))
|
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import json
from typing import Any, Callable, Optional, Tuple, Union
from urllib.parse import urljoin
from qiskit import QuantumCircuit, execute
from qiskit.providers import JobStatus
from qiskit.providers.ibmq.job import IBMQJob
from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint
from .exercises import get_question_id
from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate
def _circuit_criteria(
circuit: QuantumCircuit,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[int], Optional[int]]:
if max_qubits is not None and circuit.num_qubits > max_qubits:
print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.')
print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.')
return None, None
try:
if check_gates and not uses_multiqubit_gate(circuit):
print('Your circuit appears to not use any multi-quibit gates.')
print('Please review your circuit and try again.')
return None, None
cost = compute_cost(circuit)
if min_cost is not None and cost < min_cost:
print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n'
'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.')
return None, None
return circuit.num_qubits, cost
except Exception as err:
print(f'Unable to compute cost: {err}')
return None, None
def _circuit_grading(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
payload = None
server = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or '
'the grading servers are down right now.')
return None, None
else:
server = None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
payload = {
'answer': circuit_to_json(circuit)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _job_grading(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str):
print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}')
print(f'Please submit a job as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading '
'servers are down right now.')
return None, None
else:
server = None
job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id
if not job:
print('An invalid or non-existent job was specified.')
return None, None
job_status = job.status()
if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]:
print(f'Job did not successfully complete: {job_status.value}.')
return None, None
elif job_status is not JobStatus.DONE:
print(f'Job has not yet completed: {job_status.value}.')
print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.')
return None, None
header = job.result().header.to_dict()
if 'qc_cost' not in header:
if is_submit:
print('An unprepared answer was specified. '
'Please prepare() and grade() answer before submitting.')
else:
print('An unprepared answer was specified. Please prepare() answer before grading.')
return None, None
download_url, result_url = get_job_urls(job)
if not download_url or not result_url:
print('Unable to obtain job URLs')
return None, None
payload = {
'answer': json.dumps({
'download_url': download_url,
'result_url': result_url
})
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _number_grading(
answer: int,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(answer, int):
print(f'Expected a integer, but was given {type(answer)}')
print(f'Please provide a number as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server '
'or the grading servers are down right now.')
return None, None
else:
server = None
payload = {
'answer': str(answer)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def prepare_circuit(
circuit: QuantumCircuit,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit.')
return None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiment. Please wait...')
job = execute(
circuit,
qobj_header={
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def prepare_solver(
solver_func: Callable,
lab_id: str,
ex_id: str,
problem_set: Optional[Any] = None,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not callable(solver_func):
print(f'Expected a function, but was given {type(solver_func)}')
print(f'Please provide a function that returns a QuantumCircuit.')
return None
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading servers are down right now.')
return
endpoint = server + 'problem-set'
index, value = get_problem_set(lab_id, ex_id, endpoint)
print(f'Running {solver_func.__name__}...')
qc_1 = solver_func(problem_set)
_, cost = _circuit_criteria(
qc_1,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if value and index is not None and index >= 0 and cost is not None:
qc_2 = solver_func(value)
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiments. Please wait...')
job = execute(
[qc_1, qc_2],
qobj_header={
'qc_index': [None, index],
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def grade_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, server = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=False,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_job(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str
) -> bool:
payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def submit_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, _ = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=True,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_job(
job_or_id: IBMQJob,
lab_id: str,
ex_id: str,
) -> bool:
payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def get_problem_set(
lab_id: str, ex_id: str, endpoint: str
) -> Tuple[Optional[int], Optional[Any]]:
problem_set_response = None
try:
payload = {'question_id': get_question_id(lab_id, ex_id)}
problem_set_response = send_request(endpoint, query=payload, method='GET')
except Exception as err:
print('Unable to obtain the problem set')
if problem_set_response:
status = problem_set_response.get('status')
if status == 'valid':
try:
index = problem_set_response.get('index')
value = json.loads(problem_set_response.get('value'))
return index, value
except Exception as err:
print(f'Problem set could not be processed: {err}')
else:
cause = problem_set_response.get('cause')
print(f'Problem set failed: {cause}')
return None, None
def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool:
try:
answer_response = send_request(endpoint, body=payload)
status = answer_response.get('status', None)
cause = answer_response.get('cause', None)
score = cost if cost else answer_response.get('score', None)
handle_grade_response(status, score=score, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def submit_answer(payload: dict) -> bool:
try:
access_token = get_access_token()
baseurl = get_submission_endpoint()
endpoint = urljoin(baseurl, './challenges/answers')
submit_response = send_request(
endpoint,
body=payload,
query={'access_token': access_token}
)
status = submit_response.get('status', None)
if status is None:
status = submit_response.get('valid', None)
cause = submit_response.get('cause', None)
handle_submit_response(status, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def handle_grade_response(
status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None
) -> None:
if status == 'valid':
print('\nCongratulations 🎉! Your answer is correct.')
if score is not None:
print(f'Your score is {score}.')
elif status == 'invalid':
print(f'\nOops 😕! {cause}')
print('Please review your answer and try again.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete then try again.')
else:
print(f'Failed: {cause}')
print('Unable to grade your answer.')
def handle_submit_response(
status: Union[str, bool], cause: Optional[str] = None
) -> None:
if status == 'valid' or status is True:
print('\nSuccess 🎉! Your answer has been submitted.')
elif status == 'invalid' or status is False:
print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}')
print('Make sure your answer is correct and successfully graded before submitting.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete, grade it, and then try to submit again.')
else:
print(f'Failed: {cause}')
print('Unable to submit your answer at this time.')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
ghz.draw(output='mpl')
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit_chemistry import FermionicOperator, QMolecule
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit_aqua.components.optimizers import COBYLA
from qiskit_aqua import Operator
from qiskit_aqua.algorithms import VQE, ExactEigensolver
from qiskit import Aer
from scipy import linalg as la
import numpy as np
import yaml as yml
from yaml import SafeLoader as Loader
import os
from dask.distributed import Client, LocalCluster
import dask
import Load_Hamiltonians as lh
#Define functions that can be used in parallel algorithm
def read_variables(root_dir, file1):
#print('Root directory\n',root_dir)
#print('The file: \n', file1)
Ham_data_file = str(os.path.join(root_dir, file1[0]))
try:
doc_nw = open(Ham_data_file, 'r')
dat = yml.load(doc_nw, Loader)
finally:
doc_nw.close()
# Import all the data from a yaml file
print('Getting data')
#Importing the integrals
one_e = dat['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values']
two_e = dat['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values']
num_spatial_orbitals = dat['integral_sets'][0]['n_orbitals']
coulomb_energy = dat['integral_sets'][0]['coulomb_repulsion']['value']
num_orbitals = 2 * num_spatial_orbitals
num_particles = dat['integral_sets'][0]['n_electrons']
d = 2 * dat['integral_sets'][0]['geometry']['atoms'][1]['coords'][2]
print('Bond distance is {}'.format(d))
if map_type == 'parity':
# For two-qubit reduction
num_qubits = num_orbitals - 2
else:
num_qubits = num_orbitals
return num_spatial_orbitals, num_orbitals, num_particles, num_qubits, d, coulomb_energy, one_e, two_e
def get_molecular_qubit_operator(one_ints, two_ints, n_orbitals, thresh, qubit_map):
# Getting spatial integrals and spin integrals to construct Hamiltonian
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_ints,
two_ints,
n_orbitals)
h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals, two_electron_spatial_integrals,
n_orbitals, thresh)
# Constructing the fermion operator and qubit operator from integrals data
fop = FermionicOperator(h1, h2)
qop_paulis = fop.mapping(qubit_map)
return qop_paulis
def run_vqe(pauli_operator, num_orbitals, num_particles, num_qubits, coulomb_energy, mapping, backend):
var_energy = 0
#Get Variational form and intial state
initial_state = HartreeFock(num_qubits, num_orbitals, num_particles, mapping, two_qubit_reduction=False)
var_op = UCCSD(num_qubits, 1, num_orbitals, num_particles, active_occupied=None, active_unoccupied=None, initial_state=initial_state, qubit_mapping=mapping)
######################## VQE RESULT ###############################
# setup a classical optimizer for VQE
max_eval = 200
optimizer = COBYLA(maxiter=max_eval, disp=True, tol=1e-3)
print('Doing VQE')
algorithm = VQE(pauli_operator, var_op, optimizer,'paulis', initial_point=None, )
result = algorithm.run(backend)
var_energy = result['energy'] + coulomb_energy
# vqe_params = result['opt_params']
return var_energy
def run_exact(pauli_operator, coulomb_energy):
exact_eigensolver = ExactEigensolver(pauli_operator, k=1)
ret = exact_eigensolver.run()
print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real))
print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + coulomb_energy))
ed_energy = ret['eigvals'][0].real + coulomb_energy
return ed_energy
##Carefully upgrade terra to see if qasm/state-vector simulator perform quicker.##
#################### WALK ROOT DIR ############################
#U
root_dir = '/Users/mmetcalf/Dropbox/Quantum Embedding/Codes/Lithium_Downfolding/Qiskit Chem/HamiltonianDownfolding_w_IBM/IntegralData/vqe-data-master/Li2_cc-pVTZ/4_ORBITALS/'
data_file_list = []
for dirName, subdirList, fileList in os.walk(root_dir):
print('Found directory: %s' % dirName)
for fname in sorted(fileList):
if fname.endswith('.yaml'):
data_file_list.append(fname)
############# Output Files to Plot stuff ###############
print(data_file_list)
Fout = open('Mekena_OutputData.dat',"w")
###########################################################
#Variables that can be assigned outside of Loop
map_type = str('jordan_wigner')
truncation_threshold = 0.01
################# IBM BACKEND #####################
backend1 = Aer.get_backend('statevector_simulator')
###################################################
@dask.delayed
def final(root_dir, file1):
#print('Starting Loop')
spatial_orbitals, spin_orbitals, particle_num, qubits_num, dist, nuclear_energy, one_electron_import, two_electron_import = read_variables(
root_dir, file1)
#print('Have variables')
qop = get_molecular_qubit_operator(one_electron_import, two_electron_import, spatial_orbitals, truncation_threshold,
map_type)
#print('Have qubit operator')
# vqe_energy = run_vqe(qop, spin_orbitals, particle_num, qubits_num, nuclear_energy, map_type, backend1)
vqe_energy = 0
exact_energy = run_exact(qop, nuclear_energy)
#print('Obtained the energy')
my_info = [dist, exact_energy, vqe_energy]
#print('info: ',my_info)
return my_info
# print(output_data)
Fout.close()
if __name__ == "__main__":
computations = []
cluster = LocalCluster()
client = Client(cluster, asyncronous=True)
for file1 in zip(data_file_list):
computations.append(final(root_dir, file1))
# final(root_dir, file1)
# my_info_to_str = " ".join(str(e) for e in final_energies)
# Fout.write(my_info_to_str + "\n")
output_data = dask.compute(*computations, scheduler='distributed')
print(output_data)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qiskit-community/qiskit-quantinuum-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# Copyright 2019-2020 Quantinuum, Intl. (www.quantinuum.com)
#
# 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.
# pylint: disable=arguments-differ
"""QuantinuumJob module
This module is used for creating asynchronous job objects for Quantinuum.
"""
import asyncio
import json
import logging
from collections import Counter
from datetime import datetime, timezone
from time import sleep
import nest_asyncio
import websockets
from qiskit.assembler.disassemble import disassemble
from qiskit.providers import JobV1, JobError
from qiskit.providers.jobstatus import JOB_FINAL_STATES, JobStatus
from qiskit import qobj as qobj_mod
from qiskit.result import Result
from .apiconstants import ApiJobStatus
from .api import QuantinuumClient
logger = logging.getLogger(__name__)
# Because Qiskit is often used with the Jupyter notebook who runs its own asyncio event loop
# (via Tornado), we must be able to apply our own event loop. This is something that is done
# in the IBMQ provider as well
nest_asyncio.apply()
class QuantinuumJob(JobV1):
"""Representation of a job that will be execute on a Quantinuum backend.
Represent the jobs that will be executed on Quantinuum devices. Jobs are
intended to be created calling ``run()`` on a particular backend.
Currently jobs that are created using a qobj can only have one experiment
in the qobj. If more that one experiment exists in the qobj only the first
experiment will be run and the rest will be ignored.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = QuantinuumJob(...)
job.submit()
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = QuantinuumJob(...)
job.submit()
try:
job_status = job.status() # It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = QuantinuumJob(...)
job.submit()
try:
job_id = job.id()
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something at the API level happens that prevent
Qiskit from determining the status of the job.
Note:
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
"""
def __init__(self, backend, job_id, api=None, circuits=None, job_config=None):
"""QuantinuumJob init function.
We can instantiate jobs from two sources: A circuit, and an already
submitted job returned by the API servers.
Args:
backend (QuantinuumBackend): The backend instance used to run this job.
job_id (str or None): The job ID of an already submitted job.
Pass `None` if you are creating a new job.
api (QuantinuumClient): Quantinuum api client.
circuits (list): A list of quantum circuit objects to run. Can also
be a ``QasmQobj`` object, but this is deprecated (and won't raise a
warning (since it's raised by ``backend.run()``). See notes below
job_config (dict): A dictionary for the job configuration options
Notes:
It is mandatory to pass either ``circuits`` or ``job_id``. Passing a ``circuits``
will ignore ``job_id`` and will create an instance to be submitted to the
API server for job creation. Passing only a `job_id` will create an instance
representing an already-created job retrieved from the API server.
"""
super().__init__(backend, job_id)
if api:
self._api = api
else:
self._api = QuantinuumClient(backend.provider().credentials)
self._creation_date = datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()
# Properties used for caching.
self._cancelled = False
self._api_error_msg = None
self._result = None
self._job_ids = []
self._experiment_results = []
self._qobj_payload = {}
self._circuits_job = False
if circuits:
if isinstance(circuits, qobj_mod.QasmQobj):
self._qobj_payload = circuits.to_dict()
# Extract individual experiments
# if we want user qobj headers, the third argument contains it
self._experiments, self._job_config, _ = disassemble(circuits)
self._status = JobStatus.INITIALIZING
else:
self._experiments = circuits
self._job_config = job_config
self._circuits_job = True
else:
self._status = JobStatus.INITIALIZING
self._job_ids.append(job_id)
self._job_config = {}
def submit(self):
"""Submit the job to the backend."""
backend_name = self.backend().name()
for exp in self._experiments:
submit_info = self._api.job_submit(backend_name, self._job_config, exp.qasm())
# Error in job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
# Don't continue
return
self._job_ids.append(submit_info['job'])
# Take the last submitted job's info
self._creation_date = submit_info.get('submit-date')
self._status = submit_info.get('status')
self._job_id = submit_info.get('job')
def result(self, timeout=300):
"""Return the result of the job.
Args:
timeout (float): number of seconds to wait for job
Returns:
qiskit.Result: Result object
Raises:
JobError: if attempted to recover a result on a failed job.
Notes:
Currently when calling get_counts() on a result returned by a Quantinuum
backend, since Quantinuum backends currently support only running one
experiment per job, do not supply an argument to the get_counts() function.
Doing so may raise an exception.
"""
if self._result:
return self._result
# Wait for results sequentially
for job_id in self._job_ids:
self._experiment_results.append(
asyncio.get_event_loop().run_until_complete(self._get_status(job_id, timeout))
)
# Process results
self._result = self._process_results()
if not (self._status is JobStatus.DONE or self._status is JobStatus.CANCELLED):
raise JobError('Invalid job state. The job should be DONE or CANCELLED but '
'it is {}'.format(str(self._status)))
if not self._result:
raise JobError('Server did not return result')
return self._result
def cancel(self):
"""Attempt to cancel job."""
pass
async def _get_status(self, job_id, timeout=300):
"""Query the API to update the status.
Returns:
qiskit.providers.JobStatus: The api response including the job status
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
if job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
api_response = self._api.job_status(job_id)
if 'websocket' in api_response:
task_token = api_response['websocket']['task_token']
execution_arn = api_response['websocket']['executionArn']
credentials = self.backend().provider().credentials
websocket_uri = credentials.url.replace('https://', 'wss://ws.')
async with websockets.connect(
websocket_uri, extra_headers={
'Authorization': credentials.access_token}) as websocket:
body = {
"action": "OpenConnection",
"task_token": task_token,
"executionArn": execution_arn
}
await websocket.send(json.dumps(body))
api_response = await asyncio.wait_for(websocket.recv(), timeout=timeout)
api_response = json.loads(api_response)
else:
logger.warning('Websockets via proxy not supported. Falling-back to polling.')
residual_delay = timeout/1000 # convert us -> s
request_delay = min(1.0, residual_delay)
while api_response['status'] not in ['failed', 'completed', 'canceled']:
sleep(request_delay)
api_response = self._api.job_status(job_id)
residual_delay = residual_delay - request_delay
if residual_delay <= 0:
# break if we have exceeded timeout
break
# Max-out at 10 second delay
request_delay = min(min(request_delay*1.5, 10), residual_delay)
except Exception as err:
raise JobError(str(err))
return api_response
def status(self, timeout=300):
"""Query the API to update the status.
Returns:
qiskit.providers.JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Wait for results sequentially
for job_id in self._job_ids:
self._experiment_results.append(
asyncio.get_event_loop().run_until_complete(self._get_status(job_id, timeout))
)
# Process results
self._result = self._process_results()
return self._status
def error_message(self):
"""Provide details about the reason of failure.
Returns:
str: An error report if the job errored or ``None`` otherwise.
"""
for job_id in self._job_ids:
if self.status(job_id) is not JobStatus.ERROR:
return None
if not self._api_error_msg:
self._api_error_msg = 'An unknown error occurred.'
return self._api_error_msg
def _process_results(self):
"""Convert Quantinuum job result to qiskit.Result"""
results = []
self._status = JobStatus.DONE
for i, res_resp in enumerate(self._experiment_results):
status = res_resp.get('status', 'failed')
if status == 'failed':
self._status = JobStatus.ERROR
res = res_resp['results']
counts = dict(Counter(hex(int("".join(r), 2)) for r in [*zip(*list(res.values()))]))
experiment_result = {
'shots': self._job_config.get('shots', 1),
'success': ApiJobStatus(status) is ApiJobStatus.COMPLETED,
'data': {'counts': counts},
'job_id': self._job_ids[i]
}
if self._circuits_job:
if self._experiments[i].metadata is None:
metadata = {}
else:
metadata = self._experiments[i].metadata
experiment_result['header'] = metadata
else:
experiment_result['header'] = self._qobj_payload[
'experiments'][i]['header'] if self._qobj_payload else {}
results.append(experiment_result)
result = {
'success': self._status is JobStatus.DONE,
'job_id': self._job_id,
'results': results,
'backend_name': self._backend.name(),
'backend_version': self._backend.status().backend_version,
'qobj_id': self._job_id
}
return Result.from_dict(result)
def creation_date(self):
"""Return creation date."""
return self._creation_date
def job_ids(self):
""" Return all the job_ids associated with this experiment """
return self._job_ids
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.measure(0,0)
qc.x(0).c_if(0, 0)
qc.draw(output='mpl')
from qiskit import QuantumRegister, ClassicalRegister
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
qc = QuantumCircuit(q, c)
qc.h([0, 1, 2])
qc.barrier()
qc.measure(q, c)
qc.draw('mpl')
print(bin(3))
print(bin(7))
qc.x(2).c_if(c, 3) # for the 011 case
qc.x(2).c_if(c, 7) # for the 111 case
qc.draw(output='mpl')
nq = 2
m = 2
q = QuantumRegister(nq, 'q')
c = ClassicalRegister(m, 'c')
qc_S = QuantumCircuit(q,c)
qc_S.h(0)
qc_S.x(1)
qc_S.draw('mpl')
from math import pi
cu_circ = QuantumCircuit(2)
cu_circ.cp(pi/2, 0, 1)
cu_circ.draw('mpl')
for _ in range(2 ** (m - 1)):
qc_S.cp(pi/2, 0, 1)
qc_S.draw('mpl')
def x_measurement(qc, qubit, cbit):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'"""
qc.h(qubit)
qc.measure(qubit, cbit)
x_measurement(qc_S, q[0], c[0])
qc_S.draw('mpl')
qc_S.reset(0)
qc_S.h(0)
qc_S.draw('mpl')
qc_S.p(-pi/2, 0).c_if(c, 1)
qc_S.draw('mpl')
## 2^t c-U operations (with t=m-2)
for _ in range(2 ** (m - 2)):
qc_S.cp(pi/2, 0, 1)
x_measurement(qc_S, q[0], c[1])
qc_S.draw('mpl')
import matplotlib.pyplot as plt
from qiskit.tools.visualization import plot_histogram
from qiskit_aer.primitives import Sampler
sampler = Sampler()
job = sampler.run(qc_S)
result = job.result()
dist0 = result.quasi_dists[0]
key_new = [str(key/2**m) for key in list(dist0.keys())]
dist1 = dict(zip(key_new, dist0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(dist0, ax=ax[0])
plot_histogram(dist1, ax=ax[1])
plt.tight_layout()
nq = 3 # number of qubits
m = 3 # number of classical bits
q = QuantumRegister(nq,'q')
c = ClassicalRegister(m,'c')
qc = QuantumCircuit(q,c)
qc.h(0)
qc.x([1, 2])
qc.draw('mpl')
cu_circ = QuantumCircuit(nq)
cu_circ.mcp(pi/4, [0, 1], 2)
cu_circ.draw('mpl')
for _ in range(2 ** (m - 1)):
qc.mcp(pi/4, [0, 1], 2)
qc.draw('mpl')
x_measurement(qc, q[0], c[0])
qc.draw('mpl')
qc.reset(0)
qc.h(0)
qc.draw('mpl')
qc.p(-pi/2, 0).c_if(c, 1)
qc.draw('mpl')
for _ in range(2 ** (m - 2)):
qc.mcp(pi/4, [0, 1], 2)
x_measurement(qc, q[0], c[1])
qc.draw('mpl')
# initialization of qubit q0
qc.reset(0)
qc.h(0)
# phase correction
qc.p(-pi/4, 0).c_if(c, 1)
qc.p(-pi/2, 0).c_if(c, 2)
qc.p(-3*pi/2, 0).c_if(c, 3)
# c-U operations
for _ in range(2 ** (m - 3)):
qc.mcp(pi/4, [0, 1], 2)
# X measurement
qc.h(0)
qc.measure(0, 2)
qc.draw('mpl')
result = sampler.run(qc).result()
dist0 = result.quasi_dists[0]
key_new = [str(key/2**m) for key in list(dist0.keys())]
dist1 = dict(zip(key_new, dist0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(dist0, ax=ax[0])
plot_histogram(dist1, ax=ax[1])
plt.tight_layout()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for generator of timeline drawer."""
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import generators, types, stylesheet
from qiskit.circuit import library, Delay
class TestGates(QiskitTestCase):
"""Tests for generator.gates."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1))[0]
self.u1 = types.ScheduledGate(
t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0
)
self.u3 = types.ScheduledGate(
t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0
)
self.delay = types.ScheduledGate(
t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0
)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_sched_gate_with_finite_duration(self):
"""Test test_gen_sched_gate generator with finite duration gate."""
drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 120])
self.assertListEqual(
list(drawing_obj.yvals),
[-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_meta = {
"name": "u3",
"label": "n/a",
"bits": str(self.qubit.register.name),
"t0": 100,
"duration": 20,
"unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]",
"parameters": "0, 0, 0",
}
self.assertDictEqual(ref_meta, drawing_obj.meta)
ref_styles = {
"zorder": self.formatter["layer.gate"],
"facecolor": self.formatter["color.gates"]["u3"],
"alpha": self.formatter["alpha.gate"],
"linewidth": self.formatter["line_width.gate"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_zero_duration(self):
"""Test test_gen_sched_gate generator with zero duration gate."""
drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"])
self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"])
ref_styles = {
"zorder": self.formatter["layer.frame_change"],
"color": self.formatter["color.gates"]["u1"],
"size": self.formatter["text_size.frame_change"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_delay(self):
"""Test test_gen_sched_gate generator with delay."""
drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value))
def test_gen_full_gate_name_with_finite_duration(self):
"""Test gen_full_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]")
ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format(
name=self.formatter["latex_symbol.gates"]["u3"]
)
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_zero_duration(self):
"""Test gen_full_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1(0.00)")
ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_delay(self):
"""Test gen_full_gate_name generator with delay."""
drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
def test_gen_short_gate_name_with_finite_duration(self):
"""Test gen_short_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3")
ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_zero_duration(self):
"""Test gen_short_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1")
ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_delay(self):
"""Test gen_short_gate_name generator with delay."""
drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
class TestTimeslot(QiskitTestCase):
"""Tests for generator.bits."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1))[0]
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_timeslot(self):
"""Test gen_timeslot generator."""
drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value))
self.assertListEqual(
list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
)
self.assertListEqual(
list(drawing_obj.yvals),
[
-0.5 * self.formatter["box_height.timeslot"],
0.5 * self.formatter["box_height.timeslot"],
],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_styles = {
"zorder": self.formatter["layer.timeslot"],
"alpha": self.formatter["alpha.timeslot"],
"linewidth": self.formatter["line_width.timeslot"],
"facecolor": self.formatter["color.timeslot"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_bit_name(self):
"""Test gen_bit_name generator."""
drawing_obj = generators.gen_bit_name(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, str(self.qubit.register.name))
ref_latex = r"{{\rm {register}}}_{{{index}}}".format(
register=self.qubit.register.prefix, index=self.qubit.index
)
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.bit_name"],
"color": self.formatter["color.bit_name"],
"size": self.formatter["text_size.bit_name"],
"va": "center",
"ha": "right",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestBarrier(QiskitTestCase):
"""Tests for generator.barriers."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(3))
self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_barrier(self):
"""Test gen_barrier generator."""
drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 100])
self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5])
self.assertListEqual(drawing_obj.bits, [self.qubits[1]])
ref_styles = {
"alpha": self.formatter["alpha.barrier"],
"zorder": self.formatter["layer.barrier"],
"linewidth": self.formatter["line_width.barrier"],
"linestyle": self.formatter["line_style.barrier"],
"color": self.formatter["color.barrier"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestGateLink(QiskitTestCase):
"""Tests for generator.gate_links."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(2))
self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def gen_bit_link(self):
"""Test gen_bit_link generator."""
drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, self.qubits)
ref_styles = {
"alpha": self.formatter["alpha.bit_link"],
"zorder": self.formatter["layer.bit_link"],
"linewidth": self.formatter["line_width.bit_link"],
"linestyle": self.formatter["line_style.bit_link"],
"color": self.formatter["color.gates"]["cx"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
|
https://github.com/pochangl/qiskit-experiment
|
pochangl
|
from argparse import ArgumentParser, Namespace, BooleanOptionalAction
from qiskit import QuantumCircuit as qc
from qiskit import QuantumRegister as qr
from qiskit import transpile
from qiskit_aer import AerSimulator
from qiskit.result import Counts
from matplotlib.pyplot import show, subplots, xticks, yticks
from math import pi, sqrt
from heapq import nlargest
class GroversAlgorithm:
def __init__(self,
title: str = "Grover's Algorithm",
n_qubits: int = 5,
search: set[int] = { 11, 9, 0, 3 },
shots: int = 1000,
fontsize: int = 10,
print: bool = False,
combine_states: bool = False) -> None:
"""
_summary_
Args:
title (str, optional): Window title. Defaults to "Grover's Algorithm".
n_qubits (int, optional): Number of qubits. Defaults to 5.
search (set[int], optional): Set of nonnegative integers to search for using Grover's algorithm. Defaults to { 11, 9, 0, 3 }.
shots (int, optional): Amount of times the algorithm is simulated. Defaults to 10000.
fontsize (int, optional): Histogram's font size. Defaults to 10.
print (bool, optional): Whether or not to print quantum circuit(s). Defaults to False.
combine_states (bool, optional): Whether to combine all non-winning states into 1 bar labeled "Others" or not. Defaults to False.
"""
# Parsing command line arguments
self._parser: ArgumentParser = ArgumentParser(description = "Run grover's algorithm via command line", add_help = False)
self._init_parser(title, n_qubits, search, shots, fontsize, print, combine_states)
self._args: Namespace = self._parser.parse_args()
# Set of nonnegative ints to search for
self.search: set[int] = set(self._args.search)
# Set of m N-qubit binary strings representing target state(s) (i.e. self.search in base 2)
self._targets: set[str] = { f"{s:0{self._args.n_qubits}b}" for s in self.search }
# N-qubit quantum register
self._qubits: qr = qr(self._args.n_qubits, "qubit")
def _print_circuit(self, circuit: qc, name: str) -> None:
"""Print quantum circuit.
Args:
circuit (qc): Quantum circuit to print.
name (str): Quantum circuit's name.
"""
print(f"\n{name}:\n{circuit}")
def _oracle(self, targets: set[str]) -> qc:
"""Mark target state(s) with negative phase.
Args:
targets (set[str]): N-qubit binary string(s) representing target state(s).
Returns:
qc: Quantum circuit representation of oracle.
"""
# Create N-qubit quantum circuit for oracle
oracle = qc(self._qubits, name = "Oracle")
for target in targets:
# Reverse target state since Qiskit uses little-endian for qubit ordering
target = target[::-1]
# Flip zero qubits in target
for i in range(self._args.n_qubits):
if target[i] == "0":
# Pauli-X gate
oracle.x(i)
# Simulate (N - 1)-control Z gate
# 1. Hadamard gate
oracle.h(self._args.n_qubits - 1)
# 2. (N - 1)-control Toffoli gate
oracle.mcx(list(range(self._args.n_qubits - 1)), self._args.n_qubits - 1)
# 3. Hadamard gate
oracle.h(self._args.n_qubits - 1)
# Flip back to original state
for i in range(self._args.n_qubits):
if target[i] == "0":
# Pauli-X gate
oracle.x(i)
# Display oracle, if applicable
if self._args.print: self._print_circuit(oracle, "ORACLE")
return oracle
def _diffuser(self) -> qc:
"""Amplify target state(s) amplitude, which decreases the amplitudes of other states
and increases the probability of getting the correct solution (i.e. target state(s)).
Returns:
qc: Quantum circuit representation of diffuser (i.e. Grover's diffusion operator).
"""
# Create N-qubit quantum circuit for diffuser
diffuser = qc(self._qubits, name = "Diffuser")
# Hadamard gate
diffuser.h(self._qubits)
# Oracle with all zero target state
diffuser.append(self._oracle({"0" * self._args.n_qubits}), list(range(self._args.n_qubits)))
# Hadamard gate
diffuser.h(self._qubits)
# Display diffuser, if applicable
if self._args.print: self._print_circuit(diffuser, "DIFFUSER")
return diffuser
def _grover(self) -> qc:
"""Create quantum circuit representation of Grover's algorithm,
which consists of 4 parts: (1) state preparation/initialization,
(2) oracle, (3) diffuser, and (4) measurement of resulting state.
Steps 2-3 are repeated an optimal number of times (i.e. Grover's
iterate) in order to maximize probability of success of Grover's algorithm.
Returns:
qc: Quantum circuit representation of Grover's algorithm.
"""
# Create N-qubit quantum circuit for Grover's algorithm
grover = qc(self._qubits, name = "Grover Circuit")
# Intialize qubits with Hadamard gate (i.e. uniform superposition)
grover.h(self._qubits)
# # Apply barrier to separate steps
grover.barrier()
# Apply oracle and diffuser (i.e. Grover operator) optimal number of times
for _ in range(int((pi / 4) * sqrt((2 ** self._args.n_qubits) / len(self._targets)))):
grover.append(self._oracle(self._targets), list(range(self._args.n_qubits)))
grover.append(self._diffuser(), list(range(self._args.n_qubits)))
# Measure all qubits once finished
grover.measure_all()
# Display grover circuit, if applicable
if self._args.print: self._print_circuit(grover, "GROVER CIRCUIT")
return grover
def _outcome(self, winners: list[str], counts: Counts) -> None:
"""Print top measurement(s) (state(s) with highest frequency)
and target state(s) in binary and decimal form, determine
if top measurement(s) equals target state(s), then print result.
Args:
winners (list[str]): State(s) (N-qubit binary string(s))
with highest probability of being measured.
counts (Counts): Each state and its respective frequency.
"""
print("WINNER(S):")
print(f"Binary = {winners}\nDecimal = {[ int(key, 2) for key in winners ]}\n")
print("TARGET(S):")
print(f"Binary = {self._targets}\nDecimal = {self.search}\n")
if not all(key in self._targets for key in winners): print("Target(s) not found...")
else:
winners_frequency, total = 0, 0
for value, frequency in counts.items():
if value in winners:
winners_frequency += frequency
total += frequency
print(f"Target(s) found with {winners_frequency / total:.2%} accuracy!")
def _show_histogram(self, histogram_data) -> None:
"""Print outcome and display histogram of simulation results.
Args:
data: Each state and its respective frequency.
"""
# State(s) with highest count and their frequencies
winners = { winner : histogram_data.get(winner) for winner in nlargest(len(self._targets), histogram_data, key = histogram_data.get) }
# Print outcome
self._outcome(list(winners.keys()), histogram_data)
# X-axis and y-axis value(s) for winners, respectively
winners_x_axis = [ str(winner) for winner in [*winners] ]
winners_y_axis = [ *winners.values() ]
# All other states (i.e. non-winners) and their frequencies
others = { state : frequency for state, frequency in histogram_data.items() if state not in winners }
# X-axis and y-axis value(s) for all other states, respectively
other_states_x_axis = "Others" if self._args.combine else [*others]
other_states_y_axis = [ sum([*others.values()]) ] if self._args.combine else [ *others.values() ]
# Create histogram for simulation results
figure, axes = subplots(num = "Grover's Algorithm — Results", layout = "constrained")
axes.bar(winners_x_axis, winners_y_axis, color = "green", label = "Target")
axes.bar(other_states_x_axis, other_states_y_axis, color = "red", label = "Non-target")
axes.legend(fontsize = self._args.fontsize)
axes.grid(axis = "y", ls = "dashed")
axes.set_axisbelow(True)
# Set histogram title, x-axis title, and y-axis title respectively
axes.set_title(f"Outcome of {self._args.shots} Simulations", fontsize = int(self._args.fontsize * 1.45))
axes.set_xlabel("States (Qubits)", fontsize = int(self._args.fontsize * 1.3))
axes.set_ylabel("Frequency", fontsize = int(self._args.fontsize * 1.3))
# Set font properties for x-axis and y-axis labels respectively
xticks(fontsize = self._args.fontsize, family = "monospace", rotation = 0 if self._args.combine else 70)
yticks(fontsize = self._args.fontsize, family = "monospace")
# Set properties for annotations displaying frequency above each bar
annotation = axes.annotate("",
xy = (0, 0),
xytext = (5, 5),
xycoords = "data",
textcoords = "offset pixels",
ha = "center",
va = "bottom",
family = "monospace",
weight = "bold",
fontsize = self._args.fontsize,
bbox = dict(facecolor = "white", alpha = 0.4, edgecolor = "None", pad = 0)
)
def _hover(event) -> None:
"""Display frequency above each bar upon hovering over it.
Args:
event: Matplotlib event.
"""
visibility = annotation.get_visible()
if event.inaxes == axes:
for bars in axes.containers:
for bar in bars:
cont, _ = bar.contains(event)
if cont:
x, y = bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height()
annotation.xy = (x, y)
annotation.set_text(y)
annotation.set_visible(True)
figure.canvas.draw_idle()
return
if visibility:
annotation.set_visible(False)
figure.canvas.draw_idle()
# Display histogram
id = figure.canvas.mpl_connect("motion_notify_event", _hover)
show()
figure.canvas.mpl_disconnect(id)
def run(self) -> None:
"""
Run Grover's algorithm simulation.
"""
# Simulate Grover's algorithm locally
backend = AerSimulator(method = "density_matrix")
# Generate optimized grover circuit for simulation
transpiled_circuit = transpile(self._grover(), backend, optimization_level = 2)
# Run Grover's algorithm simulation
job = backend.run(transpiled_circuit, shots = self._args.shots)
# Get simulation results
results = job.result()
# Get each state's histogram data (including frequency) from simulation results
data = results.get_counts()
# Display simulation results
self._show_histogram(data)
def _init_parser(self,
title: str,
n_qubits: int,
search: set[int],
shots: int,
fontsize: int,
print: bool,
combine_states: bool) -> None:
"""
Helper method to initialize command line argument parser.
Args:
title (str): Window title.
n_qubits (int): Number of qubits.
search (set[int]): Set of nonnegative integers to search for using Grover's algorithm.
shots (int): Amount of times the algorithm is simulated.
fontsize (int): Histogram's font size.
print (bool): Whether or not to print quantum circuit(s).
combine_states (bool): Whether to combine all non-winning states into 1 bar labeled "Others" or not.
"""
self._parser.add_argument("-H, --help",
action = "help",
help = "show this help message and exit")
self._parser.add_argument("-T, --title",
type = str,
default = title,
dest = "title",
metavar = "<title>",
help = f"window title (default: \"{title}\")")
self._parser.add_argument("-n, --n-qubits",
type = int,
default = n_qubits,
dest = "n_qubits",
metavar = "<n_qubits>",
help = f"number of qubits (default: {n_qubits})")
self._parser.add_argument("-s, --search",
default = search,
type = int,
nargs = "+",
dest = "search",
metavar = "<search>",
help = f"nonnegative integers to search for with Grover's algorithm (default: {search})")
self._parser.add_argument("-S, --shots",
type = int,
default = shots,
dest = "shots",
metavar = "<shots>",
help = f"amount of times the algorithm is simulated (default: {shots})")
self._parser.add_argument("-f, --font-size",
type = int,
default = fontsize,
dest = "fontsize",
metavar = "<font_size>",
help = f"histogram's font size (default: {fontsize})")
self._parser.add_argument("-p, --print",
action = BooleanOptionalAction,
type = bool,
default = print,
dest = "print",
help = f"whether or not to print quantum circuit(s) (default: {print})")
self._parser.add_argument("-c, --combine",
action = BooleanOptionalAction,
type = bool,
default = combine_states,
dest = "combine",
help = f"whether to combine all non-winning states into 1 bar labeled \"Others\" or not (default: {combine_states})")
if __name__ == "__main__":
GroversAlgorithm().run()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.draw('mpl')
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import Aer, QuantumCircuit, transpile
from qiskit.circuit.library import PhaseEstimation
qc= QuantumCircuit(3,3)
# dummy unitary circuit
unitary_circuit = QuantumCircuit(1)
unitary_circuit.h(0)
# QPE
qc.append(PhaseEstimation(2, unitary_circuit), list(range(3)))
qc.measure(list(range(3)), list(range(3)))
backend = Aer.get_backend('qasm_simulator')
qc_transpiled = transpile(qc, backend)
result = backend.run(qc, shots = 8192).result()
|
https://github.com/tuf65651/quantum-research
|
tuf65651
|
# %matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# import math
# Loading your IBM Q account(s)
# IBMQ.load_account()
backend = Aer.get_backend("qasm_simulator")
from ArithmaticFunctions import *
def convolute_shift_func(circuit, control_reg, acc_reg, power):
"""Implement bit shift.
@param circuit: QuantumCircuit containing operands
@param control_reg: QuantumRegister containing qubit that defines power (all operations conditional on this)
@param acc_reg: QuantumRegister containing integer to shift
@param power: int number of places to shift (if control_reg[power])"""
## NOTE: Power is the number of places to shift. Power 1 is controlled by
## control register's 2nd bit, which is control_reg[1]
## and refers to shift of 2^1, or shift one place
# Flip all qubits in accumulator to allow ripple carry
# for qubit in range(len(acc_reg)):
# circuit.x(acc_reg[qubit])
for target_bit in range(len(acc_reg) - 1):
# shift bit by correct number of places
# circuit.ccx(control_reg[power], acc_reg[target_bit], acc_reg[target_bit + power])
# Circuit will flip target bit before evaluating. Preempt that first flip.
circuit.cx(control_reg[power], acc_reg[target_bit])
# Flip next bit if carry occurs
for flipped_bit in range(target_bit, len(acc_reg) - 1):
## Carry occurs if target now 0 (if flip makes it 1).
circuit.cx(control_reg[power], acc_reg[flipped_bit])
circuit.ccx(control_reg[power], acc_reg[flipped_bit], acc_reg[flipped_bit + 1])
circuit.cx(control_reg[power], acc_reg[flipped_bit])
# Flip bit that's being shifted
# circuit.cx(control_reg[power], acc_reg[target_bit])
def ripple_carry_bits(circuit, control_bit, acc_reg, scratch_reg, start_shifting_at):
"""Continue a carry operation
This assumes that whatever simple op triggered the ripple has already occurred.
For example, if the ripple started with addition of 1 to the least significant bit,
manually flip and then call function.
@param circuit: QuantumCircuit containing operands
@param control_bit: single bit controling whether op begins.
@param acc_reg: QuantumRegister containing integer to shift
@param scratch_reg: Quantum registered in initial |0..0> state used to store carry result of each simple addition.
@param start_shifting_at: index in acc_reg of bit to shift
TESTING - Passed minimal test cases July 18 at 8:24am Pacific Time
"""
"""
NOTE: Power is the number of places to shift. Power 1 is controlled by
control register's 2nd bit, which is control_reg[1]
and refers to shift of 2^1, or shift one place
"""
circuit.ccx(control_bit, acc_reg[start_shifting_at], scratch_reg[start_shifting_at])
circuit.cx(control_bit, acc_reg[start_shifting_at])
# After flipping target, state |0> means we should have carried... =>
# before flipping target, state |1> means we should carry.
# Flip each bit, if it's 1, carry to the next bit, and flip it back.
for bit in range(start_shifting_at + 1, len(acc_reg) - 1):
circuit.ccx(acc_reg[bit], scratch_reg[bit - 1], scratch_reg[bit])
circuit.cx(scratch_reg[bit - 1], acc_reg[bit])
def c_ripple_subtract(circuit, control_bit, min_reg, scratch_reg, start_shifting_at):
"""Continue a subtract operation
@param circuit: QuantumCircuit containing operands
@param control_bit: single bit controling whether op begins.
@param min_reg: QuantumRegister containing integer to transform
@param scratch_reg: Quantum register in initial |0..0> state used to store carry result of each simple addition.
@param start_shifting_at: index in acc_reg of bit to shift
"""
circuit.x(min_reg[start_shifting_at])
circuit.ccx(min_reg[start_shifting_at], control_bit, scratch_reg[start_shifting_at])
circuit.x(min_reg[start_shifting_at])
# Check how deep the borrow goes. Flip a scratch bit for every borrow op.
for bit in range(start_shifting_at + 1, len(min_reg)):
circuit.x(min_reg[bit])
circuit.ccx(min_reg[bit], scratch_reg[bit - 1], scratch_reg[bit])
circuit.x(min_reg[bit])
# Perform every borrow indicated in scratch, and then flip targeted bit.
for bit in range(len(scratch_reg) - 2, -1, -1):
circuit.cx(scratch_reg[bit], min_reg[bit+1])
# Finally flip original target bit
circuit.x(min_reg[start_shifting_at])
def carry_op(circuit, a_reg, acc_reg, scratch_reg):
"""Used as 'CARRY' operator for circuit illustated in arxiv.org/quant-ph/9511018
@param circuit: QuantumCircuit
@param a_reg: QuantumRegister containing addend
@param acc_reg: QuantumRegister 'b' starts with addend and accumulates sum
@param scratch_reg: QuantumRegister holds carry bits at each step"""
for bit in range(len(a_reg)):
circuit.cx(a_reg[bit], acc_reg[bit])
circuit.x(acc_reg[bit])
circuit.cx(acc_reg[bit], scratch_reg[bit])
circuit.x(acc_reg[bit])
def add_to_b_in_place(circuit, a_reg, b_reg, scratch_reg):
"""|a > | b > => |a > |a+b >
TESTING - Passed minimal test cases July 18 at 8:24am Pacific Time
"""
for bit in range(len(a_reg)):
circuit.reset(scratch_reg)
ripple_carry_bits(
circuit=circuit,
control_bit=a_reg[bit],
acc_reg=b_reg,
scratch_reg=scratch_reg,
start_shifting_at=bit)
def sub_b_from_a_in_place(circuit, minnd_reg, subtrhnd_reg, scratch_reg):
"""Subtract subtrahend integer b from minuend integer a in register a
@param circuit: QuantumCircuit containing other parameters
@param minnd_reg: QuantumRegister transformed from minuend to difference
@param subtrhnd_reg: QuantumRegister containing subtrahend
@param scratch_reg: QuantumRegister in initial |0...0> state used as borrow flags
for each primitive op (final bit indicates negative difference)
"""
def bit_shift_left(circuit, register, places=1):
"""
TESTING - Passed minimal test cases July 21 at 2:30 Pacific Time
"""
# zero out all trailing bits
num_bits = len(register)
for rollover in range(num_bits - places, num_bits):
circuit.reset(register[rollover])
# swap every bit 'places' forward, with last bits wrapping around to beginning
for bit in range(num_bits - 1,places-1,-1):
circuit.swap(register[bit], register[bit - places])
def c_copy_register(circuit, control_bit, origin, dest):
"""sets contents of dest with contents of origin if control_bit
WARNING - perform a reset before use
"""
circuit.reset(dest)
for bit in range(len(dest)):
circuit.ccx(control_bit, origin[bit], dest[bit])
def multiply(circuit, multiplicand, multiplier, scratch_zero_check, scratch_carrier, prod_accumulator):
c_copy_register(circuit=circuit, control_bit=multiplier[0], origin=multiplicand, dest=prod_accumulator)
for bit in range(1, len(multiplier)):
# free up scratch space
circuit.reset(scratch_carrier)
circuit.reset(scratch_zero_check)
# shift multiplicand one space left, to match magnitude of current multiplier bit
bit_shift_left(circuit=circuit, register=multiplicand, places=1)
# copy multiplicand into scratch register only if multiplicand bit, else keep scratch register |0>
c_copy_register(circuit=circuit, control_bit=multiplier[bit], origin=multiplicand, dest=scratch_zero_check)
# add that scratch term (shifted multiplicand or zero) to accumulated product
add_to_b_in_place(circuit=circuit, a_reg=scratch_zero_check, b_reg=prod_accumulator, scratch_reg=scratch_carrier)
n_reg = QuantumRegister(3, 'n')
m_reg = QuantumRegister(3, 'm')
scratch_a = QuantumRegister(3, 'sca')
scratch_b = QuantumRegister(3, 'scb')
scratch_y = QuantumRegister(3, 'accm')
class_reg = ClassicalRegister(3, 'y')
qc = QuantumCircuit(n_reg, m_reg, scratch_a, scratch_b, scratch_y, class_reg)
# Register n set to 5
qc.x(n_reg[0])
qc.x(n_reg[1])
# qc.x(n_reg[2])
# Register m set to
# qc.x(m_reg[0])
qc.x(m_reg[1])
n_reg = QuantumRegister(3, 'n')
m_reg = QuantumRegister(2, 'm')
scratch_a = QuantumRegister(3, 'sca')
class_reg = ClassicalRegister(3, 'y')
backend = Aer.get_backend('qasm_simulator')
n_reg = QuantumRegister(3, 'n')
scratch_a = QuantumRegister(3, 'sca')
qc = QuantumCircuit(n_reg, m_reg, scratch_a, class_reg)
# Set control bits
qc.x(m_reg[1])
# 1 - 1 = 0
"""
PASSED July 29 10:58am Pacific Time
"""
qc.x(n_reg[0])
qc.barrier()
c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[1], scratch_reg=scratch_a, start_shifting_at=0)
qc.draw()
# 2 - 1 = 1
"""
PASSED July 29 10:58am Pacific Time
"""
qc.x(n_reg[1])
qc.barrier()
c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=0)
# qc.draw()
# 4 - 1 = 3
"""
PASSED July 29 10:58am Pacific Time
"""
qc.x(n_reg[2])
c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=0)
qc.draw()
# 6 - 1 = 5
"""
PASSED July 29 10:58am Pacific Time
"""
qc.x(n_reg[1])
qc.x(n_reg[2])
c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=n_reg[True], scratch_reg=scratch_a, start_shifting_at=0)
qc.draw()
# 5 - 1 = 4
"""
PASSED July 29 10:58am Pacific Time
"""
qc.x(n_reg[0])
qc.x(n_reg[2])
c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=0)
# c_draw()
# 5 - 2 = 3
"""
PASSED July 29 10:58am Pacific Time
"""
qc.x(n_reg[0])
qc.x(n_reg[2])
c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=1)
# qc.draw()
# 7 - 2 = 5
qc.x(n_reg[0])
qc.x(n_reg[1])
qc.x(n_reg[2])
c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=1)
qc.draw()
# 7 - 0 = 7
qc.x(n_reg[0])
qc.x(n_reg[1])
qc.x(n_reg[2])
qc.barrier()
c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[False], scratch_reg=scratch_a, start_shifting_at=1)
qc.draw()
# 1 - 2 = ?
qc.x(n_reg[0])
c_ripple_subtract(circuit=qc, min_reg=n_reg, control_bit=m_reg[True], scratch_reg=scratch_a, start_shifting_at=1)
# c_draw()
for bit in range(len(n_reg)):
qc.measure(n_reg[bit], class_reg[bit])
execute(qc, backend=backend, shots=1024).result().get_counts()
multiply(
circuit=qc,
multiplier=n_reg,
multiplicand=m_reg,
scratch_zero_check=scratch_b,
scratch_carrier=scratch_a,
prod_accumulator=scratch_y)
# add_to_b_in_place(circuit=qc, a_reg=n_reg, b_reg=m_reg, scratch_reg=scratch_a)
# bit_shift_left(circuit=qc, register=m_reg, places=1)
# ripple_carry_bits(circuit=qc, control_bit=n_reg[0],acc_reg=m_reg,scratch_reg=scratch_reg, start_shifting_at=0)
# bit_shift_left(circuit=qc, register=m_reg, places=1)
for index in range(len(m_reg)):
qc.measure(scratch_y[index], class_reg[index])
qc.draw()
qc_opt = transpile(qc, optimization_level=1, backend=backend)
qc_opt.draw()
simulate = execute(qc_opt, backend=backend, shots=1024).result()
simulate.get_counts()
qc.reset(n_reg[0])
print(max_memory_mb)
|
https://github.com/alejomonbar/Classification-Iris_using-Qutrits
|
alejomonbar
|
from qiskit import IBMQ
from qiskit import QuantumCircuit, transpile
from qiskit import schedule
from qiskit.pulse import DriveChannel, Waveform, Gaussian
from qiskit.circuit import Parameter, ParameterVector
from qiskit.tools import job_monitor
from qiskit import pulse
import numpy as np
import matplotlib.pyplot as plt
provider = IBMQ.load_account()
backend = provider.backend.ibmq_bogota
x_def = backend.defaults().instruction_schedule_map.get('x',qubits = [0]) # Default x gate from IBM
qubit = 0 # The qubit that we will use in Bogota
amp = 0.4 # Guessed amplitude of the transition between |1> and |2>
duration = 160 # Duration of the Gaussian pulse for the transition
spec_pulse = Gaussian(duration=duration, amp=amp, sigma=(duration//4)) # Pulse for the transition
measure = backend.defaults().instruction_schedule_map.get('measure',qubits = [qubit]) # Default mesurement gate
num_exp = 20# number of experiments which means the different frequencies
f01 = backend.defaults().qubit_freq_est[0] # Default frequency estimation of transition |0> to |1>
frequencies = f01 - np.linspace(0,0.4e9,num_exp) # Going from the f01 to f01 - 0.4GHz Guessing where the transition frequency is.
scheds = [] # variable to storage the different experiments
for f in frequencies: # iterating over the frequencies
with pulse.build() as Schedule:
with pulse.align_sequential():
pulse.call(x_def)
pulse.set_frequency(f, DriveChannel(qubit))
pulse.play(spec_pulse, DriveChannel(qubit))
pulse.call(measure)
scheds.append(Schedule)
shots = 1000 # Number of repetitions of the experiment (to obtain the probability)
job = backend.run(scheds, meas_level=1, meas_return="single", shots=shots) # What we send to ibmq_bogota
# meas_level = 1 means that we want to obtain the points in an I-Q diagram
job_monitor(job) # To visualize where in the queue is our experiment
cal_freq = job.result() # results from the job
output = []
for i in range(num_exp):
output.append(cal_freq.get_memory(i))# each memory contains one of the 20 experiments with complex numbers the real and imaginary components represent the I-Q diagram
output = np.array(output)
output = np.squeeze(output)[:,:,0]
mean = np.mean(output, axis=1) # taken the mean over the 1000 shots
f12 = frequencies[np.argmax(mean.imag)] # The frequency will be the maximum amplitude for the imaginary term IN THIS CASE
plt.figure()
plt.scatter(frequencies, mean.imag)
plt.axvline(f12, linestyle="--", color="red")
plt.xlabel("frequency", fontsize=14)
plt.ylabel("Amplitude [a.u]", fontsize=14)
plt.grid()
plt.title(f"Frequency calibrated: {np.round(f12/1e9,3)} GHz")
scheds = []
amplitudes = np.linspace(0,0.4,25) # Guessing the range of amplitudes that generates a transition between 1 and 2
for amp in amplitudes:
spec_pulse = Gaussian(duration=duration, amp=amp, sigma=(duration//4))
with pulse.build() as Schedule:
with pulse.align_sequential():
pulse.call(x_def)
pulse.set_frequency(f12, DriveChannel(qubit))
pulse.play(spec_pulse, DriveChannel(qubit))
pulse.call(measure)
scheds.append(Schedule)
scheds[-1].draw()
shots = 1000
job_amp = backend.run(scheds, meas_level=1, meas_return="single", shots=shots)
job_monitor(job_amp)
amp_cal = job_amp.result()
amps_12 = []
for i in range(len(amplitudes)):
amps_12.append(amp_cal.get_memory(i))
amps_12 = np.array(amps_12)
amps_12 = np.squeeze(amps_12)[:,:,0]
amps_12_mean = np.mean(amps_12, axis=1)
amp_12 = amplitudes[np.argmax(amps_12_mean.imag)]
plt.figure()
plt.plot(amplitudes,amps_12_mean.imag, "o", label = "Exp")
plt.axvline(amp_12, color="red", linestyle="--", label="Amp 12")
plt.title(f"The amplitude for the transition 1-2 is :{round(amp_12,3)}", fontsize=14)
plt.xlabel("Pulse Amplitude [a.u]")
plt.ylabel("Amplitude [a.u]")
x01 = backend.defaults().instruction_schedule_map.get('x', qubits = [0]) # Gate X to rotate in the |0> |1> basis
f01 = backend.defaults().qubit_freq_est[0]
spec_pulse = Gaussian(duration=duration, amp=amp_12, sigma=(duration//4))
with pulse.build() as pulse12:
with pulse.align_sequential():
pulse.set_frequency(f12, DriveChannel(qubit))
pulse.play(spec_pulse, DriveChannel(qubit))
pulse.set_frequency(f01, DriveChannel(qubit))
x12 = pulse12
x02 = pulse.Schedule()
x02 += x01
x02 += x12
# |0>
zero = pulse.Schedule()
zero += measure
# |1>
one = pulse.Schedule()
one += x01
one |= measure << one.duration
# |2>
two = pulse.Schedule()
two += x02
two |= measure << two.duration
x02.draw()
classExp = backend.run([zero, one, two], meas_level=1, meas_return="single", shots=shots)
job_monitor(classExp)
resClass = classExp.result()
result = []
for i in range(3):
result.append([resClass.get_memory(i).real, resClass.get_memory(i).imag])
result = np.squeeze(np.array(result)).T[0]
for i in range(3):
plt.scatter(result[:,0,i], result[:,1,i], label = f"{i}", alpha = 0.5)
plt.legend()
from sklearn.cluster import KMeans
X = np.concatenate((result[:,:,0], result[:,:,1],result[:,:,2]))
kmeans = KMeans(n_clusters=3).fit(X)
centers = kmeans.cluster_centers_
plt.figure()
for i in range(3):
plt.scatter(result[:,0,i], result[:,1,i], label = f"{i}", alpha = 0.5)
plt.text(centers[i][0], centers[i][1], f"{i}", fontsize=16)
plt.legend()
labels = [1,0,2]
fig, ax = plt.subplots(1,3, figsize=(18,5))
count = []
for j in range(3):
case = 2
pred0 = kmeans.predict(result[:,:,j])
for i in range(3):
pred = result[pred0==labels[i],:,j]
ax[j].scatter(pred[:,0],pred[:,1], label=f"{i}")
ax[j].set_xlabel("I", fontsize=16)
ax[j].set_ylabel("Q", fontsize=16)
ax[j].legend()
count.append([np.sum(pred0==labels[i])/len(pred0) for i in range(3)])
count
from sklearn import datasets
iris_dataset = datasets.load_iris(return_X_y=True)
data = iris_dataset[0]
minD = np.min(data, axis=0)
maxD = np.max(data, axis=0)
index = np.random.shuffle(np.arange(len(data)))
inputNorm = (1.8 * (data - minD) / (maxD - minD) - 0.9) * np.pi # for the inputs to be between 0.1π and 0.9π
inputNorm = inputNorm[index,:][0]
target = iris_dataset[1][index][0]
def gate_12(param):
with pulse.build() as sched:
with pulse.align_sequential():
pulse.set_frequency(f12, DriveChannel(qubit))
pulse.play(Gaussian(duration=duration, amp=param*amp_12/np.pi, sigma=(duration//4)), DriveChannel(qubit))
pulse.set_frequency(f01, DriveChannel(qubit))
return sched
def u3(theta, phi, lambda_):
qc = QuantumCircuit(1)
qc.u(theta,phi,lambda_, qubit)
return schedule(transpile(qc,backend), backend)
one1 = u3(np.pi,-np.pi/2,np.pi/2)
one = one1
one |= measure << one.duration
two = one1
two |= gate_12(np.pi) << two.duration
two |= measure << two.duration
one.draw()
two.draw()
job = backend.run([one, two], meas_level=1, meas_return="single", shots=shots)
job_monitor(job)
aa = job.result()
result = []
for i in range(2):
result.append([aa.get_memory(i).real, aa.get_memory(i).imag])
result = np.squeeze(np.array(result)).T[0]
for i in range(2):
plt.scatter(result[:,0,i], result[:,1,i], label = f"{i+1}", alpha = 0.5)
plt.legend()
from qiskit.pulse import Schedule
from qiskit import Schedule
num_gates = 10
num_params = 2
x = ParameterVector("x",4)
params = ParameterVector("params", num_params)
list_of_params = list(x) + list(params)
QNN_Circuit = Schedule()
for i in range(num_gates):
if np.random.rand() > 0.5:
variables = np.random.choice(list_of_params,3)
QNN_Circuit += u3(*variables)
else:
variables = np.random.choice(list_of_params,1)
QNN_Circuit += gate_12(*variables)
QNN_Circuit += measure
Circuit = QNN_Circuit.assign_parameters({key:val for key, val in zip(list_of_params, value)}, inplace=False)
def result_estrac(job_results, qubit=0, num_jobs=1):
result = []
for i in range(num_jobs):
result.append([job_results.get_memory(i).real, job_results.get_memory(i).imag])
return np.squeeze(np.array(result)).T[qubit]
def Class_fit(job_result):
result = result_estrac(job_result)
count = []
pred0 = kmeans.predict(result)
for i in range(3):
pred = result[pred0==labels[i],:]
count = [np.sum(pred0==labels[i])/len(pred0) for i in range(3)]
return count
def loss_function(prediction, target):
softmax = np.exp(prediction)/ np.sum(np.exp(prediction))
target_vec = np.zeros((3,))
target_vec[target] = 1
cross_entropy = -np.sum(target_vec * np.log(softmax))
return cross_entropy
def Cost(inputs, target, parameters):
Circuit = QNN_Circuit.assign_parameters({key:val for key, val in zip(x, inputs)}, inplace=False)
Circuit = Circuit.assign_parameters({key:val for key, val in zip(params, parameters)}, inplace=False)
job = backend.run(Circuit, meas_level=1, meas_return="single", shots=shots)
job_monitor(job)
expResult = job.result()
prediction = Class_fit(expResult)
print(f"loss: {np.round(loss_function(prediction, target),3)}")
return loss_function(prediction, target)
def total_cost(params, Xbatch, Ybatch):
cost = 0
for i, t in zip(Xbatch, Ybatch):
cost += Cost(i, t, params)
return cost
def iterate_minibatches(inputs, targets, batch_size):
"""
A generator for batches of the input data
Args:
inputs (array[float]): input data
targets (array[float]): targets
Returns:
inputs (array[float]): one batch of input data of length `batch_size`
targets (array[float]): one batch of targets of length `batch_size`
"""
for start_idx in range(0, inputs.shape[0] - batch_size + 1, batch_size):
idxs = slice(start_idx, start_idx + batch_size)
yield inputs[idxs], targets[idxs]
from qiskit.algorithms.optimizers import SPSA
spsa_loss = []
def spsa_callback(nfev, x, fx, stepsize, accepted):
spsa_loss.append(fx)
spsa = SPSA(maxiter=20, learning_rate=0.1, perturbation=0.1, callback=spsa_callback)
initial_point = np.random.rand(num_params)
num_batches = 80
for Xbatch, Ybatch in iterate_minibatches(inputNorm, target, num_batches):
cost_fun = lambda params: total_cost(params, Xbatch, Ybatch)
x_opt, fx_opt, nfevs = spsa.optimize(num_params,
cost_fun,
initial_point=initial_point)
initial_point = x_opt
print(f"Loss function: {fx_opt}, x_opt: {x_opt}")
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### replaced cx gate ###
qc.cy(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
This is the final implementation of Shor's Algorithm using the circuit presented in section 2.3 of the report about the second
simplification introduced by the base paper used.
The circuit is general, so, in a good computer that can support simulations infinite qubits, it can factorize any number N. The only limitation
is the capacity of the computer when running in local simulator and the limits on the IBM simulator (in the number of qubits and in the number
of QASM instructions the simulations can have when sent to IBM simulator).
The user may try N=21, which is an example that runs perfectly fine even just in local simulator because, as in explained in report, this circuit,
because implements the QFT sequentially, uses less qubits then when using a "normal"n QFT.
"""
""" Imports from qiskit"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, IBMQ
from qiskit import BasicAer
import sys
""" Imports to Python functions """
import math
import array
import fractions
import numpy as np
import time
""" Local Imports """
from cfunctions import check_if_power, get_value_a
from cfunctions import get_factors
from qfunctions import create_QFT, create_inverse_QFT
from qfunctions import getAngle, cMULTmodN
""" Main program """
if __name__ == '__main__':
""" Ask for analysis number N """
N = int(input('Please insert integer number N: '))
print('input number was: {0}\n'.format(N))
""" Check if N==1 or N==0"""
if N==1 or N==0:
print('Please put an N different from 0 and from 1')
exit()
""" Check if N is even """
if (N%2)==0:
print('N is even, so does not make sense!')
exit()
""" Check if N can be put in N=p^q, p>1, q>=2 """
""" Try all numbers for p: from 2 to sqrt(N) """
if check_if_power(N)==True:
exit()
print('Not an easy case, using the quantum circuit is necessary\n')
""" To login to IBM Q experience the following functions should be called """
"""
IBMQ.delete_accounts()
IBMQ.save_account('insert token here')
IBMQ.load_accounts()"""
""" Get an integer a that is coprime with N """
a = get_value_a(N)
""" If user wants to force some values, can do that here, please make sure to update print and that N and a are coprime"""
"""print('Forcing N=15 and a=4 because its the fastest case, please read top of source file for more info')
N=15
a=2"""
""" Get n value used in Shor's algorithm, to know how many qubits are used """
n = math.ceil(math.log(N,2))
print('Total number of qubits used: {0}\n'.format(2*n+3))
ts = time.time()
""" Create quantum and classical registers """
"""auxilliary quantum register used in addition and multiplication"""
aux = QuantumRegister(n+2)
"""single qubit where the sequential QFT is performed"""
up_reg = QuantumRegister(1)
"""quantum register where the multiplications are made"""
down_reg = QuantumRegister(n)
"""classical register where the measured values of the sequential QFT are stored"""
up_classic = ClassicalRegister(2*n)
"""classical bit used to reset the state of the top qubit to 0 if the previous measurement was 1"""
c_aux = ClassicalRegister(1)
""" Create Quantum Circuit """
circuit = QuantumCircuit(down_reg , up_reg , aux, up_classic, c_aux)
""" Initialize down register to 1"""
circuit.x(down_reg[0])
""" Cycle to create the Sequential QFT, measuring qubits and applying the right gates according to measurements """
for i in range(0, 2*n):
"""reset the top qubit to 0 if the previous measurement was 1"""
circuit.x(up_reg).c_if(c_aux, 1)
circuit.h(up_reg)
cMULTmodN(circuit, up_reg[0], down_reg, aux, a**(2**(2*n-1-i)), N, n)
"""cycle through all possible values of the classical register and apply the corresponding conditional phase shift"""
for j in range(0, 2**i):
"""the phase shift is applied if the value of the classical register matches j exactly"""
circuit.u1(getAngle(j, i), up_reg[0]).c_if(up_classic, j)
circuit.h(up_reg)
circuit.measure(up_reg[0], up_classic[i])
circuit.measure(up_reg[0], c_aux[0])
""" show results of circuit creation """
create_time = round(time.time()-ts, 3)
#if n < 8: print(circuit)
print(f"... circuit creation time = {create_time}")
ts = time.time()
""" Select how many times the circuit runs"""
number_shots=int(input('Number of times to run the circuit: '))
if number_shots < 1:
print('Please run the circuit at least one time...')
exit()
""" Print info to user """
print('Executing the circuit {0} times for N={1} and a={2}\n'.format(number_shots,N,a))
""" Simulate the created Quantum Circuit """
simulation = execute(circuit, backend=BasicAer.get_backend('qasm_simulator'),shots=number_shots)
""" to run on IBM, use backend=IBMQ.get_backend('ibmq_qasm_simulator') in execute() function """
""" to run locally, use backend=BasicAer.get_backend('qasm_simulator') in execute() function """
""" Get the results of the simulation in proper structure """
sim_result=simulation.result()
counts_result = sim_result.get_counts(circuit)
""" show execution time """
exec_time = round(time.time()-ts, 3)
print(f"... circuit execute time = {exec_time}")
""" Print info to user from the simulation results """
print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format(number_shots))
i=0
while i < len(counts_result):
print('Result \"{0}\" happened {1} times out of {2}'.format(list(sim_result.get_counts().keys())[i],list(sim_result.get_counts().values())[i],number_shots))
i=i+1
""" An empty print just to have a good display in terminal """
print(' ')
""" Initialize this variable """
prob_success=0
""" For each simulation result, print proper info to user and try to calculate the factors of N"""
i=0
while i < len(counts_result):
""" Get the x_value from the final state qubits """
all_registers_output = list(sim_result.get_counts().keys())[i]
output_desired = all_registers_output.split(" ")[1]
x_value = int(output_desired, 2)
prob_this_result = 100 * ( int( list(sim_result.get_counts().values())[i] ) ) / (number_shots)
print("------> Analysing result {0}. This result happened in {1:.4f} % of all cases\n".format(output_desired,prob_this_result))
""" Print the final x_value to user """
print('In decimal, x_final value for this result is: {0}\n'.format(x_value))
""" Get the factors using the x value obtained """
success = get_factors(int(x_value),int(2*n),int(N),int(a))
if success==True:
prob_success = prob_success + prob_this_result
i=i+1
print("\nUsing a={0}, found the factors of N={1} in {2:.4f} % of the cases\n".format(a,N,prob_success))
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Check Map pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit.library import CXGate
from qiskit.transpiler.passes import CheckMap
from qiskit.transpiler import CouplingMap, Target
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestCheckMapCX(QiskitTestCase):
"""Tests the CheckMap pass with CX gates"""
def test_trivial_nop_map(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_trivial_nop_map_target(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
target = Target()
dag = circuit_to_dag(circuit)
pass_ = CheckMap(target)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_true(self):
"""Mapped is easy to check
qr0:--(+)-[H]-(+)-
| |
qr1:---.-------|--
|
qr2:-----------.--
CouplingMap map: [1]--[0]--[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_false(self):
"""Needs [0]-[1] in a [0]--[2]--[1]
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 2], [2, 1]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_false_target(self):
"""Needs [0]-[1] in a [0]--[2]--[1]
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
target = Target(num_qubits=2)
target.add_instruction(CXGate(), {(0, 2): None, (2, 1): None})
dag = circuit_to_dag(circuit)
pass_ = CheckMap(target)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_true(self):
"""Check control flow blocks are mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr, cr)
true_body.swap(0, 1)
true_body.cx(2, 1)
circuit.if_else((cr[0], 0), true_body, None, qr, cr)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_false(self):
"""Check control flow blocks are not mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr)
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr, [])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_layout_change_false(self):
"""Check control flow blocks with layout change are not mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr, cr)
true_body.cx(1, 2)
circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], cr)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_layout_change_true(self):
"""Check control flow blocks with layout change are mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr)
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], [])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_different_bits(self):
"""Check control flow blocks with layout change are mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(3, 1)
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], [cr[0]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_disjoint_controlflow_bits(self):
"""test control flow on with different registers"""
num_qubits = 4
coupling = CouplingMap.from_line(num_qubits)
qr1 = QuantumRegister(4, "qr")
qr2 = QuantumRegister(3, "qrif")
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr1, cr)
true_body = QuantumCircuit(qr2, [cr[0]])
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr1[[1, 0, 2]], [cr[0]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_nested_controlflow_true(self):
"""Test nested controlflow with true evaluation."""
num_qubits = 4
coupling = CouplingMap.from_line(num_qubits)
qr1 = QuantumRegister(4, "qr")
qr2 = QuantumRegister(3, "qrif")
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(1)
circuit = QuantumCircuit(qr1, cr1)
true_body = QuantumCircuit(qr2, cr2)
for_body = QuantumCircuit(3)
for_body.cx(0, 2)
true_body.for_loop(range(5), body=for_body, qubits=qr2, clbits=[])
circuit.if_else((cr1[0], 0), true_body, None, qr1[[1, 0, 2]], cr1)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_nested_controlflow_false(self):
"""Test nested controlflow with true evaluation."""
num_qubits = 4
coupling = CouplingMap.from_line(num_qubits)
qr1 = QuantumRegister(4, "qr")
qr2 = QuantumRegister(3, "qrif")
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(1)
circuit = QuantumCircuit(qr1, cr1)
true_body = QuantumCircuit(qr2, cr2)
for_body = QuantumCircuit(3)
for_body.cx(0, 2)
true_body.for_loop(range(5), body=for_body, qubits=qr2, clbits=[])
circuit.if_else((cr1[0], 0), true_body, None, qr1[[0, 1, 2]], cr1)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_nested_conditional_unusual_bit_order(self):
"""Test that `CheckMap` succeeds when inner conditional blocks have clbits that are involved
in their own (nested conditionals), and the binding order is not the same as the
bit-definition order. See gh-10394."""
qr = QuantumRegister(2, "q")
cr1 = ClassicalRegister(2, "c1")
cr2 = ClassicalRegister(2, "c2")
# Note that the bits here are not in the same order as in the outer circuit object, but they
# are the same as the binding order in the `if_test`, so everything maps `{x: x}` and it
# should all be fine. This kind of thing is a staple of the control-flow builders.
inner_order = [cr2[0], cr1[0], cr2[1], cr1[1]]
inner = QuantumCircuit(qr, inner_order, cr1, cr2)
inner.cx(0, 1).c_if(cr2, 3)
outer = QuantumCircuit(qr, cr1, cr2)
outer.if_test((cr1, 3), inner, outer.qubits, inner_order)
pass_ = CheckMap(CouplingMap.from_line(2))
pass_(outer)
self.assertTrue(pass_.property_set["is_swap_mapped"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test library of n-local circuits."""
import unittest
from test import combine
import numpy as np
from ddt import ddt, data, unpack
from qiskit.test.base import QiskitTestCase
from qiskit import transpile
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector, ParameterExpression
from qiskit.circuit.library import (
NLocal,
TwoLocal,
RealAmplitudes,
ExcitationPreserving,
XGate,
CRXGate,
CCXGate,
SwapGate,
RXGate,
RYGate,
EfficientSU2,
RZGate,
RXXGate,
RYYGate,
CXGate,
)
from qiskit.circuit.random.utils import random_circuit
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.quantum_info import Operator
@ddt
class TestNLocal(QiskitTestCase):
"""Test the n-local circuit class."""
def test_if_reps_is_negative(self):
"""Test to check if error is raised for negative value of reps"""
with self.assertRaises(ValueError):
_ = NLocal(reps=-1)
def test_if_reps_is_str(self):
"""Test to check if proper error is raised for str value of reps"""
with self.assertRaises(TypeError):
_ = NLocal(reps="3")
def test_if_reps_is_float(self):
"""Test to check if proper error is raised for float value of reps"""
with self.assertRaises(TypeError):
_ = NLocal(reps=5.6)
def test_if_reps_is_npint32(self):
"""Equality test for reps with int value and np.int32 value"""
self.assertEqual(NLocal(reps=3), NLocal(reps=np.int32(3)))
def test_if_reps_is_npint64(self):
"""Equality test for reps with int value and np.int64 value"""
self.assertEqual(NLocal(reps=3), NLocal(reps=np.int64(3)))
def test_reps_setter_when_negative(self):
"""Test to check if setter raises error for reps < 0"""
nlocal = NLocal(reps=1)
with self.assertRaises(ValueError):
nlocal.reps = -1
def assertCircuitEqual(self, qc1, qc2, visual=False, transpiled=True):
"""An equality test specialized to circuits."""
if transpiled:
basis_gates = ["id", "u1", "u3", "cx"]
qc1_transpiled = transpile(qc1, basis_gates=basis_gates, optimization_level=0)
qc2_transpiled = transpile(qc2, basis_gates=basis_gates, optimization_level=0)
qc1, qc2 = qc1_transpiled, qc2_transpiled
if visual:
self.assertEqual(qc1.draw(), qc2.draw())
else:
self.assertEqual(qc1, qc2)
def test_empty_nlocal(self):
"""Test the creation of an empty NLocal."""
nlocal = NLocal()
self.assertEqual(nlocal.num_qubits, 0)
self.assertEqual(nlocal.num_parameters_settable, 0)
self.assertEqual(nlocal.reps, 1)
self.assertEqual(nlocal, QuantumCircuit())
for attribute in [nlocal.rotation_blocks, nlocal.entanglement_blocks]:
self.assertEqual(len(attribute), 0)
@data(
(XGate(), [[0], [2], [1]]),
(XGate(), [[0]]),
(CRXGate(-0.2), [[2, 0], [1, 3]]),
)
@unpack
def test_add_layer_to_empty_nlocal(self, block, entangler_map):
"""Test appending gates to an empty nlocal."""
nlocal = NLocal()
nlocal.add_layer(block, entangler_map)
max_num_qubits = max(max(indices) for indices in entangler_map)
reference = QuantumCircuit(max_num_qubits + 1)
for indices in entangler_map:
reference.append(block, indices)
self.assertCircuitEqual(nlocal, reference)
@data([5, 3], [1, 5], [1, 1], [1, 2, 3, 10])
def test_append_circuit(self, num_qubits):
"""Test appending circuits to an nlocal works normally."""
# fixed depth of 3 gates per circuit
depth = 3
# keep track of a reference circuit
reference = QuantumCircuit(max(num_qubits))
# construct the NLocal from the first circuit
first_circuit = random_circuit(num_qubits[0], depth, seed=4200)
# TODO Terra bug: if this is to_gate it fails, since the QC adds an instruction not gate
nlocal = NLocal(max(num_qubits), entanglement_blocks=first_circuit.to_instruction(), reps=1)
reference.append(first_circuit, list(range(num_qubits[0])))
# append the rest
for num in num_qubits[1:]:
circuit = random_circuit(num, depth, seed=4200)
nlocal.append(circuit, list(range(num)))
reference.append(circuit, list(range(num)))
self.assertCircuitEqual(nlocal, reference)
@data([5, 3], [1, 5], [1, 1], [1, 2, 3, 10])
def test_add_nlocal(self, num_qubits):
"""Test adding an nlocal to an nlocal (using add_layer)."""
# fixed depth of 3 gates per circuit
depth = 3
# keep track of a reference circuit
reference = QuantumCircuit(max(num_qubits))
# construct the NLocal from the first circuit
first_circuit = random_circuit(num_qubits[0], depth, seed=4220)
# TODO Terra bug: if this is to_gate it fails, since the QC adds an instruction not gate
nlocal = NLocal(max(num_qubits), entanglement_blocks=first_circuit.to_instruction(), reps=1)
nlocal2 = nlocal.copy()
_ = nlocal2.data
reference.append(first_circuit, list(range(num_qubits[0])))
# append the rest
for num in num_qubits[1:]:
circuit = random_circuit(num, depth, seed=4220)
layer = NLocal(num, entanglement_blocks=circuit, reps=1)
nlocal.add_layer(layer)
nlocal2.add_layer(layer)
reference.append(circuit, list(range(num)))
self.assertCircuitEqual(nlocal, reference)
self.assertCircuitEqual(nlocal2, reference)
@unittest.skip("Feature missing")
def test_iadd_overload(self):
"""Test the overloaded + operator."""
num_qubits, depth = 2, 2
# construct two circuits for adding
first_circuit = random_circuit(num_qubits, depth, seed=4242)
circuit = random_circuit(num_qubits, depth, seed=4242)
# get a reference
reference = first_circuit + circuit
# convert the object to be appended to different types
others = [circuit, circuit.to_instruction(), circuit.to_gate(), NLocal(circuit)]
# try adding each type
for other in others:
nlocal = NLocal(num_qubits, entanglement_blocks=first_circuit, reps=1)
nlocal += other
with self.subTest(msg=f"type: {type(other)}"):
self.assertCircuitEqual(nlocal, reference)
def test_parameter_getter_from_automatic_repetition(self):
"""Test getting and setting of the nlocal parameters."""
circuit = QuantumCircuit(2)
circuit.ry(Parameter("a"), 0)
circuit.crx(Parameter("b"), 0, 1)
# repeat circuit and check that parameters are duplicated
reps = 3
nlocal = NLocal(2, entanglement_blocks=circuit, reps=reps)
self.assertTrue(nlocal.num_parameters, 6)
self.assertTrue(len(nlocal.parameters), 6)
@data(list(range(6)), ParameterVector("θ", length=6), [0, 1, Parameter("theta"), 3, 4, 5])
def test_parameter_setter_from_automatic_repetition(self, params):
"""Test getting and setting of the nlocal parameters."""
circuit = QuantumCircuit(2)
circuit.ry(Parameter("a"), 0)
circuit.crx(Parameter("b"), 0, 1)
# repeat circuit and check that parameters are duplicated
reps = 3
nlocal = NLocal(2, entanglement_blocks=circuit, reps=reps)
nlocal.assign_parameters(params, inplace=True)
param_set = {p for p in params if isinstance(p, ParameterExpression)}
with self.subTest(msg="Test the parameters of the non-transpiled circuit"):
# check the parameters of the final circuit
self.assertEqual(nlocal.parameters, param_set)
with self.subTest(msg="Test the parameters of the transpiled circuit"):
basis_gates = ["id", "u1", "u2", "u3", "cx"]
transpiled_circuit = transpile(nlocal, basis_gates=basis_gates)
self.assertEqual(transpiled_circuit.parameters, param_set)
@data(list(range(6)), ParameterVector("θ", length=6), [0, 1, Parameter("theta"), 3, 4, 5])
def test_parameters_setter(self, params):
"""Test setting the parameters via list."""
# construct circuit with some parameters
initial_params = ParameterVector("p", length=6)
circuit = QuantumCircuit(1)
for i, initial_param in enumerate(initial_params):
circuit.ry(i * initial_param, 0)
# create an NLocal from the circuit and set the new parameters
nlocal = NLocal(1, entanglement_blocks=circuit, reps=1)
nlocal.assign_parameters(params, inplace=True)
param_set = {p for p in params if isinstance(p, ParameterExpression)}
with self.subTest(msg="Test the parameters of the non-transpiled circuit"):
# check the parameters of the final circuit
self.assertEqual(nlocal.parameters, param_set)
with self.subTest(msg="Test the parameters of the transpiled circuit"):
basis_gates = ["id", "u1", "u2", "u3", "cx"]
transpiled_circuit = transpile(nlocal, basis_gates=basis_gates)
self.assertEqual(transpiled_circuit.parameters, param_set)
def test_repetetive_parameter_setting(self):
"""Test alternate setting of parameters and circuit construction."""
x = Parameter("x")
circuit = QuantumCircuit(1)
circuit.rx(x, 0)
nlocal = NLocal(1, entanglement_blocks=circuit, reps=3, insert_barriers=True)
with self.subTest(msg="immediately after initialization"):
self.assertEqual(len(nlocal.parameters), 3)
with self.subTest(msg="after circuit construction"):
self.assertEqual(len(nlocal.parameters), 3)
q = Parameter("q")
nlocal.assign_parameters([x, q, q], inplace=True)
with self.subTest(msg="setting parameter to Parameter objects"):
self.assertEqual(nlocal.parameters, set({x, q}))
nlocal.assign_parameters([0, -1], inplace=True)
with self.subTest(msg="setting parameter to numbers"):
self.assertEqual(nlocal.parameters, set())
def test_skip_unentangled_qubits(self):
"""Test skipping the unentangled qubits."""
num_qubits = 6
entanglement_1 = [[0, 1, 3], [1, 3, 5], [0, 1, 5]]
skipped_1 = [2, 4]
entanglement_2 = [entanglement_1, [[0, 1, 2], [2, 3, 5]]]
skipped_2 = [4]
for entanglement, skipped in zip([entanglement_1, entanglement_2], [skipped_1, skipped_2]):
with self.subTest(entanglement=entanglement, skipped=skipped):
nlocal = NLocal(
num_qubits,
rotation_blocks=XGate(),
entanglement_blocks=CCXGate(),
entanglement=entanglement,
reps=3,
skip_unentangled_qubits=True,
)
decomposed = nlocal.decompose()
skipped_set = {decomposed.qubits[i] for i in skipped}
dag = circuit_to_dag(decomposed)
idle = set(dag.idle_wires())
self.assertEqual(skipped_set, idle)
@data(
"linear",
"full",
"circular",
"sca",
"reverse_linear",
["linear", "full"],
["reverse_linear", "full"],
["circular", "linear", "sca"],
)
def test_entanglement_by_str(self, entanglement):
"""Test setting the entanglement of the layers by str."""
reps = 3
nlocal = NLocal(
5,
rotation_blocks=XGate(),
entanglement_blocks=CCXGate(),
entanglement=entanglement,
reps=reps,
)
def get_expected_entangler_map(rep_num, mode):
if mode == "linear":
return [(0, 1, 2), (1, 2, 3), (2, 3, 4)]
elif mode == "reverse_linear":
return [(2, 3, 4), (1, 2, 3), (0, 1, 2)]
elif mode == "full":
return [
(0, 1, 2),
(0, 1, 3),
(0, 1, 4),
(0, 2, 3),
(0, 2, 4),
(0, 3, 4),
(1, 2, 3),
(1, 2, 4),
(1, 3, 4),
(2, 3, 4),
]
else:
circular = [(3, 4, 0), (0, 1, 2), (1, 2, 3), (2, 3, 4)]
if mode == "circular":
return circular
sca = circular[-rep_num:] + circular[:-rep_num]
if rep_num % 2 == 1:
sca = [tuple(reversed(indices)) for indices in sca]
return sca
for rep_num in range(reps):
entangler_map = nlocal.get_entangler_map(rep_num, 0, 3)
if isinstance(entanglement, list):
mode = entanglement[rep_num % len(entanglement)]
else:
mode = entanglement
expected = get_expected_entangler_map(rep_num, mode)
with self.subTest(rep_num=rep_num):
# using a set here since the order does not matter
self.assertEqual(entangler_map, expected)
def test_pairwise_entanglement(self):
"""Test pairwise entanglement."""
nlocal = NLocal(
5,
rotation_blocks=XGate(),
entanglement_blocks=CXGate(),
entanglement="pairwise",
reps=1,
)
entangler_map = nlocal.get_entangler_map(0, 0, 2)
pairwise = [(0, 1), (2, 3), (1, 2), (3, 4)]
self.assertEqual(pairwise, entangler_map)
def test_pairwise_entanglement_raises(self):
"""Test choosing pairwise entanglement raises an error for too large blocks."""
nlocal = NLocal(3, XGate(), CCXGate(), entanglement="pairwise", reps=1)
# pairwise entanglement is only defined if the entangling gate has 2 qubits
with self.assertRaises(ValueError):
print(nlocal.draw())
def test_entanglement_by_list(self):
"""Test setting the entanglement by list.
This is the circuit we test (times 2, with final X layer)
┌───┐ ┌───┐┌───┐ ┌───┐
q_0: |0>┤ X ├──■────■───X────┤ X ├┤ X ├──■───X─────── .. ┤ X ├
├───┤ │ │ │ ├───┤└─┬─┘ │ │ ├───┤
q_1: |0>┤ X ├──■────┼───┼──X─┤ X ├──■────┼───X──X──── .. ┤ X ├
├───┤┌─┴─┐ │ │ │ ├───┤ │ │ │ x2 ├───┤
q_2: |0>┤ X ├┤ X ├──■───┼──X─┤ X ├──■────■──────X──X─ .. ┤ X ├
├───┤└───┘┌─┴─┐ │ ├───┤ ┌─┴─┐ │ ├───┤
q_3: |0>┤ X ├─────┤ X ├─X────┤ X ├─────┤ X ├───────X─ .. ┤ X ├
└───┘ └───┘ └───┘ └───┘ └───┘
"""
circuit = QuantumCircuit(4)
for _ in range(2):
circuit.x([0, 1, 2, 3])
circuit.barrier()
circuit.ccx(0, 1, 2)
circuit.ccx(0, 2, 3)
circuit.swap(0, 3)
circuit.swap(1, 2)
circuit.barrier()
circuit.x([0, 1, 2, 3])
circuit.barrier()
circuit.ccx(2, 1, 0)
circuit.ccx(0, 2, 3)
circuit.swap(0, 1)
circuit.swap(1, 2)
circuit.swap(2, 3)
circuit.barrier()
circuit.x([0, 1, 2, 3])
layer_1_ccx = [(0, 1, 2), (0, 2, 3)]
layer_1_swap = [(0, 3), (1, 2)]
layer_1 = [layer_1_ccx, layer_1_swap]
layer_2_ccx = [(2, 1, 0), (0, 2, 3)]
layer_2_swap = [(0, 1), (1, 2), (2, 3)]
layer_2 = [layer_2_ccx, layer_2_swap]
entanglement = [layer_1, layer_2]
nlocal = NLocal(
4,
rotation_blocks=XGate(),
entanglement_blocks=[CCXGate(), SwapGate()],
reps=4,
entanglement=entanglement,
insert_barriers=True,
)
self.assertCircuitEqual(nlocal, circuit)
def test_initial_state_as_circuit_object(self):
"""Test setting `initial_state` to `QuantumCircuit` object"""
# ┌───┐ ┌───┐
# q_0: ──■──┤ X ├───────■──┤ X ├
# ┌─┴─┐├───┤┌───┐┌─┴─┐├───┤
# q_1: ┤ X ├┤ H ├┤ X ├┤ X ├┤ X ├
# └───┘└───┘└───┘└───┘└───┘
ref = QuantumCircuit(2)
ref.cx(0, 1)
ref.x(0)
ref.h(1)
ref.x(1)
ref.cx(0, 1)
ref.x(0)
ref.x(1)
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.h(1)
expected = NLocal(
num_qubits=2,
rotation_blocks=XGate(),
entanglement_blocks=CXGate(),
initial_state=qc,
reps=1,
)
self.assertCircuitEqual(ref, expected)
@ddt
class TestTwoLocal(QiskitTestCase):
"""Tests for the TwoLocal circuit."""
def assertCircuitEqual(self, qc1, qc2, visual=False, transpiled=True):
"""An equality test specialized to circuits."""
if transpiled:
basis_gates = ["id", "u1", "u3", "cx"]
qc1_transpiled = transpile(qc1, basis_gates=basis_gates, optimization_level=0)
qc2_transpiled = transpile(qc2, basis_gates=basis_gates, optimization_level=0)
qc1, qc2 = qc1_transpiled, qc2_transpiled
if visual:
self.assertEqual(qc1.draw(), qc2.draw())
else:
self.assertEqual(qc1, qc2)
def test_skip_final_rotation_layer(self):
"""Test skipping the final rotation layer works."""
two = TwoLocal(3, ["ry", "h"], ["cz", "cx"], reps=2, skip_final_rotation_layer=True)
self.assertEqual(two.num_parameters, 6) # would be 9 with a final rotation layer
@data(
(5, "rx", "cx", "full", 2, 15),
(3, "x", "z", "linear", 1, 0),
(3, "rx", "cz", "linear", 0, 3),
(3, ["rx", "ry"], ["cry", "cx"], "circular", 2, 24),
)
@unpack
def test_num_parameters(self, num_qubits, rot, ent, ent_mode, reps, expected):
"""Test the number of parameters."""
two = TwoLocal(
num_qubits,
rotation_blocks=rot,
entanglement_blocks=ent,
entanglement=ent_mode,
reps=reps,
)
with self.subTest(msg="num_parameters_settable"):
self.assertEqual(two.num_parameters_settable, expected)
with self.subTest(msg="num_parameters"):
self.assertEqual(two.num_parameters, expected)
def test_empty_two_local(self):
"""Test the setup of an empty two-local circuit."""
two = TwoLocal()
with self.subTest(msg="0 qubits"):
self.assertEqual(two.num_qubits, 0)
with self.subTest(msg="no blocks are set"):
self.assertListEqual(two.rotation_blocks, [])
self.assertListEqual(two.entanglement_blocks, [])
with self.subTest(msg="equal to empty circuit"):
self.assertEqual(two, QuantumCircuit())
@data("rx", RXGate(Parameter("p")), RXGate, "circuit")
def test_various_block_types(self, rot):
"""Test setting the rotation blocks to various type and assert the output type is RX."""
if rot == "circuit":
rot = QuantumCircuit(1)
rot.rx(Parameter("angle"), 0)
two = TwoLocal(3, rot, reps=0)
self.assertEqual(len(two.rotation_blocks), 1)
rotation = two.rotation_blocks[0]
# decompose
self.assertIsInstance(rotation.data[0].operation, RXGate)
def test_parameter_setters(self):
"""Test different possibilities to set parameters."""
two = TwoLocal(3, rotation_blocks="rx", entanglement="cz", reps=2)
params = [0, 1, 2, Parameter("x"), Parameter("y"), Parameter("z"), 6, 7, 0]
params_set = {param for param in params if isinstance(param, Parameter)}
with self.subTest(msg="dict assign and copy"):
ordered = two.ordered_parameters
bound = two.assign_parameters(dict(zip(ordered, params)), inplace=False)
self.assertEqual(bound.parameters, params_set)
self.assertEqual(two.num_parameters, 9)
with self.subTest(msg="list assign and copy"):
ordered = two.ordered_parameters
bound = two.assign_parameters(params, inplace=False)
self.assertEqual(bound.parameters, params_set)
self.assertEqual(two.num_parameters, 9)
with self.subTest(msg="list assign inplace"):
ordered = two.ordered_parameters
two.assign_parameters(params, inplace=True)
self.assertEqual(two.parameters, params_set)
self.assertEqual(two.num_parameters, 3)
self.assertEqual(two.num_parameters_settable, 9)
def test_parameters_settable_is_constant(self):
"""Test the attribute num_parameters_settable does not change on parameter change."""
two = TwoLocal(3, rotation_blocks="rx", entanglement="cz", reps=2)
ordered_params = two.ordered_parameters
x = Parameter("x")
two.assign_parameters(dict(zip(ordered_params, [x] * two.num_parameters)), inplace=True)
with self.subTest(msg="num_parameters collapsed to 1"):
self.assertEqual(two.num_parameters, 1)
with self.subTest(msg="num_parameters_settable remained constant"):
self.assertEqual(two.num_parameters_settable, len(ordered_params))
def test_compose_inplace_to_circuit(self):
"""Test adding a two-local to an existing circuit."""
two = TwoLocal(3, ["ry", "rz"], "cz", "full", reps=1, insert_barriers=True)
circuit = QuantumCircuit(3)
circuit.compose(two, inplace=True)
# ┌──────────┐┌──────────┐ ░ ░ ┌──────────┐ ┌──────────┐
# q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├─░──■──■─────░─┤ Ry(θ[6]) ├─┤ Rz(θ[9]) ├
# ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤┌┴──────────┤
# q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├─░──■──┼──■──░─┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├
# ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤├───────────┤
# q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├─░─────■──■──░─┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├
# └──────────┘└──────────┘ ░ ░ └──────────┘└───────────┘
reference = QuantumCircuit(3)
param_iter = iter(two.ordered_parameters)
for i in range(3):
reference.ry(next(param_iter), i)
for i in range(3):
reference.rz(next(param_iter), i)
reference.barrier()
reference.cz(0, 1)
reference.cz(0, 2)
reference.cz(1, 2)
reference.barrier()
for i in range(3):
reference.ry(next(param_iter), i)
for i in range(3):
reference.rz(next(param_iter), i)
self.assertCircuitEqual(circuit.decompose(), reference)
def test_composing_two(self):
"""Test adding two two-local circuits."""
entangler_map = [[0, 3], [0, 2]]
two = TwoLocal(4, [], "cry", entangler_map, reps=1)
circuit = two.compose(two)
reference = QuantumCircuit(4)
params = two.ordered_parameters
for _ in range(2):
reference.cry(params[0], 0, 3)
reference.cry(params[1], 0, 2)
self.assertCircuitEqual(reference, circuit)
def test_ry_blocks(self):
"""Test that the RealAmplitudes circuit is instantiated correctly."""
two = RealAmplitudes(4)
with self.subTest(msg="test rotation gate"):
self.assertEqual(len(two.rotation_blocks), 1)
self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RYGate)
with self.subTest(msg="test parameter bounds"):
expected = [(-np.pi, np.pi)] * two.num_parameters
np.testing.assert_almost_equal(two.parameter_bounds, expected)
def test_ry_circuit_reverse_linear(self):
"""Test a RealAmplitudes circuit with entanglement = "reverse_linear"."""
num_qubits = 3
reps = 2
entanglement = "reverse_linear"
parameters = ParameterVector("theta", num_qubits * (reps + 1))
param_iter = iter(parameters)
expected = QuantumCircuit(3)
for _ in range(reps):
for i in range(num_qubits):
expected.ry(next(param_iter), i)
expected.cx(1, 2)
expected.cx(0, 1)
for i in range(num_qubits):
expected.ry(next(param_iter), i)
library = RealAmplitudes(
num_qubits, reps=reps, entanglement=entanglement
).assign_parameters(parameters)
self.assertCircuitEqual(library, expected)
def test_ry_circuit_full(self):
"""Test a RealAmplitudes circuit with entanglement = "full"."""
num_qubits = 3
reps = 2
entanglement = "full"
parameters = ParameterVector("theta", num_qubits * (reps + 1))
param_iter = iter(parameters)
# ┌──────────┐ ┌──────────┐ ┌──────────┐
# q_0: ┤ Ry(θ[0]) ├──■────■──┤ Ry(θ[3]) ├──────────────■────■──┤ Ry(θ[6]) ├────────────
# ├──────────┤┌─┴─┐ │ └──────────┘┌──────────┐┌─┴─┐ │ └──────────┘┌──────────┐
# q_1: ┤ Ry(θ[1]) ├┤ X ├──┼─────────■────┤ Ry(θ[4]) ├┤ X ├──┼─────────■────┤ Ry(θ[7]) ├
# ├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤
# q_2: ┤ Ry(θ[2]) ├─────┤ X ├─────┤ X ├──┤ Ry(θ[5]) ├─────┤ X ├─────┤ X ├──┤ Ry(θ[8]) ├
# └──────────┘ └───┘ └───┘ └──────────┘ └───┘ └───┘ └──────────┘
expected = QuantumCircuit(3)
for _ in range(reps):
for i in range(num_qubits):
expected.ry(next(param_iter), i)
expected.cx(0, 1)
expected.cx(0, 2)
expected.cx(1, 2)
for i in range(num_qubits):
expected.ry(next(param_iter), i)
library = RealAmplitudes(
num_qubits, reps=reps, entanglement=entanglement
).assign_parameters(parameters)
self.assertCircuitEqual(library, expected)
def test_ryrz_blocks(self):
"""Test that the EfficientSU2 circuit is instantiated correctly."""
two = EfficientSU2(3)
with self.subTest(msg="test rotation gate"):
self.assertEqual(len(two.rotation_blocks), 2)
self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RYGate)
self.assertIsInstance(two.rotation_blocks[1].data[0].operation, RZGate)
with self.subTest(msg="test parameter bounds"):
expected = [(-np.pi, np.pi)] * two.num_parameters
np.testing.assert_almost_equal(two.parameter_bounds, expected)
def test_ryrz_circuit(self):
"""Test an EfficientSU2 circuit."""
num_qubits = 3
reps = 2
entanglement = "circular"
parameters = ParameterVector("theta", 2 * num_qubits * (reps + 1))
param_iter = iter(parameters)
# ┌──────────┐┌──────────┐┌───┐ ┌──────────┐┌──────────┐ »
# q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├┤ X ├──■──┤ Ry(θ[6]) ├┤ Rz(θ[9]) ├─────────────»
# ├──────────┤├──────────┤└─┬─┘┌─┴─┐└──────────┘├──────────┤┌───────────┐»
# q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├──┼──┤ X ├─────■──────┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├»
# ├──────────┤├──────────┤ │ └───┘ ┌─┴─┐ ├──────────┤├───────────┤»
# q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├──■──────────┤ X ├────┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├»
# └──────────┘└──────────┘ └───┘ └──────────┘└───────────┘»
# « ┌───┐ ┌───────────┐┌───────────┐
# «q_0: ┤ X ├──■──┤ Ry(θ[12]) ├┤ Rz(θ[15]) ├─────────────
# « └─┬─┘┌─┴─┐└───────────┘├───────────┤┌───────────┐
# «q_1: ──┼──┤ X ├──────■──────┤ Ry(θ[13]) ├┤ Rz(θ[16]) ├
# « │ └───┘ ┌─┴─┐ ├───────────┤├───────────┤
# «q_2: ──■───────────┤ X ├────┤ Ry(θ[14]) ├┤ Rz(θ[17]) ├
# « └───┘ └───────────┘└───────────┘
expected = QuantumCircuit(3)
for _ in range(reps):
for i in range(num_qubits):
expected.ry(next(param_iter), i)
for i in range(num_qubits):
expected.rz(next(param_iter), i)
expected.cx(2, 0)
expected.cx(0, 1)
expected.cx(1, 2)
for i in range(num_qubits):
expected.ry(next(param_iter), i)
for i in range(num_qubits):
expected.rz(next(param_iter), i)
library = EfficientSU2(num_qubits, reps=reps, entanglement=entanglement).assign_parameters(
parameters
)
self.assertCircuitEqual(library, expected)
def test_swaprz_blocks(self):
"""Test that the ExcitationPreserving circuit is instantiated correctly."""
two = ExcitationPreserving(5)
with self.subTest(msg="test rotation gate"):
self.assertEqual(len(two.rotation_blocks), 1)
self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RZGate)
with self.subTest(msg="test entanglement gate"):
self.assertEqual(len(two.entanglement_blocks), 1)
block = two.entanglement_blocks[0]
self.assertEqual(len(block.data), 2)
self.assertIsInstance(block.data[0].operation, RXXGate)
self.assertIsInstance(block.data[1].operation, RYYGate)
with self.subTest(msg="test parameter bounds"):
expected = [(-np.pi, np.pi)] * two.num_parameters
np.testing.assert_almost_equal(two.parameter_bounds, expected)
def test_swaprz_circuit(self):
"""Test a ExcitationPreserving circuit in iswap mode."""
num_qubits = 3
reps = 2
entanglement = "linear"
parameters = ParameterVector("theta", num_qubits * (reps + 1) + reps * (num_qubits - 1))
param_iter = iter(parameters)
# ┌──────────┐┌────────────┐┌────────────┐ ┌──────────┐ »
# q_0: ┤ Rz(θ[0]) ├┤0 ├┤0 ├─┤ Rz(θ[5]) ├───────────────»
# ├──────────┤│ Rxx(θ[3]) ││ Ryy(θ[3]) │┌┴──────────┴┐┌────────────┐»
# q_1: ┤ Rz(θ[1]) ├┤1 ├┤1 ├┤0 ├┤0 ├»
# ├──────────┤└────────────┘└────────────┘│ Rxx(θ[4]) ││ Ryy(θ[4]) │»
# q_2: ┤ Rz(θ[2]) ├────────────────────────────┤1 ├┤1 ├»
# └──────────┘ └────────────┘└────────────┘»
# « ┌────────────┐┌────────────┐┌───────────┐ »
# «q_0: ────────────┤0 ├┤0 ├┤ Rz(θ[10]) ├───────────────»
# « ┌──────────┐│ Rxx(θ[8]) ││ Ryy(θ[8]) │├───────────┴┐┌────────────┐»
# «q_1: ┤ Rz(θ[6]) ├┤1 ├┤1 ├┤0 ├┤0 ├»
# « ├──────────┤└────────────┘└────────────┘│ Rxx(θ[9]) ││ Ryy(θ[9]) │»
# «q_2: ┤ Rz(θ[7]) ├────────────────────────────┤1 ├┤1 ├»
# « └──────────┘ └────────────┘└────────────┘»
# «
# «q_0: ─────────────
# « ┌───────────┐
# «q_1: ┤ Rz(θ[11]) ├
# « ├───────────┤
# «q_2: ┤ Rz(θ[12]) ├
# « └───────────┘
expected = QuantumCircuit(3)
for _ in range(reps):
for i in range(num_qubits):
expected.rz(next(param_iter), i)
shared_param = next(param_iter)
expected.rxx(shared_param, 0, 1)
expected.ryy(shared_param, 0, 1)
shared_param = next(param_iter)
expected.rxx(shared_param, 1, 2)
expected.ryy(shared_param, 1, 2)
for i in range(num_qubits):
expected.rz(next(param_iter), i)
library = ExcitationPreserving(
num_qubits, reps=reps, entanglement=entanglement
).assign_parameters(parameters)
self.assertCircuitEqual(library, expected)
def test_fsim_circuit(self):
"""Test a ExcitationPreserving circuit in fsim mode."""
num_qubits = 3
reps = 2
entanglement = "linear"
# need the parameters in the entanglement blocks to be the same because the order
# can get mixed up in ExcitationPreserving (since parameters are not ordered in circuits)
parameters = [1] * (num_qubits * (reps + 1) + reps * (1 + num_qubits))
param_iter = iter(parameters)
# ┌───────┐┌─────────┐┌─────────┐ ┌───────┐ »
# q_0: ┤ Rz(1) ├┤0 ├┤0 ├─■──────┤ Rz(1) ├───────────────────»
# ├───────┤│ Rxx(1) ││ Ryy(1) │ │P(1) ┌┴───────┴┐┌─────────┐ »
# q_1: ┤ Rz(1) ├┤1 ├┤1 ├─■─────┤0 ├┤0 ├─■─────»
# ├───────┤└─────────┘└─────────┘ │ Rxx(1) ││ Ryy(1) │ │P(1) »
# q_2: ┤ Rz(1) ├─────────────────────────────┤1 ├┤1 ├─■─────»
# └───────┘ └─────────┘└─────────┘ »
# « ┌─────────┐┌─────────┐ ┌───────┐ »
# «q_0: ─────────┤0 ├┤0 ├─■──────┤ Rz(1) ├───────────────────»
# « ┌───────┐│ Rxx(1) ││ Ryy(1) │ │P(1) ┌┴───────┴┐┌─────────┐ »
# «q_1: ┤ Rz(1) ├┤1 ├┤1 ├─■─────┤0 ├┤0 ├─■─────»
# « ├───────┤└─────────┘└─────────┘ │ Rxx(1) ││ Ryy(1) │ │P(1) »
# «q_2: ┤ Rz(1) ├─────────────────────────────┤1 ├┤1 ├─■─────»
# « └───────┘ └─────────┘└─────────┘ »
# «
# «q_0: ─────────
# « ┌───────┐
# «q_1: ┤ Rz(1) ├
# « ├───────┤
# «q_2: ┤ Rz(1) ├
# « └───────┘
expected = QuantumCircuit(3)
for _ in range(reps):
for i in range(num_qubits):
expected.rz(next(param_iter), i)
shared_param = next(param_iter)
expected.rxx(shared_param, 0, 1)
expected.ryy(shared_param, 0, 1)
expected.cp(next(param_iter), 0, 1)
shared_param = next(param_iter)
expected.rxx(shared_param, 1, 2)
expected.ryy(shared_param, 1, 2)
expected.cp(next(param_iter), 1, 2)
for i in range(num_qubits):
expected.rz(next(param_iter), i)
library = ExcitationPreserving(
num_qubits, reps=reps, mode="fsim", entanglement=entanglement
).assign_parameters(parameters)
self.assertCircuitEqual(library, expected)
def test_circular_on_same_block_and_circuit_size(self):
"""Test circular entanglement works correctly if the circuit and block sizes match."""
two = TwoLocal(2, "ry", "cx", entanglement="circular", reps=1)
parameters = np.arange(two.num_parameters)
# ┌───────┐ ┌───────┐
# q_0: ┤ Ry(0) ├──■──┤ Ry(2) ├
# ├───────┤┌─┴─┐├───────┤
# q_1: ┤ Ry(1) ├┤ X ├┤ Ry(3) ├
# └───────┘└───┘└───────┘
ref = QuantumCircuit(2)
ref.ry(parameters[0], 0)
ref.ry(parameters[1], 1)
ref.cx(0, 1)
ref.ry(parameters[2], 0)
ref.ry(parameters[3], 1)
self.assertCircuitEqual(two.assign_parameters(parameters), ref)
def test_circuit_with_numpy_integers(self):
"""Test if TwoLocal can be made from numpy integers"""
num_qubits = 6
reps = 3
expected_np32 = [
(i, j)
for i in np.arange(num_qubits, dtype=np.int32)
for j in np.arange(num_qubits, dtype=np.int32)
if i < j
]
expected_np64 = [
(i, j)
for i in np.arange(num_qubits, dtype=np.int64)
for j in np.arange(num_qubits, dtype=np.int64)
if i < j
]
two_np32 = TwoLocal(num_qubits, "ry", "cx", entanglement=expected_np32, reps=reps)
two_np64 = TwoLocal(num_qubits, "ry", "cx", entanglement=expected_np64, reps=reps)
expected_cx = reps * num_qubits * (num_qubits - 1) / 2
self.assertEqual(two_np32.decompose().count_ops()["cx"], expected_cx)
self.assertEqual(two_np64.decompose().count_ops()["cx"], expected_cx)
@combine(num_qubits=[4, 5])
def test_full_vs_reverse_linear(self, num_qubits):
"""Test that 'full' and 'reverse_linear' provide the same unitary element."""
reps = 2
full = RealAmplitudes(num_qubits=num_qubits, entanglement="full", reps=reps)
num_params = (reps + 1) * num_qubits
np.random.seed(num_qubits)
params = np.random.rand(num_params)
reverse = RealAmplitudes(num_qubits=num_qubits, entanglement="reverse_linear", reps=reps)
full.assign_parameters(params, inplace=True)
reverse.assign_parameters(params, inplace=True)
self.assertEqual(Operator(full), Operator(reverse))
if __name__ == "__main__":
unittest.main()
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
# !pip uninstall -y matplotlib && pip install matplotlib==3.7.2
from qiskit.circuit.library import SwapGate, CXGate
from qiskit.quantum_info import random_unitary
from qiskit.extensions import UnitaryGate
from monodromy.haar import expected_cost
from qiskit.circuit.library import iSwapGate, XXPlusYYGate, CXGate
import numpy as np
from monodromy.render import gates_to_coverage_plot
from monodromy.haar import expected_cost
from monodromy.coverage import coverage_lookup_cost
import h5py
import json
import matplotlib.pyplot as plt
from scipy import stats
from collections import Counter
import scienceplots
import LovelyPlots.utils as lp
from tqdm import tqdm
# %matplotlib widget
from qiskit import QuantumCircuit
from qiskit.circuit.library import CZGate
from qiskit.quantum_info.operators import Operator
from qiskit.circuit import Gate
from monodromy.haar import gates_to_haar
from qiskit.circuit.library import CXGate, iSwapGate
import numpy as np
qc = QuantumCircuit(2)
qc.append(iSwapGate().power(-1), [0, 1])
qc.append(CZGate().power(1 / 6), [0, 1])
syc = Operator(qc)
syc.name = "syc"
syc.params = []
print(gates_to_haar(syc))
from monodromy.render import gates_to_coverage_plot
gates_to_coverage_plot(syc, overlap=False)
class ErrorModel:
"""Use exponential decay error model.
Define fidelity model as some function of (time) cost.
"""
def __init__(self, unit_fidelity=0.99):
"""Unit fidelity is the fidelity of operation with unit cost 1.0
NOTE: simple convention is that CX, iSWAP have unit cost 1.0, then
sqrt(CX) and sqrt(iSWAP) have unit cost 0.5, etc.
"""
assert 0 <= unit_fidelity and unit_fidelity <= 1
self.unit_fidelity = unit_fidelity
self.normalized_lifetime = -1.0 / np.log(unit_fidelity)
def fidelity(self, cost):
"""Convert (time) cost to fidelity"""
return np.exp(-cost / self.normalized_lifetime)
def infidelity(self, cost):
"""Convert (time) cost to infidelity"""
return 1 - self.fidelity(cost)
# ErrorModel(0.99).fidelity(1.5)
U = syc
safe_basis_str = "syc"
basis_str = "syc"
basis_cost = 1.0
unit_fidelity = 0.99
affine_error_model = ErrorModel(unit_fidelity=unit_fidelity)
coverage_1 = gates_to_coverage_plot(U, costs=[basis_cost])
no_mirror_haar_exact = expected_cost(coverage_1)
print(no_mirror_haar_exact)
average_fidelity = affine_error_model.fidelity(no_mirror_haar_exact)
print(average_fidelity)
coverage_2 = gates_to_coverage_plot(U, SwapGate(), costs=[basis_cost, 0])
mirror_haar_exact = expected_cost(coverage_2)
print(mirror_haar_exact)
average_fidelity = affine_error_model.fidelity(mirror_haar_exact)
print(average_fidelity)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_st_qcs), ")")
t3_st_qcs[-1].draw("mpl") # only view trotter gates
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(t3_st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=initial_layout)
print('Job ID', cal_job.job_id())
dt_now = datetime.datetime.now()
print(dt_now)
with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_jakarta_100step_20220412_171248_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
# set the target state
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
# mit_results = meas_fitter.filter.apply(job.result()) # apply QREM
rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq')
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test RemoveDiagonalGatesBeforeMeasure pass"""
import unittest
from copy import deepcopy
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit.library import U1Gate, CU1Gate
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import RemoveDiagonalGatesBeforeMeasure, DAGFixedPoint
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TesRemoveDiagonalGatesBeforeMeasure(QiskitTestCase):
"""Test remove_diagonal_gates_before_measure optimizations."""
def test_optimize_1rz_1measure(self):
"""Remove a single RZGate
qr0:-RZ--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1z_1measure(self):
"""Remove a single ZGate
qr0:--Z--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.z(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1t_1measure(self):
"""Remove a single TGate, SGate, TdgGate, SdgGate, U1Gate
qr0:--T--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.t(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1s_1measure(self):
"""Remove a single SGate
qr0:--S--m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.s(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1tdg_1measure(self):
"""Remove a single TdgGate
qr0:-Tdg-m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.tdg(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1sdg_1measure(self):
"""Remove a single SdgGate
qr0:-Sdg--m-- qr0:--m-
| |
qr1:------|-- ==> qr1:--|-
| |
cr0:------.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.sdg(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1u1_1measure(self):
"""Remove a single U1Gate
qr0:--U1-m-- qr0:--m-
| |
qr1:-----|-- ==> qr1:--|-
| |
cr0:-----.-- cr0:--.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(U1Gate(0.1), [qr[0]])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1rz_1z_1measure(self):
"""Remove a single RZ and leave the other Z
qr0:-RZ--m-- qr0:----m-
| |
qr1:--Z--|-- ==> qr1:--Z-|-
| |
cr0:-----.-- cr0:----.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[0])
circuit.z(qr[1])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.z(qr[1])
expected.measure(qr[0], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_simple_if_else(self):
"""Test that the pass recurses into an if-else."""
pass_ = RemoveDiagonalGatesBeforeMeasure()
base_test = QuantumCircuit(1, 1)
base_test.z(0)
base_test.measure(0, 0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
test = QuantumCircuit(1, 1)
test.if_else(
(test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(1, 1)
expected.if_else(
(expected.clbits[0], True),
base_expected.copy(),
base_expected.copy(),
expected.qubits,
expected.clbits,
)
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the pass recurses into nested control flow."""
pass_ = RemoveDiagonalGatesBeforeMeasure()
base_test = QuantumCircuit(2, 1)
base_test.cz(0, 1)
base_test.measure(0, 0)
base_expected = QuantumCircuit(2, 1)
base_expected.measure(1, 0)
body_test = QuantumCircuit(2, 1)
body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits)
body_expected = QuantumCircuit(2, 1)
body_expected.for_loop(
(0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits
)
test = QuantumCircuit(2, 1)
test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits)
expected = QuantumCircuit(2, 1)
expected.while_loop(
(expected.clbits[0], True), body_expected, expected.qubits, expected.clbits
)
self.assertEqual(pass_(test), expected)
class TesRemoveDiagonalControlGatesBeforeMeasure(QiskitTestCase):
"""Test remove diagonal control gates before measure."""
def test_optimize_1cz_2measure(self):
"""Remove a single CZGate
qr0:--Z--m--- qr0:--m---
| | |
qr1:--.--|-m- ==> qr1:--|-m-
| | | |
cr0:-----.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1crz_2measure(self):
"""Remove a single CRZGate
qr0:-RZ--m--- qr0:--m---
| | |
qr1:--.--|-m- ==> qr1:--|-m-
| | | |
cr0:-----.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.crz(0.1, qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1cu1_2measure(self):
"""Remove a single CU1Gate
qr0:-CU1-m--- qr0:--m---
| | |
qr1:--.--|-m- ==> qr1:--|-m-
| | | |
cr0:-----.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU1Gate(0.1), [qr[0], qr[1]])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_1rzz_2measure(self):
"""Remove a single RZZGate
qr0:--.----m--- qr0:--m---
|zz | |
qr1:--.----|-m- ==> qr1:--|-m-
| | | |
cr0:-------.-.- cr0:--.-.-
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rzz(0.1, qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
expected.measure(qr[1], cr[0])
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
class TestRemoveDiagonalGatesBeforeMeasureOveroptimizations(QiskitTestCase):
"""Test situations where remove_diagonal_gates_before_measure should not optimize"""
def test_optimize_1cz_1measure(self):
"""Do not remove a CZGate because measure happens on only one of the wires
Compare with test_optimize_1cz_2measure.
qr0:--Z--m---
| |
qr1:--.--|---
|
cr0:-----.---
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = deepcopy(dag)
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(expected, after)
def test_do_not_optimize_with_conditional(self):
"""Diagonal gates with conditionals on a measurement target.
See https://github.com/Qiskit/qiskit-terra/pull/2208#issuecomment-487238819
░ ┌───┐┌─┐
qr_0: |0>────────────░─┤ H ├┤M├
┌─────────┐ ░ └───┘└╥┘
qr_1: |0>┤ Rz(0.1) ├─░───────╫─
└─┬──┴──┬─┘ ░ ║
cr_0: 0 ══╡ = 1 ╞═══════════╩═
└─────┘
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[1]).c_if(cr, 1)
circuit.barrier()
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
dag = circuit_to_dag(circuit)
expected = deepcopy(dag)
pass_ = RemoveDiagonalGatesBeforeMeasure()
after = pass_.run(dag)
self.assertEqual(expected, after)
class TestRemoveDiagonalGatesBeforeMeasureFixedPoint(QiskitTestCase):
"""Test remove_diagonal_gates_before_measure optimizations in
a transpiler, using fixed point."""
def test_optimize_rz_z(self):
"""Remove two swaps that overlap
qr0:--RZ-Z--m-- qr0:--m--
| |
cr0:--------.-- cr0:--.--
"""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.rz(0.1, qr[0])
circuit.z(qr[0])
circuit.measure(qr[0], cr[0])
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr[0])
pass_manager = PassManager()
pass_manager.append(
[RemoveDiagonalGatesBeforeMeasure(), DAGFixedPoint()],
do_while=lambda property_set: not property_set["dag_fixed_point"],
)
after = pass_manager.run(circuit)
self.assertEqual(expected, after)
if __name__ == "__main__":
unittest.main()
|
https://github.com/m0tela01/GroversAlgorithmQSvsQiskit
|
m0tela01
|
%matplotlib inline
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer
from qiskit.compiler import transpile, assemble
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator
from qiskit.visualization import *
from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout
from qiskit.tools.jupyter import *
from qiskit.tools.visualization import plot_histogram, plot_state_city
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
import numpy as np
from math import pi
provider = IBMQ.load_account()
q = QuantumRegister(5, name='quantumRegister')
c = ClassicalRegister(5, name ='qlassicalRegister')
qc = QuantumCircuit(q, c)
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
qc.h(q[4])
qc.barrier()
qc.barrier()
qc.draw()
qc.h(q[2])
qc.cx(q[3],q[2])
qc.tdg(q[2])
qc.cx(q[4],q[2])
qc.t(q[2])
qc.cx(q[3],q[2])
qc.tdg(q[2])
qc.cx(q[4],q[2])
# qc.tdg(q[2])
# qc.cx(q[4],q[2])
qc.barrier()
qc.t(q[2])
qc.tdg(q[3])
qc.h(q[2])
qc.barrier()
qc.h(q[3])
qc.h(q[4])
qc.cx(q[3],q[4])
qc.h(q[3])
qc.h(q[4])
qc.tdg(q[3])
qc.barrier()
qc.draw()
qc.h(q[3])
qc.h(q[4])
qc.cx(q[3],q[4])
qc.h(q[3])
qc.h(q[4])
qc.s(q[3])
qc.t(q[4])
qc.barrier()
qc.cx(q[2],q[1])
qc.t(q[1])
qc.cx(q[2],q[1])
qc.tdg(q[1])
qc.tdg(q[2])
qc.h(q[2])
qc.cx(q[3],q[2])
qc.tdg(q[2])
qc.cx(q[4],q[2])
qc.t(q[2])
qc.cx(q[3],q[2])
qc.tdg(q[2])
qc.cx(q[4],q[2])
qc.t(q[2])
qc.tdg(q[3])
qc.h(q[2])
qc.barrier()
qc.h(q[3])
qc.h(q[4])
qc.cx(q[3],q[4])
qc.h(q[3])
qc.h(q[4])
qc.tdg(q[3])
qc.barrier()
qc.h(q[3])
qc.h(q[4])
qc.cx(q[3],q[4])
qc.h(q[3])
qc.h(q[4])
qc.s(q[3])
qc.t(q[4])
qc.barrier()
qc.cx(q[2],q[1])
qc.tdg(q[1])
qc.cx(q[2],q[1])
qc.t(q[1])
qc.t(q[2])
qc.barrier()
qc.h(q[3])
qc.h(q[4])
qc.cx(q[3],q[4])
qc.h(q[3])
qc.h(q[4])
qc.barrier()
qc.draw()
qc.cx(q[2],q[1])
qc.h(q[1])
qc.h(q[2])
qc.cx(q[2],q[1])
qc.h(q[1])
qc.h(q[2])
qc.cx(q[2],q[1])
qc.cx(q[3],q[2])
qc.u1(pi/8, q[2])
qc.cx(q[3],q[2])
qc.u1(-pi/8, q[2])
qc.u1(-pi/8,q[3])
qc.barrier()
qc.h(q[3])
qc.h(q[4])
qc.cx(q[3],q[4])
qc.h(q[3])
qc.h(q[4])
qc.barrier()
qc.cx(q[3],q[2])
qc.u1(-pi/8,q[2])
qc.cx(q[3],q[2])
qc.u1(pi/8,q[2])
qc.u1(pi/8,q[3])
qc.cx(q[4],q[2])
qc.u1(-pi/8,q[2])
qc.cx(q[4],q[2])
qc.u1(pi/8,q[2])
qc.u1(-pi/8,q[4])
qc.barrier()
qc.cx(q[2],q[1])
qc.h(q[1])
qc.h(q[2])
qc.cx(q[2],q[1])
qc.h(q[1])
qc.h(q[2])
qc.cx(q[2],q[1])
qc.barrier()
qc.barrier()
qc.h(q[4])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
qc.barrier()
qc.x(q[4])
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
qc.draw()
qc.barrier()
qc.barrier()
qc.h(q[2])
qc.cx(q[3],q[2])
qc.tdg(q[2])
qc.cx(q[4],q[2])
qc.t(q[2])
qc.cx(q[3],q[2])
qc.tdg(q[2])
qc.cx(q[4],q[2])
# qc.tdg(q[2])
# qc.cx(q[4],q[2])
qc.barrier()
qc.t(q[2])
qc.tdg(q[3])
qc.h(q[2])
qc.barrier()
qc.h(q[3])
qc.h(q[4])
qc.cx(q[3],q[4])
qc.h(q[3])
qc.h(q[4])
qc.tdg(q[3])
qc.barrier()
qc.draw()
qc.h(q[3])
qc.h(q[4])
qc.cx(q[3],q[4])
qc.h(q[3])
qc.h(q[4])
qc.s(q[3])
qc.t(q[4])
qc.barrier()
qc.cx(q[2],q[1])
qc.t(q[1])
qc.cx(q[2],q[1])
qc.tdg(q[1])
qc.tdg(q[2])
qc.h(q[2])
qc.cx(q[3],q[2])
qc.tdg(q[2])
qc.cx(q[4],q[2])
qc.t(q[2])
qc.cx(q[3],q[2])
qc.tdg(q[2])
qc.cx(q[4],q[2])
qc.t(q[2])
qc.tdg(q[3])
qc.h(q[2])
qc.barrier()
qc.h(q[3])
qc.h(q[4])
qc.cx(q[3],q[4])
qc.h(q[3])
qc.h(q[4])
qc.tdg(q[3])
qc.barrier()
qc.h(q[3])
qc.h(q[4])
qc.cx(q[3],q[4])
qc.h(q[3])
qc.h(q[4])
qc.s(q[3])
qc.t(q[4])
qc.barrier()
qc.cx(q[2],q[1])
qc.tdg(q[1])
qc.cx(q[2],q[1])
qc.t(q[1])
qc.t(q[2])
qc.barrier()
qc.h(q[3])
qc.h(q[4])
qc.cx(q[3],q[4])
qc.h(q[3])
qc.h(q[4])
qc.barrier()
qc.draw()
qc.cx(q[2],q[1])
qc.h(q[1])
qc.h(q[2])
qc.cx(q[2],q[1])
qc.h(q[1])
qc.h(q[2])
qc.cx(q[2],q[1])
qc.cx(q[3],q[2])
qc.u1(pi/8, q[2])
qc.cx(q[3],q[2])
qc.u1(-pi/8, q[2])
qc.u1(-pi/8,q[3])
qc.barrier()
qc.h(q[3])
qc.h(q[4])
qc.cx(q[3],q[4])
qc.h(q[3])
qc.h(q[4])
qc.barrier()
qc.cx(q[3],q[2])
qc.u1(-pi/8,q[2])
qc.cx(q[3],q[2])
qc.u1(pi/8,q[2])
qc.u1(pi/8,q[3])
qc.cx(q[4],q[2])
qc.u1(-pi/8,q[2])
qc.cx(q[4],q[2])
qc.u1(pi/8,q[2])
qc.u1(-pi/8,q[4])
qc.barrier()
qc.cx(q[2],q[1])
qc.h(q[1])
qc.h(q[2])
qc.cx(q[2],q[1])
qc.h(q[1])
qc.h(q[2])
qc.cx(q[2],q[1])
qc.draw()
qc.barrier()
qc.barrier()
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
qc.x(q[4])
qc.barrier()
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
qc.h(q[4])
qc.draw()
qc.barrier()
qc.measure(q[1], c[1])
qc.measure(q[2], c[2])
qc.measure(q[3], c[3])
qc.measure(q[4], c[4])
|
https://github.com/Fergus-Hayes/qiskit_tools
|
Fergus-Hayes
|
from qiskit.utils import algorithm_globals
from qiskit import QuantumCircuit, Aer, execute
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
from qiskit_machine_learning.connectors import TorchConnector
from qiskit_machine_learning.neural_networks import SamplerQNN
from torch import nn
from torch.optim import Adam
import torch, time, argparse, sys
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime
from tqdm import tqdm
matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.family'] = 'STIXGeneral'
width=0.75
color='black'
fontsize=28
ticksize=22
figsize=(10,10)
# For this example, I have chosen a power-law with power -7/3
def targ_prob(xs):
px = xs**(-7./3)
return px/np.sum(px)
# Set the number of qubits
n = 4
# Number of dimensions (currently hard coded to 1 but can be expanded)
num_dim = 1
# Number of evaluation points
num_discrete_values = 2**n
# Range of x and the intervals between points
xmin, xmax = 40., 168.
dx = (xmax-xmin)/num_discrete_values
# Full set of x values
xs = np.arange(xmin, xmax, dx)
# Evaluate the target distribution over this range
prob_data = targ_prob(xs)
coords = np.linspace(-2, 2, num_discrete_values)
grid_elements = np.expand_dims(coords,axis=1)
# Set the number of samples S we wish to take from the PQC and target distribution
shots=10000
# Set the random seed used in the simulation (the outcome is highly sensitive to this)
rseed = 1696004649
# Uncomment line below to change the random seed for the training
#rseed = int(datetime.now().timestamp())
algorithm_globals.random_seed = rseed
_ = torch.manual_seed(rseed)
# Define the sampler object
sampler = Sampler(options={"shots": shots, "seed": algorithm_globals.random_seed})
qc = QuantumCircuit(n)
# Begin by initiallising the qubits in an equal superposition
qc.h(qc.qubits);
# Set the number of layers L
reps = 12
ansatz = RealAmplitudes(n, reps=reps)
qc.compose(ansatz, inplace=True)
def create_generator() -> TorchConnector:
qnn = SamplerQNN(
circuit=qc,
sampler=sampler,
input_params=[],
weight_params=qc.parameters,
sparse=False,
)
initial_weights = algorithm_globals.random.random(qc.num_parameters)
return TorchConnector(qnn, initial_weights)
class Discriminator(nn.Module):
def __init__(self, input_size):
super(Discriminator, self).__init__()
self.linear_input = nn.Linear(input_size, 20)
self.leaky_relu = nn.LeakyReLU(0.2)
self.linear20 = nn.Linear(20, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, input: torch.Tensor) -> torch.Tensor:
x = self.linear_input(input)
x = self.leaky_relu(x)
x = self.linear20(x)
x = self.sigmoid(x)
return x
generator = create_generator()
discriminator = Discriminator(num_dim)
def adversarial_loss(input, target, w):
bce_loss = target * torch.log(input) + (1 - target) * torch.log(1 - input)
weighted_loss = w * bce_loss
total_loss = -torch.sum(weighted_loss)
return total_loss
lr=0.01
b1=0.7
b2=0.999
generator_optimizer = Adam(generator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005)
discriminator_optimizer = Adam(discriminator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005)
generator_loss_values = []
discriminator_loss_values = []
entropy_values = []
# Set the number of epochs
n_epochs=1000
num_qnn_outputs = num_discrete_values**num_dim
# Resume training if already performed some iterations
n_epochs = n_epochs-len(entropy_values)
start = time.time()
for epoch in tqdm(range(n_epochs)):
# Define torch target objects
valid = torch.ones(num_qnn_outputs, 1, dtype=torch.float)
fake = torch.zeros(num_qnn_outputs, 1, dtype=torch.float)
# Define torch tensor representing the target probability distribution
real_dist = torch.tensor(prob_data, dtype=torch.float).reshape(-1, 1)
# Define torch tensor representing the grid over which samples are taken
samples = torch.tensor(grid_elements, dtype=torch.float)
disc_value = discriminator(samples)
# Generate data
gen_dist = generator(torch.tensor([])).reshape(-1, 1)
# Train generator
generator_optimizer.zero_grad()
generator_loss = adversarial_loss(disc_value, valid, gen_dist)
# store for plotting
generator_loss_values.append(generator_loss.detach().item())
generator_loss.backward(retain_graph=True)
generator_optimizer.step()
# Train Discriminator
discriminator_optimizer.zero_grad()
real_loss = adversarial_loss(disc_value, valid, real_dist)
fake_loss = adversarial_loss(disc_value, fake, gen_dist.detach())
discriminator_loss = (real_loss + fake_loss) / 2
# Store for plotting
discriminator_loss_values.append(discriminator_loss.detach().item())
discriminator_loss.backward()
discriminator_optimizer.step()
# Retreive trained parameters
with torch.no_grad():
generated_weights = generator.weight.detach().numpy().reshape((reps+1,n))
# Build circuit to execute given trained parameters
circ = QuantumCircuit(n)
circ.h(circ.qubits)
# Implement parameterised quantum circuit equvalent to RealAmplitude
for rep in np.arange(reps+1):
for i in np.arange(n):
circ.ry(generated_weights[rep,i],circ.qubits[i])
for i in np.arange(n):
if i!=n-1 and rep!=reps:
circ.cx(circ.qubits[i], circ.qubits[i+1])
# Produce resulting state vector
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
state_vector = np.asarray(result.get_statevector())
# Calculate value equivalent to mismatch from fidelity
entropy_value = 1-np.sqrt(np.abs(np.dot(np.sqrt(prob_data),np.conjugate(state_vector)))**2)
entropy_values.append(entropy_value)
print(np.round(100.*(epoch/n_epochs),2),'%','Mismatch:',"{:.2e}".format(entropy_value),'Generator loss:', np.round(generator_loss_values[-1],2), 'Discriminator loss:', np.round(discriminator_loss_values[-1],2))
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} sec")
fig = plt.figure(figsize=np.array(figsize)*[1,2])
ax = fig.add_subplot(211)
plt.plot(generator_loss_values, lw=2, color='black')
plt.plot(discriminator_loss_values, lw=2, color='grey')
ax.set_ylabel('Loss function', fontsize=fontsize);
ax.tick_params(axis='both', labelsize=ticksize);
ax = fig.add_subplot(212)
plt.plot(np.log10(entropy_values), lw=2, color='black')
ax.set_ylabel(r'log$_{10}(1-\sqrt{\mathcal{F}})$', fontsize=fontsize);
ax.set_xlabel('Iterations', fontsize=fontsize);
ax.tick_params(axis='both', labelsize=ticksize);
with torch.no_grad():
generated_weights = generator.weight.detach().numpy().reshape((reps+1,n))
circ = QuantumCircuit(n)
circ.h(circ.qubits)
for rep in np.arange(reps+1):
for i in np.arange(n):
circ.ry(generated_weights[rep,i],circ.qubits[i])
for i in np.arange(n):
if i!=n-1 and rep!=reps:
circ.cx(circ.qubits[i], circ.qubits[i+1])
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
state_vector = np.asarray(result.get_statevector())
fidelity = np.abs(np.dot(np.sqrt(prob_data),np.conjugate(state_vector)))**2
mismatch = 1. - np.sqrt(fidelity)
print('Fidelity:', fidelity, 'Mismatch:', mismatch)
target_state = np.sqrt(targ_prob(xs))
fig, ax = plt.subplots(2, 1, figsize=figsize, gridspec_kw={'height_ratios': [1.5, 1]})
color1 = 'black'
color2 = 'grey'
ax[0].scatter(xs, state_vector.real, color=color1, lw=2)
ax[0].plot(xs, state_vector.real, color=color1, ls='-', lw=1)
ax[0].plot(xs, target_state, color=color1, ls='--', lw=2)
ax[0].tick_params(axis='both', labelsize=ticksize)
ax[1].set_xlabel(r'$x$', fontsize=fontsize)
ax[0].set_ylabel(r'Amplitude', fontsize=fontsize)
ax[0].set_xlim(xmin-1,xmax+1)
ax[0].set_xticks([])
ax[1].scatter(xs, state_vector.real-target_state.real, color=color1, lw=2)
ax[1].set_ylabel(r'$\Delta$ Amplitude', fontsize=fontsize)
ax[1].tick_params(axis='both', labelsize=ticksize)
ax[1].set_xlim(xmin-1,xmax+1)
fig.tight_layout()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the EchoRZXWeylDecomposition pass"""
import unittest
from math import pi
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import (
EchoRZXWeylDecomposition,
)
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeParis
import qiskit.quantum_info as qi
from qiskit.quantum_info.synthesis.two_qubit_decompose import (
TwoQubitWeylDecomposition,
)
class TestEchoRZXWeylDecomposition(QiskitTestCase):
"""Tests the EchoRZXWeylDecomposition pass."""
def setUp(self):
super().setUp()
self.backend = FakeParis()
self.inst_map = self.backend.defaults().instruction_schedule_map
def assertRZXgates(self, unitary_circuit, after):
"""Check the number of rzx gates"""
alpha = TwoQubitWeylDecomposition(unitary_circuit).a
beta = TwoQubitWeylDecomposition(unitary_circuit).b
gamma = TwoQubitWeylDecomposition(unitary_circuit).c
expected_rzx_number = 0
if not alpha == 0:
expected_rzx_number += 2
if not beta == 0:
expected_rzx_number += 2
if not gamma == 0:
expected_rzx_number += 2
circuit_rzx_number = QuantumCircuit.count_ops(after)["rzx"]
self.assertEqual(expected_rzx_number, circuit_rzx_number)
@staticmethod
def count_gate_number(gate, circuit):
"""Count the number of a specific gate type in a circuit"""
if gate not in QuantumCircuit.count_ops(circuit):
gate_number = 0
else:
gate_number = QuantumCircuit.count_ops(circuit)[gate]
return gate_number
def test_rzx_number_native_weyl_decomposition(self):
"""Check the number of RZX gates for a hardware-native cx"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
unitary_circuit = qi.Operator(circuit).data
after = EchoRZXWeylDecomposition(self.inst_map)(circuit)
unitary_after = qi.Operator(after).data
self.assertTrue(np.allclose(unitary_circuit, unitary_after))
# check whether the after circuit has the correct number of rzx gates.
self.assertRZXgates(unitary_circuit, after)
def test_h_number_non_native_weyl_decomposition_1(self):
"""Check the number of added Hadamard gates for a native and non-native rzz gate"""
theta = pi / 11
qr = QuantumRegister(2, "qr")
# rzz gate in native direction
circuit = QuantumCircuit(qr)
circuit.rzz(theta, qr[0], qr[1])
# rzz gate in non-native direction
circuit_non_native = QuantumCircuit(qr)
circuit_non_native.rzz(theta, qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = EchoRZXWeylDecomposition(self.inst_map)
after = dag_to_circuit(pass_.run(dag))
dag_non_native = circuit_to_dag(circuit_non_native)
pass_ = EchoRZXWeylDecomposition(self.inst_map)
after_non_native = dag_to_circuit(pass_.run(dag_non_native))
circuit_rzx_number = self.count_gate_number("rzx", after)
circuit_h_number = self.count_gate_number("h", after)
circuit_non_native_h_number = self.count_gate_number("h", after_non_native)
# for each pair of rzx gates four hadamard gates have to be added in
# the case of a non-hardware-native directed gate.
self.assertEqual(
(circuit_rzx_number / 2) * 4, circuit_non_native_h_number - circuit_h_number
)
def test_h_number_non_native_weyl_decomposition_2(self):
"""Check the number of added Hadamard gates for a swap gate"""
qr = QuantumRegister(2, "qr")
# swap gate in native direction.
circuit = QuantumCircuit(qr)
circuit.swap(qr[0], qr[1])
# swap gate in non-native direction.
circuit_non_native = QuantumCircuit(qr)
circuit_non_native.swap(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = EchoRZXWeylDecomposition(self.inst_map)
after = dag_to_circuit(pass_.run(dag))
dag_non_native = circuit_to_dag(circuit_non_native)
pass_ = EchoRZXWeylDecomposition(self.inst_map)
after_non_native = dag_to_circuit(pass_.run(dag_non_native))
circuit_rzx_number = self.count_gate_number("rzx", after)
circuit_h_number = self.count_gate_number("h", after)
circuit_non_native_h_number = self.count_gate_number("h", after_non_native)
# for each pair of rzx gates four hadamard gates have to be added in
# the case of a non-hardware-native directed gate.
self.assertEqual(
(circuit_rzx_number / 2) * 4, circuit_non_native_h_number - circuit_h_number
)
def test_weyl_decomposition_gate_angles(self):
"""Check the number and angles of the RZX gates for different gates"""
thetas = [pi / 9, 2.1, -0.2]
qr = QuantumRegister(2, "qr")
circuit_rxx = QuantumCircuit(qr)
circuit_rxx.rxx(thetas[0], qr[1], qr[0])
circuit_ryy = QuantumCircuit(qr)
circuit_ryy.ryy(thetas[1], qr[0], qr[1])
circuit_rzz = QuantumCircuit(qr)
circuit_rzz.rzz(thetas[2], qr[1], qr[0])
circuits = [circuit_rxx, circuit_ryy, circuit_rzz]
for circuit in circuits:
unitary_circuit = qi.Operator(circuit).data
dag = circuit_to_dag(circuit)
pass_ = EchoRZXWeylDecomposition(self.inst_map)
after = dag_to_circuit(pass_.run(dag))
dag_after = circuit_to_dag(after)
unitary_after = qi.Operator(after).data
# check whether the unitaries are equivalent.
self.assertTrue(np.allclose(unitary_circuit, unitary_after))
# check whether the after circuit has the correct number of rzx gates.
self.assertRZXgates(unitary_circuit, after)
alpha = TwoQubitWeylDecomposition(unitary_circuit).a
rzx_angles = []
for node in dag_after.two_qubit_ops():
if node.name == "rzx":
rzx_angle = node.op.params[0]
# check whether the absolute values of the RZX gate angles
# are equivalent to the corresponding Weyl parameter.
self.assertAlmostEqual(np.abs(rzx_angle), alpha)
rzx_angles.append(rzx_angle)
# check whether the angles of every RZX gate pair of an echoed RZX gate
# have opposite signs.
for idx in range(1, len(rzx_angles), 2):
self.assertAlmostEqual(rzx_angles[idx - 1], -rzx_angles[idx])
def test_weyl_unitaries_random_circuit(self):
"""Weyl decomposition for a random two-qubit circuit."""
theta = pi / 9
epsilon = 5
delta = -1
eta = 0.2
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
# random two-qubit circuit.
circuit.rzx(theta, 0, 1)
circuit.rzz(epsilon, 0, 1)
circuit.rz(eta, 0)
circuit.swap(1, 0)
circuit.h(0)
circuit.rzz(delta, 1, 0)
circuit.swap(0, 1)
circuit.cx(1, 0)
circuit.swap(0, 1)
circuit.h(1)
circuit.rxx(theta, 0, 1)
circuit.ryy(theta, 1, 0)
circuit.ecr(0, 1)
unitary_circuit = qi.Operator(circuit).data
dag = circuit_to_dag(circuit)
pass_ = EchoRZXWeylDecomposition(self.inst_map)
after = dag_to_circuit(pass_.run(dag))
unitary_after = qi.Operator(after).data
self.assertTrue(np.allclose(unitary_circuit, unitary_after))
if __name__ == "__main__":
unittest.main()
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
%%capture
%pip install qiskit
%pip install qiskit_ibm_provider
%pip install qiskit-aer
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer
from qiskit_ibm_provider import IBMProvider
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.circuit.library import C3XGate
# Importing matplotlib
import matplotlib.pyplot as plt
# Importing Numpy, Cmath and math
import numpy as np
import os, math, cmath
from numpy import pi
# Other imports
from IPython.display import display, Math, Latex
# Specify the path to your env file
env_file_path = 'config.env'
# Load environment variables from the file
os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#'))
# Load IBM Provider API KEY
IBMP_API_KEY = os.environ.get('IBMP_API_KEY')
# Loading your IBM Quantum account(s)
IBMProvider.save_account(IBMP_API_KEY, overwrite=True)
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
qc_b1 = QuantumCircuit(2, 2)
qc_b1.h(0)
qc_b1.cx(0, 1)
qc_b1.draw(output='mpl', style="iqp")
sv = backend.run(qc_b1).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.x(0)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.z(0)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.x(1)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.x(0)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.x(0)
qc_b4.h(0)
qc_b4.x(1)
qc_b4.cx(0, 1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.h(0)
qc_b4.cx(0, 1)
qc_b4.x(0)
qc_b4.z(1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
def sv_latex_from_qc(qc, backend):
sv = backend.run(qc).result().get_statevector()
return sv.draw(output='latex')
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(3)
sv_latex_from_qc(qc_ej2, backend)
def circuit_adder (num):
if num<1 or num>8:
raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo.
# Definición del circuito base que vamos a construir
qreg_q = QuantumRegister(4, 'q')
creg_c = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
qbit_position = 0
for element in reversed(np.binary_repr(num)):
if (element=='1'):
circuit.barrier()
match qbit_position:
case 0: # +1
circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]])
circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
circuit.x(qreg_q[0])
case 1: # +2
circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.x(qreg_q[1])
case 2: # +4
circuit.cx(qreg_q[2], qreg_q[3])
circuit.x(qreg_q[2])
case 3: # +8
circuit.x(qreg_q[3])
qbit_position+=1
return circuit
add_3 = circuit_adder(3)
add_3.draw(output='mpl', style="iqp")
qc_test_2 = QuantumCircuit(4, 4)
qc_test_2.x(1)
qc_test_2_plus_3 = qc_test_2.compose(add_3)
qc_test_2_plus_3.draw(output='mpl', style="iqp")
sv_latex_from_qc(qc_test_2_plus_3, backend)
qc_test_7 = QuantumCircuit(4, 4)
qc_test_7.x(0)
qc_test_7.x(1)
qc_test_7.x(2)
qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8))
sv_latex_from_qc(qc_test_7_plus_8, backend)
#qc_test_7_plus_8.draw()
theta = 6.544985
phi = 2.338741
lmbda = 0
alice_1 = 0
alice_2 = 1
bob_1 = 2
qr_alice = QuantumRegister(2, 'Alice')
qr_bob = QuantumRegister(1, 'Bob')
cr = ClassicalRegister(3, 'c')
qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr)
qc_ej3.barrier(label='1')
qc_ej3.u(theta, phi, lmbda, alice_1);
qc_ej3.barrier(label='2')
qc_ej3.h(alice_2)
qc_ej3.cx(alice_2, bob_1);
qc_ej3.barrier(label='3')
qc_ej3.cx(alice_1, alice_2)
qc_ej3.h(alice_1);
qc_ej3.barrier(label='4')
qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]);
qc_ej3.barrier(label='5')
qc_ej3.x(bob_1).c_if(alice_2, 1)
qc_ej3.z(bob_1).c_if(alice_1, 1)
qc_ej3.measure(bob_1, bob_1);
qc_ej3.draw(output='mpl', style="iqp")
result = backend.run(qc_ej3, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
sv_0 = np.array([1, 0])
sv_1 = np.array([0, 1])
def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10):
"""
Check if the given numerical value corresponds to a symbolic constant within a specified tolerance.
Parameters:
- value (float): The numerical value to check.
- symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations.
Defaults to {1/np.sqrt(2): '1/√2'}.
- tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10.
Returns:
str or float: If a match is found, returns the symbolic representation as a string
(prefixed with '-' if the value is negative); otherwise, returns the original value.
"""
for constant, symbol in symbolic_constants.items():
if np.isclose(abs(value), constant, atol=tolerance):
return symbol if value >= 0 else '-' + symbol
return value
def array_to_dirac_notation(array, tolerance=1e-10):
"""
Convert a complex-valued array representing a quantum state in superposition
to Dirac notation.
Parameters:
- array (numpy.ndarray): The complex-valued array representing
the quantum state in superposition.
- tolerance (float): Tolerance for considering amplitudes as negligible.
Returns:
str: The Dirac notation representation of the quantum state.
"""
# Ensure the statevector is normalized
array = array / np.linalg.norm(array)
# Get the number of qubits
num_qubits = int(np.log2(len(array)))
# Find indices where amplitude is not negligible
non_zero_indices = np.where(np.abs(array) > tolerance)[0]
# Generate Dirac notation terms
terms = [
(find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b"))
for i in non_zero_indices
]
# Format Dirac notation
dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms])
return dirac_notation
def array_to_matrix_representation(array):
"""
Convert a one-dimensional array to a column matrix representation.
Parameters:
- array (numpy.ndarray): The one-dimensional array to be converted.
Returns:
numpy.ndarray: The column matrix representation of the input array.
"""
# Replace symbolic constants with their representations
matrix_representation = np.array([find_symbolic_representation(value) or value for value in array])
# Return the column matrix representation
return matrix_representation.reshape((len(matrix_representation), 1))
def array_to_dirac_and_matrix_latex(array):
"""
Generate LaTeX code for displaying both the matrix representation and Dirac notation
of a quantum state.
Parameters:
- array (numpy.ndarray): The complex-valued array representing the quantum state.
Returns:
Latex: A Latex object containing LaTeX code for displaying both representations.
"""
matrix_representation = array_to_matrix_representation(array)
latex = "Matrix representation\n\\begin{bmatrix}\n" + \
"\\\\\n".join(map(str, matrix_representation.flatten())) + \
"\n\\end{bmatrix}\n"
latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}'
return Latex(latex)
sv_b1 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b2 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b3 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b4 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXDebugging())
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
import scipy as sci
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
N = 3
q = QuantumRegister(N, name='q')
qc = QuantumCircuit(q,name='qc')
for i in range(N):
qc.h(q[i])
oq.Wavefunction(qc);
N = 3
q = QuantumRegister(N, name='q')
c = ClassicalRegister(N, name = 'c')
qc = QuantumCircuit(q,c,name='qc')
for i in range(N):
qc.h(q[i])
qc.measure(q,c)
oq.Measurement(qc,shots=1000)
q = QuantumRegister(2, name='q')
G_qc = QuantumCircuit(q,name='qc')
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.cz(q[0],q[1])
print('___________Initial State____________')
oq.Wavefunction(G_qc)
print('\nX_Transformation: |00> <----> |11>')
oq.X_Transformation(G_qc, q, [0,0])
print('\n__________ After X(0) + X(1) ______')
oq.Wavefunction(G_qc);
q = QuantumRegister(2, name='q')
G_qc = QuantumCircuit(q,name='qc')
marked=[0,1]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.cz(q[0],q[1])
G_qc.x(q[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc)
oq.X_Transformation(G_qc, q, marked)
print('\n__________ X(0) ______')
oq.Wavefunction(G_qc)
oq.X_Transformation(G_qc,q, marked)
print('\n__________ X(0) ______')
oq.Wavefunction(G_qc);
q = QuantumRegister(3, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, n_anc,name='qc')
marked = [0,1,0]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.h(q[2])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,False,False])
G_qc.h(anc[0])
oq.X_Transformation(G_qc,q,marked)
print('\n___________H(q[3]) + X_Transformation____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,True,False])
oq.n_NOT(G_qc,q, anc[0],n_anc)
print('\n___________n_NOT____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,True,False])
oq.X_Transformation(G_qc,q,marked)
G_qc.h(anc[0])
print('\n___________X_Transformation + H(q[3])____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,True,False]);
q = QuantumRegister(3, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, n_anc,name='qc')
marked = [0,1,0]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.h(q[2])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,False,False])
oq.Grover_Oracle(marked, G_qc, q, anc, n_anc)
print('\n___________Final State____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,True,False]);
q = QuantumRegister(2, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, name='qc')
marked = [1,0]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
oq.Grover_Oracle(marked, G_qc, q, anc, n_anc)
print('\n___________Grover Oracle: ',marked,'____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
G_qc.h(q[0])
G_qc.h(q[1])
oq.Grover_Oracle([0,0], G_qc, q, anc, n_anc)
G_qc.h(q[0])
G_qc.h(q[1])
print('\n___________After Grover Diffusion____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False]);
q = QuantumRegister(2, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, name='qc')
marked = [1,0]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
oq.Grover_Oracle(marked, G_qc, q, anc, n_anc)
print('\n___________Grover Oracle: ',marked,'____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
G_qc.h(q[0])
G_qc.h(q[1])
print('\n___________H^2 transformation____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
oq.Grover_Oracle([0,0], G_qc, q, anc, n_anc)
print('\n___________Grover Oracle: [0, 0]____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
G_qc.h(q[0])
G_qc.h(q[1])
print('\n___________H^2 transformation____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False]);
q = QuantumRegister(2, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, name='qc')
marked = [1,0]
G_qc.h(q[0])
G_qc.id(q[1])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
G_qc.h(q[0])
G_qc.h(q[1])
oq.Grover_Oracle([0,0], G_qc, q, anc, n_anc)
G_qc.h(q[0])
G_qc.h(q[1])
print('\n___________After Grover____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False]);
q = QuantumRegister(2, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, name='qc')
marked = [1,0]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
oq.Grover_Oracle(marked, G_qc, q, anc, n_anc)
print('\n___________Grover Oracle: |01>____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
G_qc.h(q[0])
G_qc.h(q[1])
print('\n___________H^2 transformation____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
oq.Grover_Oracle([0,1], G_qc, q, anc, n_anc)
oq.Grover_Oracle([1,0], G_qc, q, anc, n_anc)
oq.Grover_Oracle([1,1], G_qc, q, anc, n_anc)
print('\n___________Flipping the sign on: |01> |10> |11>____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
G_qc.h(q[0])
G_qc.h(q[1])
print('\n___________H^2 transformation____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False]);
q = QuantumRegister(3, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, n_anc,name='qc')
marked = [1,1,0]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.h(q[2])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,False,False])
iterations = 3
for i in range(iterations):
oq.Grover_Oracle(marked, G_qc, q, anc, n_anc)
oq.Grover_Diffusion(marked, G_qc, q, anc, n_anc)
print('\n___________',i+1,' Grover iteration____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,False,False])
Q = 4
marked = [0,1,1,0]
G_qc, q, an1, an2, c = oq.Grover(Q, marked)
oq.Wavefunction(G_qc, systems=[Q,1,Q-2], show_systems=[True,False,False], column = True)
print(' ')
G_qc.measure(q,c)
print('\n_________Measurement Results_________')
oq.Measurement(G_qc, shots = 100);
|
https://github.com/tsirlucas/quantum-realtime-comm
|
tsirlucas
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/quantumofme/pavia-qiskit-tutorials
|
quantumofme
|
# Welcome to qiskit
import qiskit as qk
myvers = qk.__version__
print("You are using qiskit version", myvers)
print("More details on qiskit components:",qk.__qiskit_version__)
my_token = ''
# Set up your credentials for the IBM Quantum Experience in one-time mode (easiest)
ibmq_provider = qk.IBMQ.enable_account(my_token)
# Check the available local backends
qk.Aer.backends()
# Check the available cloud-based backends
ibmq_provider.backends()
qr = qk.QuantumRegister(2,name='qreg')
cr = qk.ClassicalRegister(2,name='creg')
qc = qk.QuantumCircuit(qr,cr,name='test_circ') # A QuantumCircuit is composed of quantum and classical registers
qc.x(qr[0])
for indx in range(2):
qc.h(qr[indx])
qc.cx(qr[0],qr[1]) # The first entry is the control qubit, the second entry is the target qubit for the CNOT
qc.measure(qr[0],cr[0])
qc.measure(qr[1],cr[1])
qc.draw()
qc.draw(output='mpl')
backend1 = qk.Aer.get_backend('qasm_simulator')
job1 = qk.execute(qc, backend1, shots=1024) # The shots are the number of times the circuit will be run.
# More shots will mean better reconstruction of the measurement
# statistics, but also longer execution times
result1 = job1.result()
counts1 = result1.get_counts(qc)
print(counts1)
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts1)
backend2 = ibmq_provider.get_backend('ibmqx2')
job2 = qk.execute(qc, backend=backend2, shots=1024)
from qiskit.tools.monitor import job_monitor
job_monitor(job2, interval=5)
result2 = job2.result()
counts2 = result2.get_counts(qc)
print(counts2)
plot_histogram(counts2)
jobID = job2.job_id()
print(jobID)
job_get = backend2.retrieve_job(jobID)
counts_get = job_get.result().get_counts()
print(counts_get)
plot_histogram([counts1,counts_get])
from qiskit.tools.visualization import plot_gate_map
print('List of pairwise connection between qubits available for CNOT operations:\n',
backend2.configuration().coupling_map)
plot_gate_map(backend2)
custom_layout = [3,4] # abstract qr[0] will be mapped in q[3] on the device
# abstract qr[1] will be mapped in q[4] on the device
compiled_qc = qk.transpile(qc,backend = backend2,initial_layout = custom_layout,optimization_level=0)
compiled_qc.draw()
from qiskit.tools.visualization import plot_circuit_layout
plot_circuit_layout(compiled_qc,backend2)
compiled_qobj = qk.assemble(compiled_qc,shots=1024)
job3 = backend2.run(compiled_qobj)
job4 = qk.execute(qc,backend=backend2,shots=1024,initial_layout=custom_layout,optimization_level=0)
custom_layout_bad = [1,3] # There is no 1 -> 3 connection on the device
compiled_qc_bad = qk.transpile(qc, backend = backend2, initial_layout = custom_layout_bad,optimization_level=0)
compiled_qc_bad.draw(output='mpl')
plot_circuit_layout(compiled_qc_bad,backend2)
qr = qk.QuantumRegister(5,name='qreg')
cr = qk.ClassicalRegister(5,name='creg')
qc = qk.QuantumCircuit(qr,cr,name='exercise')
qc.h(qr[0])
for i in range(1,5):
qc.cx(qr[0],qr[i])
qc.draw(output='mpl')
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A module of magic functions"""
import time
import threading
from IPython.display import display # pylint: disable=import-error
from IPython.core import magic_arguments # pylint: disable=import-error
from IPython.core.magic import cell_magic, Magics, magics_class # pylint: disable=import-error
try:
import ipywidgets as widgets # pylint: disable=import-error
except ImportError:
raise ImportError('These functions need ipywidgets. '
'Run "pip install ipywidgets" before.')
import qiskit
from qiskit.tools.events.progressbar import TextProgressBar
from .progressbar import HTMLProgressBar
def _html_checker(job_var, interval, status, header,
_interval_set=False):
"""Internal function that updates the status
of a HTML job monitor.
Args:
job_var (BaseJob): The job to keep track of.
interval (int): The status check interval
status (widget): HTML ipywidget for output ot screen
header (str): String representing HTML code for status.
_interval_set (bool): Was interval set by user?
"""
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
status.value = header % (job_status_msg)
while job_status_name not in ['DONE', 'CANCELLED']:
time.sleep(interval)
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
if job_status_name == 'ERROR':
break
else:
if job_status_name == 'QUEUED':
job_status_msg += ' (%s)' % job_var.queue_position()
if not _interval_set:
interval = max(job_var.queue_position(), 2)
else:
if not _interval_set:
interval = 2
status.value = header % (job_status_msg)
status.value = header % (job_status_msg)
@magics_class
class StatusMagic(Magics):
"""A class of status magic functions.
"""
@cell_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument(
'-i',
'--interval',
type=float,
default=None,
help='Interval for status check.'
)
def qiskit_job_status(self, line='', cell=None):
"""A Jupyter magic function to check the status of a Qiskit job instance.
"""
args = magic_arguments.parse_argstring(self.qiskit_job_status, line)
if args.interval is None:
args.interval = 2
_interval_set = False
else:
_interval_set = True
# Split cell lines to get LHS variables
cell_lines = cell.split('\n')
line_vars = []
for cline in cell_lines:
if '=' in cline and '==' not in cline:
line_vars.append(cline.replace(' ', '').split('=')[0])
elif '.append(' in cline:
line_vars.append(cline.replace(' ', '').split('(')[0])
# Execute the cell
self.shell.ex(cell)
# Look for all vars that are BaseJob instances
jobs = []
for var in line_vars:
iter_var = False
if '#' not in var:
# The line var is a list or array, but we cannot parse the index
# so just iterate over the whole array for jobs.
if '[' in var:
var = var.split('[')[0]
iter_var = True
elif '.append' in var:
var = var.split('.append')[0]
iter_var = True
if iter_var:
for item in self.shell.user_ns[var]:
if isinstance(item, qiskit.providers.basejob.BaseJob):
jobs.append(item)
else:
if isinstance(self.shell.user_ns[var],
qiskit.providers.basejob.BaseJob):
jobs.append(self.shell.user_ns[var])
# Must have one job class
if not any(jobs):
raise Exception(
"Cell must contain at least one variable of BaseJob type.")
# List index of job if checking status of multiple jobs.
multi_job = False
if len(jobs) > 1:
multi_job = True
job_checkers = []
# Loop over every BaseJob that was found.
for idx, job_var in enumerate(jobs):
style = "font-size:16px;"
if multi_job:
idx_str = '[%s]' % idx
else:
idx_str = ''
header = "<p style='{style}'>Job Status {id}: %s </p>".format(id=idx_str,
style=style)
status = widgets.HTML(
value=header % job_var.status().value)
thread = threading.Thread(target=_html_checker, args=(job_var, args.interval,
status, header,
_interval_set))
thread.start()
job_checkers.append(status)
# Group all HTML widgets into single vertical layout
box = widgets.VBox(job_checkers)
display(box)
@magics_class
class ProgressBarMagic(Magics):
"""A class of progress bar magic functions.
"""
@cell_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument(
'-t',
'--type',
type=str,
default='html',
help="Type of progress bar, 'html' or 'text'."
)
def qiskit_progress_bar(self, line='', cell=None): # pylint: disable=W0613
"""A Jupyter magic function to generate progressbar.
"""
args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line)
if args.type == 'html':
HTMLProgressBar()
elif args.type == 'text':
TextProgressBar()
else:
raise qiskit.QiskitError('Invalid progress bar type.')
self.shell.ex(cell)
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.enable_account('Enter API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(2,'q')
c = ClassicalRegister(2,'c')
circuit = QuantumCircuit(q,c)
circuit.x(q[0])
circuit.ch(q[0], q[1]);
circuit.measure(q,c)
print(circuit)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
|
https://github.com/bartubisgin/QSVTinQiskit-2021-Europe-Hackathon-Winning-Project-
|
bartubisgin
|
import warnings; warnings.simplefilter('ignore')
# Importing the necessary libraries
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries
from qiskit import *
from qiskit.quantum_info import Statevector
from qiskit.tools.jupyter import *
from qiskit.visualization import *
#we have 2 system qubits
system_qubits = 2
#following the argument above we need 2 additional qubits
nqubits = system_qubits + 2
q = QuantumRegister(nqubits, 'q')
circuit = QuantumCircuit(q)
x = np.linspace(-1, 1)
test = np.polynomial.Chebyshev((0, 0, 0, 1)) # The 3rd Chebyshev polynomial!
y = test(x)
plt.plot(x, y)
# Define projectors.
# Note that p_left is actually p_right from above because the order
# of operations are reversed when equations are turned into circuits
# due to how time-flow is defined in circuit structures
# In the Qiskit implementation qubit indexes start from 0
# and the most significant qubit is the highest index
# keeping this in mind e.g for 4 nqubits = {q0,q1,q2,q3}
# q0 and q1 are the system qubits
# q2 is the signal qubit
# q3 is the ancillary rotation qubit
# nqubits-1 = 4-1 = 3 below, then corresponds to q3
def p_left(q, phi): #right projector
qc = QuantumCircuit(q)
n = q
ctrl_range = list(range(0,n-1))
for qubit in range(n-1): # Implement a simple multi 0-controlled
qc.x(qubit)
qc.mcx(ctrl_range , n-1) # 0-Controlled on all but the last qubits, acts on the last qubit
for qubit in range(n-1):
qc.x(qubit)
#qc.barrier(0, 1, 2, 3)
qc.rz(phi, n-1) # RZ(phi) on the last qubit
#qc.barrier(0, 1, 2, 3)
for qubit in range(n-1): # Reverse the effect of the first multi-control
qc.x(qubit)
qc.mcx(ctrl_range ,n-1)
for qubit in range(n-1):
qc.x(qubit)
p_left_gate = qc.to_gate() # Compiles all this into a gate
p_left_gate.name = "P$_l$(Φ)"
return p_left_gate
def p_right(phi): # Left projector acts just on the signal and the ancillary qubit
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.rz(phi, 1)
qc.cx(0 ,1)
p_right_gate = qc.to_gate()
p_right_gate.name = "P$_r$(Φ)"
return p_right_gate
#Define Oracle and the reverse-gate for
#constructing the dagger later
def U(q):
qc = QuantumCircuit(q)
n = q + 1
for qubit in range(n-2):
qc.h(qubit)
qc.mcx(list(range(0,n-2)), n-2)
U_gate = qc.to_gate()
U_gate.name = "U"
return U_gate
def reverse_gate(gate):
gate_rev = gate.reverse_ops()
gate_rev.name = gate.name + "$^†$"
return gate_rev
#we have 2 system qubits
system_qubits = 2
#following the argument above we need 2 additional qubits
nqubits = system_qubits + 2
q = QuantumRegister(nqubits, 'q')
circuit = QuantumCircuit(q)
d = 3
u = U(nqubits-1)
u_dag = reverse_gate(u) #construct U_dagger
p_right_range = [nqubits-2, nqubits-1] # build the ranges of qubits for gates to act upon
u_range = list(range(0, nqubits-1))
p_left_range = list(range(0, nqubits))
circuit.append(p_left(nqubits, (1-d)*pi), p_left_range) # in general, starting from this line,
circuit.append(u, u_range) # the circuit would iterate over the phases,
# but the phases for pure Cheby are just trivial pi/2
# so we chose to directly putting pi's in here for simplification
for i in range((d-1)//2): # we put pi instead of pi/2 because of how RZ is defined in Qiskit
circuit.append(p_right(pi), p_right_range)
circuit.append(u_dag, u_range)
circuit.append(p_left(nqubits, pi), p_left_range)
circuit.append(u, u_range)
circuit.measure_all()
circuit.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_circuit = transpile(circuit, qasm_sim)
qobj = assemble(transpiled_circuit)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
# We have 2 system qubits
system_qubits = 2
# Following the argument above we need 2 additional qubits
nqubits = system_qubits + 2
q = QuantumRegister(nqubits, 'q')
circuit = QuantumCircuit(q)
############################## d in terms of n!
d = (2*system_qubits) - 1
if system_qubits > 6 and system_qubits < 10:
for i in range(1, system_qubits - 6 + 1):
d += 2 * i
###############################
u = U(nqubits-1)
u_dag = reverse_gate(u)
p_right_range = [nqubits-2, nqubits-1]
u_range = list(range(0, nqubits-1))
p_left_range = list(range(0, nqubits))
circuit.append(p_left(nqubits, (1-d)*pi), p_left_range)
circuit.append(U(nqubits-1), u_range)
for i in range((d-1)//2):
circuit.append(p_right(pi), p_right_range) #debug this, doesnt work just as a 2 qubit gate
circuit.append(u_dag, u_range)
circuit.append(p_left(nqubits,pi), p_left_range)
circuit.append(u, u_range)
circuit.measure_all()
circuit.draw('mpl')
def qsvt_search(target): # target = marked element, is a bit-string!
systemqubits = len(target)
nqubits = systemqubits + 2
q = QuantumRegister(nqubits, 'q')
circuit = QuantumCircuit(q)
d = (2*systemqubits) - 1
if systemqubits > 6 and systemqubits < 10:
for i in range(1, systemqubits - 6 + 1):
d += 2 * i
u = U(nqubits-1)
u_dag = reverse_gate(u)
p_right_range = [nqubits-2, nqubits-1]
u_range = list(range(0, nqubits-1))
p_left_range = list(range(0, nqubits))
circuit.append(p_left(nqubits,(1-d)*pi), p_left_range)
circuit.append(U(nqubits-1), u_range)
for i in range((d-1)//2):
circuit.append(p_right(pi), p_right_range) #debug this, doesnt work just as a 2 qubit gate
circuit.append(u_dag, u_range)
circuit.append(p_left(nqubits,pi), p_left_range)
circuit.append(u, u_range)
for i in range(len(target)): # The operation for acquiring arbitrary marked element
bts = target [::-1] # bitstring is reversed to be compatible with the reverse qubit order in Qiskit
if bts[i] == '0':
circuit.x(i)
circuit.measure_all()
return circuit
circuit_test = qsvt_search('1101')
circuit_test.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_circuit = transpile(circuit_test, qasm_sim)
qobj = assemble(transpiled_circuit)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
qc = qsvt_search('001')
qc.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_circuit = transpile(qc, qasm_sim)
qobj = assemble(transpiled_circuit)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
# We have 4 system qubits
system_qubits = 4
nqubits = system_qubits + 2
q = QuantumRegister(nqubits, 'q')
circuit = QuantumCircuit(q)
d = 3 # set d = something you chose to test different values!
u = U(nqubits-1)
u_dag = reverse_gate(u)
p_right_range = [nqubits-2, nqubits-1]
u_range = list(range(0, nqubits-1))
p_left_range = list(range(0, nqubits))
circuit.append(p_left(nqubits,(1-d)*pi), p_left_range)
circuit.append(U(nqubits-1), u_range)
for i in range((d-1)//2):
circuit.append(p_right(pi), p_right_range) #debug this, doesnt work just as a 2 qubit gate
circuit.append(u_dag, u_range)
circuit.append(p_left(nqubits,pi), p_left_range)
circuit.append(u, u_range)
circuit.measure_all()
circuit.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_circuit = transpile(circuit, qasm_sim)
qobj = assemble(transpiled_circuit)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
qc = qsvt_search('001110')
qc.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_circuit = transpile(qc, qasm_sim)
qobj = assemble(transpiled_circuit)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
qc = qsvt_search('001110110')
qc.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_circuit = transpile(qc, qasm_sim)
qobj = assemble(transpiled_circuit)
results = qasm_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
|
https://github.com/kdk/qiskit-timeline-debugger
|
kdk
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, assemble, transpile
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.providers.ibmq import least_busy
# import basic plot tools
from qiskit.visualization import plot_histogram
n = 2
grover_circuit = QuantumCircuit(n)
def initialize_s(qc, qubits):
"""Apply a H-gate to 'qubits' in qc"""
for q in qubits:
qc.h(q)
return qc
def diffuser(nqubits):
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
# Do multi-controlled-Z gate
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>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
# We will return the diffuser as a gate
U_s = qc.to_gate()
U_s.name = "U$_s$"
return U_s
grover_circuit = initialize_s(grover_circuit, [0,1])
grover_circuit.draw(output="mpl")
grover_circuit.cz(0,1) # Oracle
grover_circuit.draw(output="mpl")
# Diffusion operator (U_s)
grover_circuit.append(diffuser(n),[0,1])
grover_circuit.draw(output="mpl")
sim = Aer.get_backend('aer_simulator')
# we need to make a copy of the circuit with the 'save_statevector'
# instruction to run on the Aer simulator
grover_circuit_sim = grover_circuit.copy()
grover_circuit_sim.save_statevector()
qobj = assemble(grover_circuit_sim)
result = sim.run(qobj).result()
statevec = result.get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
grover_circuit.measure_all()
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(grover_circuit)
result = aer_sim.run(qobj).result()
counts = result.get_counts()
plot_histogram(counts)
nqubits = 4
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
qc.barrier()
# Do multi-controlled-Z gate
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc.h(nqubits-1)
qc.barrier()
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
qc.draw(output="mpl")
from qiskit.circuit import classical_function, Int1
# define a classical function f(x): this returns 1 for the solutions of the problem
# in this case, the solutions are 1010 and 1100
@classical_function
def f(x1: Int1, x2: Int1, x3: Int1, x4: Int1) -> Int1:
return (x1 and not x2 and x3 and not x4) or (x1 and x2 and not x3 and not x4)
nqubits = 4
Uf = f.synth() # turn it into a circuit
oracle = QuantumCircuit(nqubits+1)
oracle.compose(Uf, inplace=True)
oracle.draw(output="mpl")
# We will return the diffuser as a gate
#U_f = oracle.to_gate()
# U_f.name = "U$_f$"
# return U_f
|
https://github.com/AlphaMiyaL/Qiskit-Quantum-Journey
|
AlphaMiyaL
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
secretnumber = '11100011'
circuit = QuantumCircuit(len(secretnumber)+1,len(secretnumber))
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.h(len(secretnumber))
circuit.barrier()
for ii, yesno in enumerate(reversed(secretnumber)):
if yesno == '1':
circuit.cx(ii,len(secretnumber))
circuit.barrier()
circuit.h(range(len(secretnumber)))
circuit.barrier()
circuit.measure(range(len(secretnumber)),range(len(secretnumber)))
circuit.draw(output = 'mpl')
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module
# pylint: disable=attribute-defined-outside-init,unsubscriptable-object
import os
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
class QUEKOTranspilerBench:
params = ([0, 1, 2, 3], [None, "sabre"])
param_names = ["optimization level", "routing/layout method"]
timeout = 600
# pylint: disable=unused-argument
def setup(self, optimization_level, routing_method):
self.rochester_coupling_map = [
[0, 5],
[0, 1],
[1, 2],
[1, 0],
[2, 3],
[2, 1],
[3, 4],
[3, 2],
[4, 6],
[4, 3],
[5, 9],
[5, 0],
[6, 13],
[6, 4],
[7, 16],
[7, 8],
[8, 9],
[8, 7],
[9, 10],
[9, 8],
[9, 5],
[10, 11],
[10, 9],
[11, 17],
[11, 12],
[11, 10],
[12, 13],
[12, 11],
[13, 14],
[13, 12],
[13, 6],
[14, 15],
[14, 13],
[15, 18],
[15, 14],
[16, 19],
[16, 7],
[17, 23],
[17, 11],
[18, 27],
[18, 15],
[19, 20],
[19, 16],
[20, 21],
[20, 19],
[21, 28],
[21, 22],
[21, 20],
[22, 23],
[22, 21],
[23, 24],
[23, 22],
[23, 17],
[24, 25],
[24, 23],
[25, 29],
[25, 26],
[25, 24],
[26, 27],
[26, 25],
[27, 26],
[27, 18],
[28, 32],
[28, 21],
[29, 36],
[29, 25],
[30, 39],
[30, 31],
[31, 32],
[31, 30],
[32, 33],
[32, 31],
[32, 28],
[33, 34],
[33, 32],
[34, 40],
[34, 35],
[34, 33],
[35, 36],
[35, 34],
[36, 37],
[36, 35],
[36, 29],
[37, 38],
[37, 36],
[38, 41],
[38, 37],
[39, 42],
[39, 30],
[40, 46],
[40, 34],
[41, 50],
[41, 38],
[42, 43],
[42, 39],
[43, 44],
[43, 42],
[44, 51],
[44, 45],
[44, 43],
[45, 46],
[45, 44],
[46, 47],
[46, 45],
[46, 40],
[47, 48],
[47, 46],
[48, 52],
[48, 49],
[48, 47],
[49, 50],
[49, 48],
[50, 49],
[50, 41],
[51, 44],
[52, 48],
]
self.tokyo_coupling_map = [
[0, 1],
[1, 2],
[2, 3],
[3, 4],
[0, 5],
[1, 6],
[1, 7],
[2, 6],
[2, 7],
[3, 8],
[3, 9],
[4, 8],
[4, 9],
[5, 6],
[6, 7],
[7, 8],
[8, 9],
[5, 10],
[5, 11],
[6, 10],
[6, 11],
[7, 12],
[7, 13],
[8, 12],
[8, 13],
[9, 14],
[10, 11],
[11, 12],
[12, 13],
[13, 14],
[10, 15],
[11, 16],
[11, 17],
[12, 16],
[12, 17],
[13, 18],
[13, 19],
[14, 18],
[14, 19],
[15, 16],
[16, 17],
[17, 18],
[18, 19],
]
self.sycamore_coupling_map = [
[0, 6],
[1, 6],
[1, 7],
[2, 7],
[2, 8],
[3, 8],
[3, 9],
[4, 9],
[4, 10],
[5, 10],
[5, 11],
[6, 12],
[6, 13],
[7, 13],
[7, 14],
[8, 14],
[8, 15],
[9, 15],
[9, 16],
[10, 16],
[10, 17],
[11, 17],
[12, 18],
[13, 18],
[13, 19],
[14, 19],
[14, 20],
[15, 20],
[15, 21],
[16, 21],
[16, 22],
[17, 22],
[17, 23],
[18, 24],
[18, 25],
[19, 25],
[19, 26],
[20, 26],
[20, 27],
[21, 27],
[21, 28],
[22, 28],
[22, 29],
[23, 29],
[24, 30],
[25, 30],
[25, 31],
[26, 31],
[26, 32],
[27, 32],
[27, 33],
[28, 33],
[28, 34],
[29, 34],
[29, 35],
[30, 36],
[30, 37],
[31, 37],
[31, 38],
[32, 38],
[32, 39],
[33, 39],
[33, 40],
[34, 40],
[34, 41],
[35, 41],
[36, 42],
[37, 42],
[37, 43],
[38, 43],
[38, 44],
[39, 44],
[39, 45],
[40, 45],
[40, 46],
[41, 46],
[41, 47],
[42, 48],
[42, 49],
[43, 49],
[43, 50],
[44, 50],
[44, 51],
[45, 51],
[45, 52],
[46, 52],
[46, 53],
[47, 53],
]
self.basis_gates = ["id", "rz", "sx", "x", "cx"]
self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm"))
self.bigd = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "20QBT_45CYC_.0D1_.1D2_3.qasm")
)
self.bss = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "53QBT_100CYC_QSE_3.qasm")
)
self.bntf = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "54QBT_25CYC_QSE_3.qasm")
)
def track_depth_bntf_optimal_depth_25(self, optimization_level, routing_method):
return transpile(
self.bntf,
coupling_map=self.sycamore_coupling_map,
basis_gates=self.basis_gates,
routing_method=routing_method,
layout_method=routing_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def track_depth_bss_optimal_depth_100(self, optimization_level, routing_method):
return transpile(
self.bss,
coupling_map=self.rochester_coupling_map,
basis_gates=self.basis_gates,
routing_method=routing_method,
layout_method=routing_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def track_depth_bigd_optimal_depth_45(self, optimization_level, routing_method):
return transpile(
self.bigd,
coupling_map=self.tokyo_coupling_map,
basis_gates=self.basis_gates,
routing_method=routing_method,
layout_method=routing_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def time_transpile_bntf(self, optimization_level, routing_method):
transpile(
self.bntf,
coupling_map=self.sycamore_coupling_map,
basis_gates=self.basis_gates,
routing_method=routing_method,
layout_method=routing_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def time_transpile_bss(self, optimization_level, routing_method):
transpile(
self.bss,
coupling_map=self.rochester_coupling_map,
basis_gates=self.basis_gates,
routing_method=routing_method,
layout_method=routing_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def time_transpile_bigd(self, optimization_level, routing_method):
transpile(
self.bigd,
coupling_map=self.tokyo_coupling_map,
basis_gates=self.basis_gates,
routing_method=routing_method,
layout_method=routing_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
|
https://github.com/hkhetawat/QArithmetic
|
hkhetawat
|
# Import the Qiskit SDK
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer
from QArithmetic import lshift, rshift
# Input N
n = 5
a = QuantumRegister(n)
b = QuantumRegister(n)
ca = ClassicalRegister(n)
cb = ClassicalRegister(n)
qc = QuantumCircuit(a, b, ca, cb)
# Input Superposition
# a = 11010
qc.x(a[1])
qc.x(a[3])
qc.x(a[4])
# b = 00011
qc.x(b[0])
qc.x(b[1])
# Left-shift |a>.
lshift(qc, a, n)
lshift(qc, a, n)
qc.measure(a, ca)
# Right-shift |b>.
rshift(qc, b, n)
rshift(qc, b, n)
qc.measure(b, cb)
# Simulate the circuit.
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for PauliList class."""
import itertools
import unittest
from test import combine
import numpy as np
from ddt import ddt
from scipy.sparse import csr_matrix
from qiskit import QiskitError
from qiskit.circuit.library import (
CXGate,
CYGate,
CZGate,
HGate,
IGate,
SdgGate,
SGate,
SwapGate,
XGate,
YGate,
ZGate,
)
from qiskit.quantum_info.operators import (
Clifford,
Operator,
Pauli,
PauliList,
PauliTable,
StabilizerTable,
)
from qiskit.quantum_info.random import random_clifford, random_pauli_list
from qiskit.test import QiskitTestCase
from .test_pauli import pauli_group_labels
def pauli_mat(label):
"""Return Pauli matrix from a Pauli label"""
mat = np.eye(1, dtype=complex)
if label[0:2] == "-i":
mat *= -1j
label = label[2:]
elif label[0] == "-":
mat *= -1
label = label[1:]
elif label[0] == "i":
mat *= 1j
label = label[1:]
for i in label:
if i == "I":
mat = np.kron(mat, np.eye(2, dtype=complex))
elif i == "X":
mat = np.kron(mat, np.array([[0, 1], [1, 0]], dtype=complex))
elif i == "Y":
mat = np.kron(mat, np.array([[0, -1j], [1j, 0]], dtype=complex))
elif i == "Z":
mat = np.kron(mat, np.array([[1, 0], [0, -1]], dtype=complex))
else:
raise QiskitError(f"Invalid Pauli string {i}")
return mat
class TestPauliListInit(QiskitTestCase):
"""Tests for PauliList initialization."""
def test_array_init(self):
"""Test array initialization."""
# Matrix array initialization
with self.subTest(msg="Empty array"):
x = np.array([], dtype=bool).reshape((1, 0))
z = np.array([], dtype=bool).reshape((1, 0))
pauli_list = PauliList.from_symplectic(x, z)
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg="bool array"):
z = np.array([[False], [True]])
x = np.array([[False], [True]])
pauli_list = PauliList.from_symplectic(z, x)
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg="bool array no copy"):
z = np.array([[False], [True]])
x = np.array([[True], [True]])
pauli_list = PauliList.from_symplectic(z, x)
z[0, 0] = not z[0, 0]
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
def test_string_init(self):
"""Test string initialization."""
# String initialization
with self.subTest(msg='str init "I"'):
pauli_list = PauliList("I")
z = np.array([[False]])
x = np.array([[False]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "X"'):
pauli_list = PauliList("X")
z = np.array([[False]])
x = np.array([[True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "Y"'):
pauli_list = PauliList("Y")
z = np.array([[True]])
x = np.array([[True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "Z"'):
pauli_list = PauliList("Z")
z = np.array([[True]])
x = np.array([[False]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "iZ"'):
pauli_list = PauliList("iZ")
z = np.array([[True]])
x = np.array([[False]])
phase = np.array([3])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
np.testing.assert_equal(pauli_list.phase, phase)
with self.subTest(msg='str init "-Z"'):
pauli_list = PauliList("-Z")
z = np.array([[True]])
x = np.array([[False]])
phase = np.array([2])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
np.testing.assert_equal(pauli_list.phase, phase)
with self.subTest(msg='str init "-iZ"'):
pauli_list = PauliList("-iZ")
z = np.array([[True]])
x = np.array([[False]])
phase = np.array([1])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
np.testing.assert_equal(pauli_list.phase, phase)
with self.subTest(msg='str init "IX"'):
pauli_list = PauliList("IX")
z = np.array([[False, False]])
x = np.array([[True, False]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "XI"'):
pauli_list = PauliList("XI")
z = np.array([[False, False]])
x = np.array([[False, True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "YZ"'):
pauli_list = PauliList("YZ")
z = np.array([[True, True]])
x = np.array([[False, True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "iZY"'):
pauli_list = PauliList("iZY")
z = np.array([[True, True]])
x = np.array([[True, False]])
phase = np.array([3])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
np.testing.assert_equal(pauli_list.phase, phase)
with self.subTest(msg='str init "XIZ"'):
pauli_list = PauliList("XIZ")
z = np.array([[True, False, False]])
x = np.array([[False, False, True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg="str init prevent broadcasting"):
with self.assertRaises(ValueError):
PauliList(["XYZ", "I"])
def test_list_init(self):
"""Test list initialization."""
with self.subTest(msg="PauliList"):
target = PauliList(["iXI", "IX", "IZ"])
value = PauliList(target)
self.assertEqual(value, target)
with self.subTest(msg="PauliList no copy"):
target = PauliList(["iXI", "IX", "IZ"])
value = PauliList(target)
value[0] = "-iII"
self.assertEqual(value, target)
def test_pauli_table_init(self):
"""Test table initialization."""
with self.subTest(msg="PauliTable"):
target = PauliTable.from_labels(["XI", "IX", "IZ"])
value = PauliList(target)
self.assertEqual(value, target)
with self.subTest(msg="PauliTable no copy"):
target = PauliTable.from_labels(["XI", "IX", "IZ"])
value = PauliList(target)
value[0] = "II"
self.assertEqual(value, target)
def test_stabilizer_table_init(self):
"""Test table initialization."""
with self.subTest(msg="PauliTable"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["+II", "-XZ"])
value = PauliList(target)
self.assertEqual(value, target)
with self.subTest(msg="PauliTable no copy"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["+YY", "-XZ", "XI"])
value = PauliList(target)
value[0] = "II"
self.assertEqual(value, target)
def test_init_from_settings(self):
"""Test initializing from the settings dictionary."""
pauli_list = PauliList(["IX", "-iYZ", "YY"])
from_settings = PauliList(**pauli_list.settings)
self.assertEqual(pauli_list, from_settings)
@ddt
class TestPauliListProperties(QiskitTestCase):
"""Tests for PauliList properties."""
def test_x_property(self):
"""Test X property"""
with self.subTest(msg="X"):
pauli = PauliList(["XI", "IZ", "YY"])
array = np.array([[False, True], [False, False], [True, True]], dtype=bool)
self.assertTrue(np.all(pauli.x == array))
with self.subTest(msg="set X"):
pauli = PauliList(["XI", "IZ"])
val = np.array([[False, False], [True, True]], dtype=bool)
pauli.x = val
self.assertEqual(pauli, PauliList(["II", "iXY"]))
with self.subTest(msg="set X raises"):
with self.assertRaises(Exception):
pauli = PauliList(["XI", "IZ"])
val = np.array([[False, False, False], [True, True, True]], dtype=bool)
pauli.x = val
def test_z_property(self):
"""Test Z property"""
with self.subTest(msg="Z"):
pauli = PauliList(["XI", "IZ", "YY"])
array = np.array([[False, False], [True, False], [True, True]], dtype=bool)
self.assertTrue(np.all(pauli.z == array))
with self.subTest(msg="set Z"):
pauli = PauliList(["XI", "IZ"])
val = np.array([[False, False], [True, True]], dtype=bool)
pauli.z = val
self.assertEqual(pauli, PauliList(["XI", "ZZ"]))
with self.subTest(msg="set Z raises"):
with self.assertRaises(Exception):
pauli = PauliList(["XI", "IZ"])
val = np.array([[False, False, False], [True, True, True]], dtype=bool)
pauli.z = val
def test_phase_property(self):
"""Test phase property"""
with self.subTest(msg="phase"):
pauli = PauliList(["XI", "IZ", "YY", "YI"])
array = np.array([0, 0, 0, 0], dtype=int)
np.testing.assert_equal(pauli.phase, array)
with self.subTest(msg="set phase"):
pauli = PauliList(["XI", "IZ"])
val = np.array([2, 3], dtype=int)
pauli.phase = val
self.assertEqual(pauli, PauliList(["-XI", "iIZ"]))
with self.subTest(msg="set Z raises"):
with self.assertRaises(Exception):
pauli = PauliList(["XI", "IZ"])
val = np.array([1, 2, 3], dtype=int)
pauli.phase = val
def test_shape_property(self):
"""Test shape property"""
shape = (3, 4)
pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape))
self.assertEqual(pauli.shape, shape)
@combine(j=range(1, 10))
def test_size_property(self, j):
"""Test size property"""
shape = (j, 4)
pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape))
self.assertEqual(len(pauli), j)
@combine(j=range(1, 10))
def test_n_qubit_property(self, j):
"""Test n_qubit property"""
shape = (5, j)
pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape))
self.assertEqual(pauli.num_qubits, j)
def test_eq(self):
"""Test __eq__ method."""
pauli1 = PauliList(["II", "XI"])
pauli2 = PauliList(["XI", "II"])
self.assertEqual(pauli1, pauli1)
self.assertNotEqual(pauli1, pauli2)
def test_len_methods(self):
"""Test __len__ method."""
for j in range(1, 10):
labels = j * ["XX"]
pauli = PauliList(labels)
self.assertEqual(len(pauli), j)
def test_add_methods(self):
"""Test __add__ method."""
labels1 = ["XXI", "IXX"]
labels2 = ["XXI", "ZZI", "ZYZ"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
target = PauliList(labels1 + labels2)
self.assertEqual(target, pauli1 + pauli2)
def test_add_qargs(self):
"""Test add method with qargs."""
pauli1 = PauliList(["IIII", "YYYY"])
pauli2 = PauliList(["XY", "YZ"])
pauli3 = PauliList(["X", "Y", "Z"])
with self.subTest(msg="qargs=[0, 1]"):
target = PauliList(["IIII", "YYYY", "IIXY", "IIYZ"])
self.assertEqual(pauli1 + pauli2([0, 1]), target)
with self.subTest(msg="qargs=[0, 3]"):
target = PauliList(["IIII", "YYYY", "XIIY", "YIIZ"])
self.assertEqual(pauli1 + pauli2([0, 3]), target)
with self.subTest(msg="qargs=[2, 1]"):
target = PauliList(["IIII", "YYYY", "IYXI", "IZYI"])
self.assertEqual(pauli1 + pauli2([2, 1]), target)
with self.subTest(msg="qargs=[3, 1]"):
target = PauliList(["IIII", "YYYY", "YIXI", "ZIYI"])
self.assertEqual(pauli1 + pauli2([3, 1]), target)
with self.subTest(msg="qargs=[0]"):
target = PauliList(["IIII", "YYYY", "IIIX", "IIIY", "IIIZ"])
self.assertEqual(pauli1 + pauli3([0]), target)
with self.subTest(msg="qargs=[1]"):
target = PauliList(["IIII", "YYYY", "IIXI", "IIYI", "IIZI"])
self.assertEqual(pauli1 + pauli3([1]), target)
with self.subTest(msg="qargs=[2]"):
target = PauliList(["IIII", "YYYY", "IXII", "IYII", "IZII"])
self.assertEqual(pauli1 + pauli3([2]), target)
with self.subTest(msg="qargs=[3]"):
target = PauliList(["IIII", "YYYY", "XIII", "YIII", "ZIII"])
self.assertEqual(pauli1 + pauli3([3]), target)
def test_getitem_methods(self):
"""Test __getitem__ method."""
with self.subTest(msg="__getitem__ single"):
labels = ["XI", "IY"]
pauli = PauliList(labels)
self.assertEqual(pauli[0], PauliList(labels[0]))
self.assertEqual(pauli[1], PauliList(labels[1]))
with self.subTest(msg="__getitem__ array"):
labels = np.array(["XI", "IY", "IZ", "XY", "ZX"])
pauli = PauliList(labels)
inds = [0, 3]
self.assertEqual(pauli[inds], PauliList(labels[inds]))
inds = np.array([4, 1])
self.assertEqual(pauli[inds], PauliList(labels[inds]))
with self.subTest(msg="__getitem__ slice"):
labels = np.array(["XI", "IY", "IZ", "XY", "ZX"])
pauli = PauliList(labels)
self.assertEqual(pauli[:], pauli)
self.assertEqual(pauli[1:3], PauliList(labels[1:3]))
def test_setitem_methods(self):
"""Test __setitem__ method."""
with self.subTest(msg="__setitem__ single"):
labels = ["XI", "IY"]
pauli = PauliList(["XI", "IY"])
pauli[0] = "II"
self.assertEqual(pauli[0], PauliList("II"))
pauli[1] = "-iXX"
self.assertEqual(pauli[1], PauliList("-iXX"))
with self.assertRaises(Exception):
# Wrong size Pauli
pauli[0] = "XXX"
with self.subTest(msg="__setitem__ array"):
labels = np.array(["XI", "IY", "IZ"])
pauli = PauliList(labels)
target = PauliList(["II", "ZZ"])
inds = [2, 0]
pauli[inds] = target
self.assertEqual(pauli[inds], target)
with self.assertRaises(Exception):
pauli[inds] = PauliList(["YY", "ZZ", "XX"])
with self.subTest(msg="__setitem__ slice"):
labels = np.array(5 * ["III"])
pauli = PauliList(labels)
target = PauliList(5 * ["XXX"])
pauli[:] = target
self.assertEqual(pauli[:], target)
target = PauliList(2 * ["ZZZ"])
pauli[1:3] = target
self.assertEqual(pauli[1:3], target)
class TestPauliListLabels(QiskitTestCase):
"""Tests PauliList label representation conversions."""
def test_from_labels_1q(self):
"""Test 1-qubit from_labels method."""
labels = ["I", "Z", "Z", "X", "Y"]
target = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_1q_with_phase(self):
"""Test 1-qubit from_labels method with phase."""
labels = ["-I", "iZ", "iZ", "X", "-iY"]
target = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
np.array([2, 3, 3, 0, 1]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_2q(self):
"""Test 2-qubit from_labels method."""
labels = ["II", "YY", "XZ"]
target = PauliList.from_symplectic(
np.array([[False, False], [True, True], [True, False]]),
np.array([[False, False], [True, True], [False, True]]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_2q_with_phase(self):
"""Test 2-qubit from_labels method."""
labels = ["iII", "iYY", "-iXZ"]
target = PauliList.from_symplectic(
np.array([[False, False], [True, True], [True, False]]),
np.array([[False, False], [True, True], [False, True]]),
np.array([3, 3, 1]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_5q(self):
"""Test 5-qubit from_labels method."""
labels = [5 * "I", 5 * "X", 5 * "Y", 5 * "Z"]
target = PauliList.from_symplectic(
np.array([[False] * 5, [False] * 5, [True] * 5, [True] * 5]),
np.array([[False] * 5, [True] * 5, [True] * 5, [False] * 5]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_to_labels_1q(self):
"""Test 1-qubit to_labels method."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
)
target = ["I", "Z", "Z", "X", "Y"]
value = pauli.to_labels()
self.assertEqual(value, target)
def test_to_labels_1q_with_phase(self):
"""Test 1-qubit to_labels method with phase."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
np.array([1, 3, 2, 3, 1]),
)
target = ["-iI", "iZ", "-Z", "iX", "-iY"]
value = pauli.to_labels()
self.assertEqual(value, target)
def test_to_labels_1q_array(self):
"""Test 1-qubit to_labels method w/ array=True."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
)
target = np.array(["I", "Z", "Z", "X", "Y"])
value = pauli.to_labels(array=True)
self.assertTrue(np.all(value == target))
def test_to_labels_1q_array_with_phase(self):
"""Test 1-qubit to_labels method w/ array=True."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
np.array([2, 3, 0, 1, 0]),
)
target = np.array(["-I", "iZ", "Z", "-iX", "Y"])
value = pauli.to_labels(array=True)
self.assertTrue(np.all(value == target))
def test_labels_round_trip(self):
"""Test from_labels and to_labels round trip."""
target = ["III", "IXZ", "XYI", "ZZZ", "-iZIX", "-IYX"]
value = PauliList(target).to_labels()
self.assertEqual(value, target)
def test_labels_round_trip_array(self):
"""Test from_labels and to_labels round trip w/ array=True."""
labels = ["III", "IXZ", "XYI", "ZZZ", "-iZIX", "-IYX"]
target = np.array(labels)
value = PauliList(labels).to_labels(array=True)
self.assertTrue(np.all(value == target))
class TestPauliListMatrix(QiskitTestCase):
"""Tests PauliList matrix representation conversions."""
def test_to_matrix_1q(self):
"""Test 1-qubit to_matrix method."""
labels = ["X", "I", "Z", "Y"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_array(self):
"""Test 1-qubit to_matrix method w/ array=True."""
labels = ["Z", "I", "Y", "X"]
target = np.array([pauli_mat(i) for i in labels])
value = PauliList(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_sparse(self):
"""Test 1-qubit to_matrix method w/ sparse=True."""
labels = ["X", "I", "Z", "Y"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_2q(self):
"""Test 2-qubit to_matrix method."""
labels = ["IX", "YI", "II", "ZZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_array(self):
"""Test 2-qubit to_matrix method w/ array=True."""
labels = ["ZZ", "XY", "YX", "IZ"]
target = np.array([pauli_mat(i) for i in labels])
value = PauliList(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_sparse(self):
"""Test 2-qubit to_matrix method w/ sparse=True."""
labels = ["IX", "II", "ZY", "YZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_5q(self):
"""Test 5-qubit to_matrix method."""
labels = ["IXIXI", "YZIXI", "IIXYZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_5q_sparse(self):
"""Test 5-qubit to_matrix method w/ sparse=True."""
labels = ["XXXYY", "IXIZY", "ZYXIX"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_5q_with_phase(self):
"""Test 5-qubit to_matrix method with phase."""
labels = ["iIXIXI", "-YZIXI", "-iIIXYZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_5q_sparse_with_phase(self):
"""Test 5-qubit to_matrix method w/ sparse=True with phase."""
labels = ["iXXXYY", "-IXIZY", "-iZYXIX"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
class TestPauliListIteration(QiskitTestCase):
"""Tests for PauliList iterators class."""
def test_enumerate(self):
"""Test enumerate with PauliList."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli):
self.assertEqual(i, PauliList(labels[idx]))
def test_iter(self):
"""Test iter with PauliList."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(iter(pauli)):
self.assertEqual(i, PauliList(labels[idx]))
def test_zip(self):
"""Test zip with PauliList."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for label, i in zip(labels, pauli):
self.assertEqual(i, PauliList(label))
def test_label_iter(self):
"""Test PauliList label_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli.label_iter()):
self.assertEqual(i, labels[idx])
def test_matrix_iter(self):
"""Test PauliList dense matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli.matrix_iter()):
self.assertTrue(np.all(i == pauli_mat(labels[idx])))
def test_matrix_iter_sparse(self):
"""Test PauliList sparse matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli.matrix_iter(sparse=True)):
self.assertTrue(isinstance(i, csr_matrix))
self.assertTrue(np.all(i.toarray() == pauli_mat(labels[idx])))
@ddt
class TestPauliListOperator(QiskitTestCase):
"""Tests for PauliList base operator methods."""
@combine(j=range(1, 10))
def test_tensor(self, j):
"""Test tensor method j={j}."""
labels1 = ["XX", "YY"]
labels2 = [j * "I", j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.tensor(pauli2)
target = PauliList([l1 + l2 for l1 in labels1 for l2 in labels2])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_tensor_with_phase(self, j):
"""Test tensor method j={j} with phase."""
labels1 = ["XX", "iYY"]
labels2 = [j * "I", "i" + j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.tensor(pauli2)
target = PauliList(["XX" + "I" * j, "iXX" + "Z" * j, "iYY" + "I" * j, "-YY" + "Z" * j])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_expand(self, j):
"""Test expand method j={j}."""
labels1 = ["XX", "YY"]
labels2 = [j * "I", j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.expand(pauli2)
target = PauliList([j + i for j in labels2 for i in labels1])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_expand_with_phase(self, j):
"""Test expand method j={j}."""
labels1 = ["-XX", "iYY"]
labels2 = ["i" + j * "I", "-i" + j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.expand(pauli2)
target = PauliList(
["-i" + "I" * j + "XX", "-" + "I" * j + "YY", "i" + "Z" * j + "XX", "Z" * j + "YY"]
)
self.assertEqual(value, target)
def test_compose_1q(self):
"""Test 1-qubit compose methods."""
# Test single qubit Pauli dot products
pauli = PauliList(["I", "X", "Y", "Z"])
with self.subTest(msg="compose single I"):
target = PauliList(["I", "X", "Y", "Z"])
value = pauli.compose("I")
self.assertEqual(target, value)
with self.subTest(msg="compose single X"):
target = PauliList(["X", "I", "iZ", "-iY"])
value = pauli.compose("X")
self.assertEqual(target, value)
with self.subTest(msg="compose single Y"):
target = PauliList(["Y", "-iZ", "I", "iX"])
value = pauli.compose("Y")
self.assertEqual(target, value)
with self.subTest(msg="compose single Z"):
target = PauliList(["Z", "iY", "-iX", "I"])
value = pauli.compose("Z")
self.assertEqual(target, value)
def test_dot_1q(self):
"""Test 1-qubit dot method."""
# Test single qubit Pauli dot products
pauli = PauliList(["I", "X", "Y", "Z"])
with self.subTest(msg="dot single I"):
target = PauliList(["I", "X", "Y", "Z"])
value = pauli.dot("I")
self.assertEqual(target, value)
with self.subTest(msg="dot single X"):
target = PauliList(["X", "I", "-iZ", "iY"])
value = pauli.dot("X")
self.assertEqual(target, value)
with self.subTest(msg="dot single Y"):
target = PauliList(["Y", "iZ", "I", "-iX"])
value = pauli.dot("Y")
self.assertEqual(target, value)
with self.subTest(msg="dot single Z"):
target = PauliList(["Z", "-iY", "iX", "I"])
value = pauli.dot("Z")
self.assertEqual(target, value)
def test_qargs_compose_1q(self):
"""Test 1-qubit compose method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("Z")
with self.subTest(msg="compose 1-qubit qargs=[0]"):
target = PauliList(["IIZ", "iXXY"])
value = pauli1.compose(pauli2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[1]"):
target = PauliList(["IZI", "iXYX"])
value = pauli1.compose(pauli2, qargs=[1])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[2]"):
target = PauliList(["ZII", "iYXX"])
value = pauli1.compose(pauli2, qargs=[2])
self.assertEqual(value, target)
def test_qargs_dot_1q(self):
"""Test 1-qubit dot method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("Z")
with self.subTest(msg="dot 1-qubit qargs=[0]"):
target = PauliList(["IIZ", "-iXXY"])
value = pauli1.dot(pauli2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="dot 1-qubit qargs=[1]"):
target = PauliList(["IZI", "-iXYX"])
value = pauli1.dot(pauli2, qargs=[1])
self.assertEqual(value, target)
with self.subTest(msg="dot 1-qubit qargs=[2]"):
target = PauliList(["ZII", "-iYXX"])
value = pauli1.dot(pauli2, qargs=[2])
self.assertEqual(value, target)
def test_qargs_compose_2q(self):
"""Test 2-qubit compose method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("ZY")
with self.subTest(msg="compose 2-qubit qargs=[0, 1]"):
target = PauliList(["IZY", "XYZ"])
value = pauli1.compose(pauli2, qargs=[0, 1])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[1, 0]"):
target = PauliList(["IYZ", "XZY"])
value = pauli1.compose(pauli2, qargs=[1, 0])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[0, 2]"):
target = PauliList(["ZIY", "YXZ"])
value = pauli1.compose(pauli2, qargs=[0, 2])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[2, 0]"):
target = PauliList(["YIZ", "ZXY"])
value = pauli1.compose(pauli2, qargs=[2, 0])
self.assertEqual(value, target)
def test_qargs_dot_2q(self):
"""Test 2-qubit dot method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("ZY")
with self.subTest(msg="dot 2-qubit qargs=[0, 1]"):
target = PauliList(["IZY", "XYZ"])
value = pauli1.dot(pauli2, qargs=[0, 1])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[1, 0]"):
target = PauliList(["IYZ", "XZY"])
value = pauli1.dot(pauli2, qargs=[1, 0])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[0, 2]"):
target = PauliList(["ZIY", "YXZ"])
value = pauli1.dot(pauli2, qargs=[0, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[2, 0]"):
target = PauliList(["YIZ", "ZXY"])
value = pauli1.dot(pauli2, qargs=[2, 0])
self.assertEqual(value, target)
def test_qargs_compose_3q(self):
"""Test 3-qubit compose method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("XYZ")
with self.subTest(msg="compose 3-qubit qargs=None"):
target = PauliList(["XYZ", "IZY"])
value = pauli1.compose(pauli2)
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[0, 1, 2]"):
target = PauliList(["XYZ", "IZY"])
value = pauli1.compose(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[2, 1, 0]"):
target = PauliList(["ZYX", "YZI"])
value = pauli1.compose(pauli2, qargs=[2, 1, 0])
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[1, 0, 2]"):
target = PauliList(["XZY", "IYZ"])
value = pauli1.compose(pauli2, qargs=[1, 0, 2])
self.assertEqual(value, target)
def test_qargs_dot_3q(self):
"""Test 3-qubit dot method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("XYZ")
with self.subTest(msg="dot 3-qubit qargs=None"):
target = PauliList(["XYZ", "IZY"])
value = pauli1.dot(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[0, 1, 2]"):
target = PauliList(["XYZ", "IZY"])
value = pauli1.dot(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[2, 1, 0]"):
target = PauliList(["ZYX", "YZI"])
value = pauli1.dot(pauli2, qargs=[2, 1, 0])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[1, 0, 2]"):
target = PauliList(["XZY", "IYZ"])
value = pauli1.dot(pauli2, qargs=[1, 0, 2])
self.assertEqual(value, target)
@ddt
class TestPauliListMethods(QiskitTestCase):
"""Tests for PauliList utility methods class."""
def test_sort(self):
"""Test sort method."""
with self.subTest(msg="1 qubit standard order"):
unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"]
srt = ["I", "-iI", "-I", "iI", "X", "X", "Y", "-iY", "Z", "Z"]
target = PauliList(srt)
value = PauliList(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="1 qubit weight order"):
unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"]
srt = ["I", "-iI", "-I", "iI", "X", "X", "Y", "-iY", "Z", "Z"]
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="1 qubit phase order"):
unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"]
srt = ["I", "X", "X", "Y", "Z", "Z", "-iI", "-iY", "-I", "iI"]
target = PauliList(srt)
value = PauliList(unsrt).sort(phase=True)
self.assertEqual(target, value)
with self.subTest(msg="1 qubit weight & phase order"):
unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"]
srt = ["I", "X", "X", "Y", "Z", "Z", "-iI", "-iY", "-I", "iI"]
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True, phase=True)
self.assertEqual(target, value)
with self.subTest(msg="2 qubit standard order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"iIZ",
"XI",
"XX",
"XX",
"iXX",
"XY",
"XZ",
"iXZ",
"YI",
"YI",
"-YI",
"YX",
"-iYX",
"YY",
"-iYY",
"-YY",
"iYY",
"YZ",
"ZI",
"ZX",
"ZX",
"ZY",
"ZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit weight order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"iIZ",
"XI",
"YI",
"YI",
"-YI",
"ZI",
"XX",
"XX",
"iXX",
"XY",
"XZ",
"iXZ",
"YX",
"-iYX",
"YY",
"YY",
"-YY",
"YZ",
"ZX",
"ZX",
"ZY",
"ZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="2 qubit phase order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"XI",
"XX",
"XX",
"XY",
"XZ",
"YI",
"YI",
"YX",
"YY",
"YY",
"YZ",
"ZI",
"ZX",
"ZX",
"ZY",
"ZZ",
"-iYX",
"-YI",
"-YY",
"iIZ",
"iXX",
"iXZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(phase=True)
self.assertEqual(target, value)
with self.subTest(msg="2 qubit weight & phase order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"XI",
"YI",
"YI",
"ZI",
"XX",
"XX",
"XY",
"XZ",
"YX",
"YY",
"YY",
"YZ",
"ZX",
"ZX",
"ZY",
"ZZ",
"-iYX",
"-YI",
"-YY",
"iIZ",
"iXX",
"iXZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True, phase=True)
self.assertEqual(target, value)
with self.subTest(msg="3 qubit standard order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"-IIY",
"IIZ",
"IXI",
"IXX",
"IXY",
"iIXY",
"IXZ",
"IYI",
"IYX",
"IYY",
"IYZ",
"IZI",
"IZX",
"IZY",
"IZY",
"IZZ",
"XII",
"XII",
"XIX",
"XIY",
"XIZ",
"XXI",
"XXX",
"-iXXX",
"XXY",
"XXZ",
"XYI",
"XYX",
"iXYX",
"XYY",
"XYZ",
"XYZ",
"XZI",
"XZX",
"XZY",
"XZZ",
"YII",
"YIX",
"YIY",
"YIZ",
"YXI",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYI",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZI",
"YZX",
"YZY",
"YZZ",
"ZII",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZXX",
"iZXX",
"ZXY",
"ZXZ",
"ZYI",
"ZYI",
"ZYX",
"ZYY",
"ZYZ",
"ZZI",
"ZZX",
"ZZY",
"ZZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="3 qubit weight order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"-IIY",
"IIZ",
"IXI",
"IYI",
"IZI",
"XII",
"XII",
"YII",
"ZII",
"IXX",
"IXY",
"iIXY",
"IXZ",
"IYX",
"IYY",
"IYZ",
"IZX",
"IZY",
"IZY",
"IZZ",
"XIX",
"XIY",
"XIZ",
"XXI",
"XYI",
"XZI",
"YIX",
"YIY",
"YIZ",
"YXI",
"YYI",
"YZI",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZYI",
"ZYI",
"ZZI",
"XXX",
"-iXXX",
"XXY",
"XXZ",
"XYX",
"iXYX",
"XYY",
"XYZ",
"XYZ",
"XZX",
"XZY",
"XZZ",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZX",
"YZY",
"YZZ",
"ZXX",
"iZXX",
"ZXY",
"ZXZ",
"ZYX",
"ZYY",
"ZYZ",
"ZZX",
"ZZY",
"ZZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="3 qubit phase order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"IIZ",
"IXI",
"IXX",
"IXY",
"IXZ",
"IYI",
"IYX",
"IYY",
"IYZ",
"IZI",
"IZX",
"IZY",
"IZY",
"IZZ",
"XII",
"XII",
"XIX",
"XIY",
"XIZ",
"XXI",
"XXX",
"XXY",
"XXZ",
"XYI",
"XYX",
"XYY",
"XYZ",
"XYZ",
"XZI",
"XZX",
"XZY",
"XZZ",
"YII",
"YIX",
"YIY",
"YIZ",
"YXI",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYI",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZI",
"YZX",
"YZY",
"YZZ",
"ZII",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZXX",
"ZXY",
"ZXZ",
"ZYI",
"ZYI",
"ZYX",
"ZYY",
"ZYZ",
"ZZI",
"ZZX",
"ZZY",
"ZZZ",
"-iXXX",
"-IIY",
"iIXY",
"iXYX",
"iZXX",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(phase=True)
self.assertEqual(target, value)
with self.subTest(msg="3 qubit weight & phase order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"IYI",
"IZI",
"XII",
"XII",
"YII",
"ZII",
"IXX",
"IXY",
"IXZ",
"IYX",
"IYY",
"IYZ",
"IZX",
"IZY",
"IZY",
"IZZ",
"XIX",
"XIY",
"XIZ",
"XXI",
"XYI",
"XZI",
"YIX",
"YIY",
"YIZ",
"YYI",
"YZI",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZYI",
"ZYI",
"ZZI",
"XXX",
"XXY",
"XXZ",
"XYX",
"XYY",
"XYZ",
"XZX",
"XZY",
"XZZ",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZX",
"YZY",
"YZZ",
"ZXX",
"ZXY",
"ZXZ",
"ZYX",
"ZYY",
"ZYZ",
"ZZX",
"ZZY",
"ZZZ",
"-iZIZ",
"-iXXX",
"-IIY",
"iIXI",
"iIXY",
"iYXI",
"iXYX",
"iXYZ",
"iZXX",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True, phase=True)
self.assertEqual(target, value)
def test_unique(self):
"""Test unique method."""
with self.subTest(msg="1 qubit"):
labels = ["X", "Z", "X", "X", "I", "Y", "I", "X", "Z", "Z", "X", "I"]
unique = ["X", "Z", "I", "Y"]
target = PauliList(unique)
value = PauliList(labels).unique()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit"):
labels = ["XX", "IX", "XX", "II", "IZ", "ZI", "YX", "YX", "ZZ", "IX", "XI"]
unique = ["XX", "IX", "II", "IZ", "ZI", "YX", "ZZ", "XI"]
target = PauliList(unique)
value = PauliList(labels).unique()
self.assertEqual(target, value)
with self.subTest(msg="10 qubit"):
labels = [10 * "X", 10 * "I", 10 * "X"]
unique = [10 * "X", 10 * "I"]
target = PauliList(unique)
value = PauliList(labels).unique()
self.assertEqual(target, value)
def test_delete(self):
"""Test delete method."""
with self.subTest(msg="single row"):
for j in range(1, 6):
pauli = PauliList([j * "X", j * "Y"])
self.assertEqual(pauli.delete(0), PauliList(j * "Y"))
self.assertEqual(pauli.delete(1), PauliList(j * "X"))
with self.subTest(msg="multiple rows"):
for j in range(1, 6):
pauli = PauliList([j * "X", "-i" + j * "Y", j * "Z"])
self.assertEqual(pauli.delete([0, 2]), PauliList("-i" + j * "Y"))
self.assertEqual(pauli.delete([1, 2]), PauliList(j * "X"))
self.assertEqual(pauli.delete([0, 1]), PauliList(j * "Z"))
with self.subTest(msg="single qubit"):
pauli = PauliList(["IIX", "iIYI", "ZII"])
value = pauli.delete(0, qubit=True)
target = PauliList(["II", "iIY", "ZI"])
self.assertEqual(value, target)
value = pauli.delete(1, qubit=True)
target = PauliList(["IX", "iII", "ZI"])
self.assertEqual(value, target)
value = pauli.delete(2, qubit=True)
target = PauliList(["IX", "iYI", "II"])
self.assertEqual(value, target)
with self.subTest(msg="multiple qubits"):
pauli = PauliList(["IIX", "IYI", "-ZII"])
value = pauli.delete([0, 1], qubit=True)
target = PauliList(["I", "I", "-Z"])
self.assertEqual(value, target)
value = pauli.delete([1, 2], qubit=True)
target = PauliList(["X", "I", "-I"])
self.assertEqual(value, target)
value = pauli.delete([0, 2], qubit=True)
target = PauliList(["I", "Y", "-I"])
self.assertEqual(value, target)
def test_insert(self):
"""Test insert method."""
# Insert single row
for j in range(1, 10):
pauli = PauliList(j * "X")
target0 = PauliList([j * "I", j * "X"])
target1 = PauliList([j * "X", j * "I"])
with self.subTest(msg=f"single row from str ({j})"):
value0 = pauli.insert(0, j * "I")
self.assertEqual(value0, target0)
value1 = pauli.insert(1, j * "I")
self.assertEqual(value1, target1)
with self.subTest(msg=f"single row from PauliList ({j})"):
value0 = pauli.insert(0, PauliList(j * "I"))
self.assertEqual(value0, target0)
value1 = pauli.insert(1, PauliList(j * "I"))
self.assertEqual(value1, target1)
target0 = PauliList(["i" + j * "I", j * "X"])
target1 = PauliList([j * "X", "i" + j * "I"])
with self.subTest(msg=f"single row with phase from str ({j})"):
value0 = pauli.insert(0, "i" + j * "I")
self.assertEqual(value0, target0)
value1 = pauli.insert(1, "i" + j * "I")
self.assertEqual(value1, target1)
with self.subTest(msg=f"single row with phase from PauliList ({j})"):
value0 = pauli.insert(0, PauliList("i" + j * "I"))
self.assertEqual(value0, target0)
value1 = pauli.insert(1, PauliList("i" + j * "I"))
self.assertEqual(value1, target1)
# Insert multiple rows
for j in range(1, 10):
pauli = PauliList("i" + j * "X")
insert = PauliList([j * "I", j * "Y", j * "Z", "-i" + j * "X"])
target0 = insert + pauli
target1 = pauli + insert
with self.subTest(msg=f"multiple-rows from PauliList ({j})"):
value0 = pauli.insert(0, insert)
self.assertEqual(value0, target0)
value1 = pauli.insert(1, insert)
self.assertEqual(value1, target1)
# Insert single column
pauli = PauliList(["X", "Y", "Z", "-iI"])
for i in ["I", "X", "Y", "Z", "iY"]:
phase = "" if len(i) == 1 else i[0]
p = i if len(i) == 1 else i[1]
target0 = PauliList(
[
phase + "X" + p,
phase + "Y" + p,
phase + "Z" + p,
("" if phase else "-i") + "I" + p,
]
)
target1 = PauliList(
[
i + "X",
i + "Y",
i + "Z",
("" if phase else "-i") + p + "I",
]
)
with self.subTest(msg="single-column single-val from str"):
value = pauli.insert(0, i, qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, i, qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="single-column single-val from PauliList"):
value = pauli.insert(0, PauliList(i), qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, PauliList(i), qubit=True)
self.assertEqual(value, target1)
# Insert single column with multiple values
pauli = PauliList(["X", "Y", "iZ"])
for i in [["I", "X", "Y"], ["X", "iY", "Z"], ["Y", "Z", "I"]]:
target0 = PauliList(
["X" + i[0], "Y" + i[1] if len(i[1]) == 1 else i[1][0] + "Y" + i[1][1], "iZ" + i[2]]
)
target1 = PauliList([i[0] + "X", i[1] + "Y", "i" + i[2] + "Z"])
with self.subTest(msg="single-column multiple-vals from PauliList"):
value = pauli.insert(0, PauliList(i), qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, PauliList(i), qubit=True)
self.assertEqual(value, target1)
# Insert multiple columns from single
pauli = PauliList(["X", "iY", "Z"])
for j in range(1, 5):
for i in [j * "I", j * "X", j * "Y", "i" + j * "Z"]:
phase = "" if len(i) == j else i[0]
p = i if len(i) == j else i[1:]
target0 = PauliList(
[
phase + "X" + p,
("-" if phase else "i") + "Y" + p,
phase + "Z" + p,
]
)
target1 = PauliList([i + "X", ("-" if phase else "i") + p + "Y", i + "Z"])
with self.subTest(msg="multiple-columns single-val from str"):
value = pauli.insert(0, i, qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, i, qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="multiple-columns single-val from PauliList"):
value = pauli.insert(0, PauliList(i), qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, PauliList(i), qubit=True)
self.assertEqual(value, target1)
# Insert multiple columns multiple row values
pauli = PauliList(["X", "Y", "-iZ"])
for j in range(1, 5):
for i in [
[j * "I", j * "X", j * "Y"],
[j * "X", j * "Z", "i" + j * "Y"],
[j * "Y", j * "Z", j * "I"],
]:
target0 = PauliList(
[
"X" + i[0],
"Y" + i[1],
("-i" if len(i[2]) == j else "") + "Z" + i[2][-j:],
]
)
target1 = PauliList(
[
i[0] + "X",
i[1] + "Y",
("-i" if len(i[2]) == j else "") + i[2][-j:] + "Z",
]
)
with self.subTest(msg="multiple-column multiple-vals from PauliList"):
value = pauli.insert(0, PauliList(i), qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, PauliList(i), qubit=True)
self.assertEqual(value, target1)
def test_commutes(self):
"""Test commutes method."""
# Single qubit Pauli
pauli = PauliList(["I", "X", "Y", "Z", "-iY"])
with self.subTest(msg="commutes single-Pauli I"):
value = list(pauli.commutes("I"))
target = [True, True, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli X"):
value = list(pauli.commutes("X"))
target = [True, True, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli Y"):
value = list(pauli.commutes("Y"))
target = [True, False, True, False, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli Z"):
value = list(pauli.commutes("Z"))
target = [True, False, False, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli iZ"):
value = list(pauli.commutes("iZ"))
target = [True, False, False, True, False]
self.assertEqual(value, target)
# 2-qubit Pauli
pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "-iYY"])
with self.subTest(msg="commutes single-Pauli II"):
value = list(pauli.commutes("II"))
target = [True, True, True, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli IX"):
value = list(pauli.commutes("IX"))
target = [True, True, True, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli XI"):
value = list(pauli.commutes("XI"))
target = [True, True, False, True, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli YI"):
value = list(pauli.commutes("YI"))
target = [True, True, True, False, False, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli IY"):
value = list(pauli.commutes("IY"))
target = [True, False, True, True, False, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli XY"):
value = list(pauli.commutes("XY"))
target = [True, False, False, True, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli YX"):
value = list(pauli.commutes("YX"))
target = [True, True, True, True, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli ZZ"):
value = list(pauli.commutes("ZZ"))
target = [True, False, False, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli iYX"):
value = list(pauli.commutes("iYX"))
target = [True, True, True, True, True, False]
self.assertEqual(value, target)
def test_anticommutes(self):
"""Test anticommutes method."""
# Single qubit Pauli
pauli = PauliList(["I", "X", "Y", "Z", "-iY"])
with self.subTest(msg="anticommutes single-Pauli I"):
value = list(pauli.anticommutes("I"))
target = [False, False, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli X"):
value = list(pauli.anticommutes("X"))
target = [False, False, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli Y"):
value = list(pauli.anticommutes("Y"))
target = [False, True, False, True, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli Z"):
value = list(pauli.anticommutes("Z"))
target = [False, True, True, False, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli iZ"):
value = list(pauli.anticommutes("iZ"))
target = [False, True, True, False, True]
self.assertEqual(value, target)
# 2-qubit Pauli
pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iZX"])
with self.subTest(msg="anticommutes single-Pauli II"):
value = list(pauli.anticommutes("II"))
target = [False, False, False, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli IX"):
value = list(pauli.anticommutes("IX"))
target = [False, False, False, True, True, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli XI"):
value = list(pauli.anticommutes("XI"))
target = [False, False, True, False, True, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli YI"):
value = list(pauli.anticommutes("YI"))
target = [False, False, False, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli IY"):
value = list(pauli.anticommutes("IY"))
target = [False, True, False, False, True, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli XY"):
value = list(pauli.anticommutes("XY"))
target = [False, True, True, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli YX"):
value = list(pauli.anticommutes("YX"))
target = [False, False, False, False, False, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli ZZ"):
value = list(pauli.anticommutes("ZZ"))
target = [False, True, True, False, False, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli iXY"):
value = list(pauli.anticommutes("iXY"))
target = [False, True, True, False, False, False]
self.assertEqual(value, target)
def test_commutes_with_all(self):
"""Test commutes_with_all method."""
# 1-qubit
pauli = PauliList(["I", "X", "Y", "Z", "-iY"])
with self.subTest(msg="commutes_with_all [I]"):
value = list(pauli.commutes_with_all("I"))
target = [0, 1, 2, 3, 4]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [X]"):
value = list(pauli.commutes_with_all("X"))
target = [0, 1]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [Y]"):
value = list(pauli.commutes_with_all("Y"))
target = [0, 2, 4]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [Z]"):
value = list(pauli.commutes_with_all("Z"))
target = [0, 3]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [iY]"):
value = list(pauli.commutes_with_all("iY"))
target = [0, 2, 4]
self.assertEqual(value, target)
# 2-qubit Pauli
pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iXY"])
with self.subTest(msg="commutes_with_all [IX, YI]"):
other = PauliList(["IX", "YI"])
value = list(pauli.commutes_with_all(other))
target = [0, 1, 2]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, ZZ]"):
other = PauliList(["XY", "ZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4, 5]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [YX, ZZ]"):
other = PauliList(["YX", "ZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4, 5]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, YX]"):
other = PauliList(["XY", "YX"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4, 5]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, IX]"):
other = PauliList(["XY", "IX"])
value = list(pauli.commutes_with_all(other))
target = [0]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [YX, IX]"):
other = PauliList(["YX", "IX"])
value = list(pauli.commutes_with_all(other))
target = [0, 1, 2]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [-iYX, iZZ]"):
other = PauliList(["-iYX", "iZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4, 5]
self.assertEqual(value, target)
def test_anticommutes_with_all(self):
"""Test anticommutes_with_all method."""
# 1-qubit
pauli = PauliList(["I", "X", "Y", "Z", "-iY"])
with self.subTest(msg="anticommutes_with_all [I]"):
value = list(pauli.anticommutes_with_all("I"))
target = []
self.assertEqual(value, target)
with self.subTest(msg="antianticommutes_with_all [X]"):
value = list(pauli.anticommutes_with_all("X"))
target = [2, 3, 4]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [Y]"):
value = list(pauli.anticommutes_with_all("Y"))
target = [1, 3]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [Z]"):
value = list(pauli.anticommutes_with_all("Z"))
target = [1, 2, 4]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [iY]"):
value = list(pauli.anticommutes_with_all("iY"))
target = [1, 3]
self.assertEqual(value, target)
# 2-qubit Pauli
pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iZX"])
with self.subTest(msg="anticommutes_with_all [IX, YI]"):
other = PauliList(["IX", "YI"])
value = list(pauli.anticommutes_with_all(other))
target = [3, 4]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, ZZ]"):
other = PauliList(["XY", "ZZ"])
value = list(pauli.anticommutes_with_all(other))
target = [1, 2]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [YX, ZZ]"):
other = PauliList(["YX", "ZZ"])
value = list(pauli.anticommutes_with_all(other))
target = [5]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, YX]"):
other = PauliList(["XY", "YX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, IX]"):
other = PauliList(["XY", "IX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [YX, IX]"):
other = PauliList(["YX", "IX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
@combine(
gate=(
IGate(),
XGate(),
YGate(),
ZGate(),
HGate(),
SGate(),
SdgGate(),
Clifford(IGate()),
Clifford(XGate()),
Clifford(YGate()),
Clifford(ZGate()),
Clifford(HGate()),
Clifford(SGate()),
Clifford(SdgGate()),
)
)
def test_evolve_clifford1(self, gate):
"""Test evolve method for 1-qubit Clifford gates."""
op = Operator(gate)
pauli_list = PauliList(pauli_group_labels(1, True))
value = [Operator(pauli) for pauli in pauli_list.evolve(gate)]
value_h = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="h")]
value_s = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="s")]
if isinstance(gate, Clifford):
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.adjoint())]
else:
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.inverse())]
target = [op.adjoint().dot(pauli).dot(op) for pauli in pauli_list]
self.assertListEqual(value, target)
self.assertListEqual(value, value_h)
self.assertListEqual(value_inv, value_s)
@combine(
gate=(
CXGate(),
CYGate(),
CZGate(),
SwapGate(),
Clifford(CXGate()),
Clifford(CYGate()),
Clifford(CZGate()),
Clifford(SwapGate()),
)
)
def test_evolve_clifford2(self, gate):
"""Test evolve method for 2-qubit Clifford gates."""
op = Operator(gate)
pauli_list = PauliList(pauli_group_labels(2, True))
value = [Operator(pauli) for pauli in pauli_list.evolve(gate)]
value_h = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="h")]
value_s = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="s")]
if isinstance(gate, Clifford):
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.adjoint())]
else:
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.inverse())]
target = [op.adjoint().dot(pauli).dot(op) for pauli in pauli_list]
self.assertListEqual(value, target)
self.assertListEqual(value, value_h)
self.assertListEqual(value_inv, value_s)
def test_phase_dtype_evolve_clifford(self):
"""Test phase dtype during evolve method for Clifford gates."""
gates = (
IGate(),
XGate(),
YGate(),
ZGate(),
HGate(),
SGate(),
SdgGate(),
CXGate(),
CYGate(),
CZGate(),
SwapGate(),
)
dtypes = [
int,
np.int8,
np.uint8,
np.int16,
np.uint16,
np.int32,
np.uint32,
np.int64,
np.uint64,
]
for gate, dtype in itertools.product(gates, dtypes):
z = np.ones(gate.num_qubits, dtype=bool)
x = np.ones(gate.num_qubits, dtype=bool)
phase = (np.sum(z & x) % 4).astype(dtype)
paulis = Pauli((z, x, phase))
evo = paulis.evolve(gate)
self.assertEqual(evo.phase.dtype, dtype)
@combine(phase=(True, False))
def test_evolve_clifford_qargs(self, phase):
"""Test evolve method for random Clifford"""
cliff = random_clifford(3, seed=10)
op = Operator(cliff)
pauli_list = random_pauli_list(5, 3, seed=10, phase=phase)
qargs = [3, 0, 1]
value = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs)]
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(cliff.adjoint(), qargs=qargs)]
value_h = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs, frame="h")]
value_s = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs, frame="s")]
target = [
Operator(pauli).compose(op.adjoint(), qargs=qargs).dot(op, qargs=qargs)
for pauli in pauli_list
]
self.assertListEqual(value, target)
self.assertListEqual(value, value_h)
self.assertListEqual(value_inv, value_s)
def test_group_qubit_wise_commuting(self):
"""Test grouping qubit-wise commuting operators"""
def qubitwise_commutes(left: Pauli, right: Pauli) -> bool:
return len(left) == len(right) and all(a.commutes(b) for a, b in zip(left, right))
input_labels = ["IY", "ZX", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "iZZ", "II"]
np.random.shuffle(input_labels)
pauli_list = PauliList(input_labels)
groups = pauli_list.group_qubit_wise_commuting()
# checking that every input Pauli in pauli_list is in a group in the ouput
output_labels = [pauli.to_label() for group in groups for pauli in group]
self.assertListEqual(sorted(output_labels), sorted(input_labels))
# Within each group, every operator qubit-wise commutes with every other operator.
for group in groups:
self.assertTrue(
all(
qubitwise_commutes(pauli1, pauli2)
for pauli1, pauli2 in itertools.combinations(group, 2)
)
)
# For every pair of groups, at least one element from one does not qubit-wise commute with
# at least one element of the other.
for group1, group2 in itertools.combinations(groups, 2):
self.assertFalse(
all(
qubitwise_commutes(group1_pauli, group2_pauli)
for group1_pauli, group2_pauli in itertools.product(group1, group2)
)
)
def test_group_commuting(self):
"""Test general grouping commuting operators"""
def commutes(left: Pauli, right: Pauli) -> bool:
return len(left) == len(right) and left.commutes(right)
input_labels = ["IY", "ZX", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "iZZ", "II"]
np.random.shuffle(input_labels)
pauli_list = PauliList(input_labels)
# if qubit_wise=True, equivalent to test_group_qubit_wise_commuting
groups = pauli_list.group_commuting(qubit_wise=False)
# checking that every input Pauli in pauli_list is in a group in the ouput
output_labels = [pauli.to_label() for group in groups for pauli in group]
self.assertListEqual(sorted(output_labels), sorted(input_labels))
# Within each group, every operator commutes with every other operator.
for group in groups:
self.assertTrue(
all(commutes(pauli1, pauli2) for pauli1, pauli2 in itertools.combinations(group, 2))
)
# For every pair of groups, at least one element from one group does not commute with
# at least one element of the other.
for group1, group2 in itertools.combinations(groups, 2):
self.assertFalse(
all(
commutes(group1_pauli, group2_pauli)
for group1_pauli, group2_pauli in itertools.product(group1, group2)
)
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-hackathon-korea-22
|
qiskit-community
|
# Import auxiliary libraries
# Import Qiskit
from qiskit import Aer
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit.utils import QuantumInstance
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
qp_ex = QuadraticProgram()
qp_ex.integer_var(lowerbound=0, upperbound=100, name='x')
qp_ex.integer_var(lowerbound=0, upperbound=100, name='y')
qp_ex.maximize(linear={'x': 100, 'y': 40})
qp_ex.linear_constraint(linear={'x': 100, 'y': 50}, sense='LE', rhs=3000, name='constraints_1')
qp_ex.linear_constraint(linear={'x': 10}, sense='LE', rhs=100, name='constraints_2')
print(qp_ex.export_as_lp_string())
qp = QuadraticProgram()
qp.integer_var(lowerbound=0, upperbound=5, name='x')
qp.integer_var(lowerbound=0, upperbound=5, name='y')
qp.maximize(linear={'x': 3, 'y': 2})
qp.linear_constraint(linear={'x': 1, 'y': 2}, sense='LE', rhs=4, name='constraints_1')
qp.linear_constraint(linear={'x': 1 }, sense='LE', rhs=2, name='constraints_2')
print(qp.export_as_lp_string())
qins = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), shots=1000, seed_simulator=0)
meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, quantum_instance=qins)) # Define QAOA solver
result = meo.solve(qp)
print('result:', result._variables_dict)
# print('status:', result._status)
# print('time:', result.min_eigen_solver_result.optimizer_time)
exact_mes = NumPyMinimumEigensolver()
exact = MinimumEigenOptimizer(exact_mes) # Using the exact classical numpy minimum eigen solver
exact_result = exact.solve(qp)
print('result:', exact_result._variables_dict)
# print('status:', exact_result._status)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Create circuit to test transpiler on
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator, Diagonal
oracle = Diagonal([1]*7 + [-1])
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc = qc.compose(GroverOperator(oracle))
# Use Statevector object to calculate the ideal output
from qiskit.quantum_info import Statevector
ideal_distribution = Statevector.from_instruction(qc).probabilities_dict()
from qiskit.visualization import plot_histogram
plot_histogram(ideal_distribution)
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend('ibm_algiers')
# Need to add measurements to the circuit
qc.measure_all()
from qiskit import transpile
circuits = []
for optimization_level in [0, 3]:
t_qc = transpile(qc,
backend,
optimization_level=optimization_level,
seed_transpiler=0)
print(f'CNOTs (optimization_level={optimization_level}): ',
t_qc.count_ops()['cx'])
circuits.append(t_qc)
from qiskit.transpiler import PassManager, InstructionDurations
from qiskit.transpiler.passes import ASAPSchedule, DynamicalDecoupling
from qiskit.circuit.library import XGate
# Get gate durations so the transpiler knows how long each operation takes
durations = InstructionDurations.from_backend(backend)
# This is the sequence we'll apply to idling qubits
dd_sequence = [XGate(), XGate()]
# Run scheduling and dynamic decoupling passes on circuit
pm = PassManager([ASAPSchedule(durations),
DynamicalDecoupling(durations, dd_sequence)]
)
circ_dd = pm.run(circuits[1])
# Add this new circuit to our list
circuits.append(circ_dd)
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
sampler = Sampler()
job = sampler.run(
circuits=circuits, # sample all three circuits
skip_transpilation=True,
shots=8000)
result = job.result()
from qiskit.visualization import plot_histogram
binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists]
plot_histogram(binary_prob+[ideal_distribution],
bar_labels=False,
legend=['optimization_level=0',
'optimization_level=3',
'optimization_level=3 + dd',
'ideal distribution'])
from qiskit.quantum_info import hellinger_fidelity
for counts in result.quasi_dists:
print(
f"{hellinger_fidelity(counts.binary_probabilities(), ideal_distribution):.3f}"
)
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# vector |v>
print("vector |v>")
values = [-0.1, -0.3, 0.4, 0.5]
total = 0 # summation of squares
for i in range(len(values)):
total += values[i]**2; # add the square of each value
print("total is ",total)
print("the missing part is",1-total)
print("so, the value a should be",(1-total)**0.5) # sqaure root of the missing part
print()
print("vector |u>")
values = [1/(2**0.5), -1/(3**0.5)]
total = 0 # summation of squares
for i in range(len(values)):
total += values[i]**2; # add the square of each value
print("total is ",total)
print("the missing part is",1-total)
# the missing part is 1/b, square of 1/sqrt(b)
# thus b is 1/missing-part
print("so, the value b should be",1/(1-total))
from random import randrange
# randomly create a 2-dimensional quantum state
def random_quantum_state():
first_entry = randrange(100)
first_entry = first_entry/100
first_entry = first_entry**0.5 # we found the first value before determining its sign
if randrange(2) == 0: # determine the sign
first_entry = -1 * first_entry
second_entry = 1 - (first_entry**2)
second_entry = second_entry**0.5
if randrange(2) == 0: # determine the sign
second_entry = -1 * second_entry
return [first_entry,second_entry]
def is_quantum_state(quantum_state):
length_square = 0
for i in range(len(quantum_state)):
length_square += quantum_state[i]**2
print("summation of entry squares is",length_square)
# there might be precision problem
# the length may be very close to 1 but not exactly 1
# so we use the following trick
if (length_square - 1)**2 < 0.00000001: return True
return False # else
# define a function for Hadamard multiplication
def hadamard(quantum_state):
result_quantum_state = [0,0] # define with zero entries
result_quantum_state[0] = (1/(2**0.5)) * quantum_state[0] + (1/(2**0.5)) * quantum_state[1]
result_quantum_state[1] = (1/(2**0.5)) * quantum_state[0] - (1/(2**0.5)) * quantum_state[1]
return result_quantum_state
# we are ready
for i in range(10):
picked_quantum_state=random_quantum_state()
print(picked_quantum_state,"this is randomly picked quantum state")
new_quantum_state = hadamard(picked_quantum_state)
print(new_quantum_state,"this is new quantum state")
print("Is it valid?",is_quantum_state(new_quantum_state))
print() # print an empty line
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
import numpy as np
from qiskit import *
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
s = 101011
from qiskit import *
qc = QuantumCircuit(6+1,6)
qc.h([0,1,2,3,4,5])
qc.draw('mpl')
qc.x(6)
qc.h(6)
qc.barrier()
qc.draw('mpl')
qc.cx(5, 6)
qc.cx(3, 6)
qc.cx(1, 6)
qc.cx(0, 6)
qc.barrier()
qc.draw('mpl')
qc.h([0,1,2,3,4,5])
qc.draw('mpl')
qc.measure([0,1,2,3,4,5], [0,1,2,3,4,5])
qc.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 1).result()
counts =result.get_counts()
print(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw('mpl')
|
https://github.com/drobiu/quantum-project
|
drobiu
|
import json
import logging
import numpy as np
import warnings
from functools import wraps
from typing import Any, Callable, Optional, Tuple, Union
from qiskit import IBMQ, QuantumCircuit, assemble
from qiskit.circuit import Barrier, Gate, Instruction, Measure
from qiskit.circuit.library import UGate, U3Gate, CXGate
from qiskit.providers.ibmq import AccountProvider, IBMQProviderError
from qiskit.providers.ibmq.job import IBMQJob
def get_provider() -> AccountProvider:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
ibmq_logger = logging.getLogger('qiskit.providers.ibmq')
current_level = ibmq_logger.level
ibmq_logger.setLevel(logging.ERROR)
# get provider
try:
provider = IBMQ.get_provider()
except IBMQProviderError:
provider = IBMQ.load_account()
ibmq_logger.setLevel(current_level)
return provider
def get_job(job_id: str) -> Optional[IBMQJob]:
try:
job = get_provider().backends.retrieve_job(job_id)
return job
except Exception:
pass
return None
def circuit_to_json(qc: QuantumCircuit) -> str:
class _QobjEncoder(json.encoder.JSONEncoder):
def default(self, obj: Any) -> Any:
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return (obj.real, obj.imag)
return json.JSONEncoder.default(self, obj)
return json.dumps(circuit_to_dict(qc), cls=_QobjEncoder)
def circuit_to_dict(qc: QuantumCircuit) -> dict:
qobj = assemble(qc)
return qobj.to_dict()
def get_job_urls(job: Union[str, IBMQJob]) -> Tuple[bool, Optional[str], Optional[str]]:
try:
job_id = job.job_id() if isinstance(job, IBMQJob) else job
download_url = get_provider()._api_client.account_api.job(job_id).download_url()['url']
result_url = get_provider()._api_client.account_api.job(job_id).result_url()['url']
return download_url, result_url
except Exception:
return None, None
def cached(key_function: Callable) -> Callable:
def _decorator(f: Any) -> Callable:
f.__cache = {}
@wraps(f)
def _decorated(*args: Any, **kwargs: Any) -> int:
key = key_function(*args, **kwargs)
if key not in f.__cache:
f.__cache[key] = f(*args, **kwargs)
return f.__cache[key]
return _decorated
return _decorator
def gate_key(gate: Gate) -> Tuple[str, int]:
return gate.name, gate.num_qubits
@cached(gate_key)
def gate_cost(gate: Gate) -> int:
if isinstance(gate, (UGate, U3Gate)):
return 1
elif isinstance(gate, CXGate):
return 10
elif isinstance(gate, (Measure, Barrier)):
return 0
return sum(map(gate_cost, (g for g, _, _ in gate.definition.data)))
def compute_cost(circuit: Union[Instruction, QuantumCircuit]) -> int:
print('Computing cost...')
circuit_data = None
if isinstance(circuit, QuantumCircuit):
circuit_data = circuit.data
elif isinstance(circuit, Instruction):
circuit_data = circuit.definition.data
else:
raise Exception(f'Unable to obtain circuit data from {type(circuit)}')
return sum(map(gate_cost, (g for g, _, _ in circuit_data)))
def uses_multiqubit_gate(circuit: QuantumCircuit) -> bool:
circuit_data = None
if isinstance(circuit, QuantumCircuit):
circuit_data = circuit.data
elif isinstance(circuit, Instruction) and circuit.definition is not None:
circuit_data = circuit.definition.data
else:
raise Exception(f'Unable to obtain circuit data from {type(circuit)}')
for g, _, _ in circuit_data:
if isinstance(g, (Barrier, Measure)):
continue
elif isinstance(g, Gate):
if g.num_qubits > 1:
return True
elif isinstance(g, (QuantumCircuit, Instruction)) and uses_multiqubit_gate(g):
return True
return False
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
from numpy.random import rand
from qiskit import transpile
## The Receiver entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Receiver(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Decode the message measuring the circuit (density-dependent)
def decode_quantum_message(self, message, density, backend):
## The values of the participant
self.values = []
for i, qc in enumerate(message):
qc.barrier()
if rand() < density:
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
qc.measure(0, 0)
transpiled_qc = transpile(qc, backend=backend)
result = backend.run(transpiled_qc, shots=1, memory=True).result()
measured_bit = int(result.get_memory()[0])
self.values.append(measured_bit)
else:
self.values.append(-1)
return message
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit.circuit import Parameter
from qiskit import pulse
from qiskit.test.mock.backends.almaden import *
phase = Parameter('phase')
with pulse.build(FakeAlmaden()) as phase_test_sched:
pulse.shift_phase(phase, pulse.drive_channel(0))
phase_test_sched.instructions # ()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
from qiskit.transpiler.passes import UnitarySynthesis
circuit = QuantumCircuit(1)
circuit.rx(0.8, 0)
unitary = Operator(circuit).data
unitary_circ = QuantumCircuit(1)
unitary_circ.unitary(unitary, [0])
synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk")
out = synth(unitary_circ)
out.draw('mpl')
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 6 12:18:27 2022
@author: pejmanjouzdani
"""
import numpy as np
from qiskit.circuit.exceptions import CircuitError
from qiskit import QuantumCircuit
def getQCirc(circ_U, Q):
#############
# Qiskit error
if not isinstance(circ_U, QuantumCircuit):
raise CircuitError('The circuit is not an instance of the QuantumCircuit')
# TypeError
if not isinstance(Q, np.ndarray):
if not isinstance(Q, list):
raise TypeError(' the provided Pauli string operator is not am instance of list or numpy array ')
#############
circ_Q = QuantumCircuit.copy(circ_U)
#############
# ValueError
### the number of qubits must be the same as number of operators in Q
if not circ_Q.num_qubits == len(Q):
raise ValueError('the number of qubits in the circuit is not the same as the number of Pauli operators in Q')
#############
for (q, o) in enumerate(Q):
if o==0:
pass
if o==1:
circ_Q.x(q)
if o==2:
circ_Q.y(q)
if o==3:
circ_Q.z(q)
return circ_Q
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test circuits with variable parameters."""
import unittest
import cmath
import math
import copy
import pickle
from operator import add, mul, sub, truediv
from test import combine
import numpy
from ddt import data, ddt, named_data
import qiskit
import qiskit.circuit.library as circlib
from qiskit.circuit.library.standard_gates.rz import RZGate
from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.circuit import Gate, Instruction, Parameter, ParameterExpression, ParameterVector
from qiskit.circuit.parametertable import ParameterReferences, ParameterTable, ParameterView
from qiskit.circuit.exceptions import CircuitError
from qiskit.compiler import assemble, transpile
from qiskit.execute_function import execute
from qiskit import pulse
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOurense
from qiskit.tools import parallel_map
def raise_if_parameter_table_invalid(circuit):
"""Validates the internal consistency of a ParameterTable and its
containing QuantumCircuit. Intended for use in testing.
Raises:
CircuitError: if QuantumCircuit and ParameterTable are inconsistent.
"""
table = circuit._parameter_table
# Assert parameters present in circuit match those in table.
circuit_parameters = {
parameter
for instruction in circuit._data
for param in instruction.operation.params
for parameter in param.parameters
if isinstance(param, ParameterExpression)
}
table_parameters = set(table._table.keys())
if circuit_parameters != table_parameters:
raise CircuitError(
"Circuit/ParameterTable Parameter mismatch. "
"Circuit parameters: {}. "
"Table parameters: {}.".format(circuit_parameters, table_parameters)
)
# Assert parameter locations in table are present in circuit.
circuit_instructions = [instr.operation for instr in circuit._data]
for parameter, instr_list in table.items():
for instr, param_index in instr_list:
if instr not in circuit_instructions:
raise CircuitError(f"ParameterTable instruction not present in circuit: {instr}.")
if not isinstance(instr.params[param_index], ParameterExpression):
raise CircuitError(
"ParameterTable instruction does not have a "
"ParameterExpression at param_index {}: {}."
"".format(param_index, instr)
)
if parameter not in instr.params[param_index].parameters:
raise CircuitError(
"ParameterTable instruction parameters does "
"not match ParameterTable key. Instruction "
"parameters: {} ParameterTable key: {}."
"".format(instr.params[param_index].parameters, parameter)
)
# Assert circuit has no other parameter locations other than those in table.
for instruction in circuit._data:
for param_index, param in enumerate(instruction.operation.params):
if isinstance(param, ParameterExpression):
parameters = param.parameters
for parameter in parameters:
if (instruction.operation, param_index) not in table[parameter]:
raise CircuitError(
"Found parameterized instruction not "
"present in table. Instruction: {} "
"param_index: {}".format(instruction.operation, param_index)
)
@ddt
class TestParameters(QiskitTestCase):
"""Test Parameters."""
def test_gate(self):
"""Test instantiating gate with variable parameters"""
theta = Parameter("θ")
theta_gate = Gate("test", 1, params=[theta])
self.assertEqual(theta_gate.name, "test")
self.assertIsInstance(theta_gate.params[0], Parameter)
def test_compile_quantum_circuit(self):
"""Test instantiating gate with variable parameters"""
theta = Parameter("θ")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
backend = BasicAer.get_backend("qasm_simulator")
qc_aer = transpile(qc, backend)
self.assertIn(theta, qc_aer.parameters)
def test_duplicate_name_on_append(self):
"""Test adding a second parameter object with the same name fails."""
param_a = Parameter("a")
param_a_again = Parameter("a")
qc = QuantumCircuit(1)
qc.rx(param_a, 0)
self.assertRaises(CircuitError, qc.rx, param_a_again, 0)
def test_get_parameters(self):
"""Test instantiating gate with variable parameters"""
from qiskit.circuit.library.standard_gates.rx import RXGate
theta = Parameter("θ")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
rxg = RXGate(theta)
qc.append(rxg, [qr[0]], [])
vparams = qc._parameter_table
self.assertEqual(len(vparams), 1)
self.assertIs(theta, next(iter(vparams)))
self.assertEqual(rxg, next(iter(vparams[theta]))[0])
def test_get_parameters_by_index(self):
"""Test getting parameters by index"""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
v = ParameterVector("v", 3)
qc = QuantumCircuit(1)
qc.rx(x, 0)
qc.rz(z, 0)
qc.ry(y, 0)
qc.u(*v, 0)
self.assertEqual(x, qc.parameters[3])
self.assertEqual(y, qc.parameters[4])
self.assertEqual(z, qc.parameters[5])
for i, vi in enumerate(v):
self.assertEqual(vi, qc.parameters[i])
def test_bind_parameters_anonymously(self):
"""Test setting parameters by insertion order anonymously"""
phase = Parameter("phase")
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
v = ParameterVector("v", 3)
qc = QuantumCircuit(1, global_phase=phase)
qc.rx(x, 0)
qc.rz(z, 0)
qc.ry(y, 0)
qc.u(*v, 0)
params = [0.1 * i for i in range(len(qc.parameters))]
order = [phase] + v[:] + [x, y, z]
param_dict = dict(zip(order, params))
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
bqc_anonymous = getattr(qc, assign_fun)(params)
bqc_list = getattr(qc, assign_fun)(param_dict)
self.assertEqual(bqc_anonymous, bqc_list)
def test_bind_parameters_allow_unknown(self):
"""Test binding parameters allowing unknown parameters."""
a = Parameter("a")
b = Parameter("b")
c = a.bind({a: 1, b: 1}, allow_unknown_parameters=True)
self.assertEqual(c, a.bind({a: 1}))
@data(QuantumCircuit.assign_parameters, QuantumCircuit.bind_parameters)
def test_bind_parameters_custom_definition_global_phase(self, assigner):
"""Test that a custom gate with a parametrised `global_phase` is assigned correctly."""
x = Parameter("x")
custom = QuantumCircuit(1, global_phase=x).to_gate()
base = QuantumCircuit(1)
base.append(custom, [0], [])
test = Operator(assigner(base, {x: math.pi}))
expected = Operator(numpy.array([[-1, 0], [0, -1]]))
self.assertEqual(test, expected)
def test_bind_half_single_precision(self):
"""Test binding with 16bit and 32bit floats."""
phase = Parameter("phase")
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
v = ParameterVector("v", 3)
for i in (numpy.float16, numpy.float32):
with self.subTest(float_type=i):
expr = (v[0] * (x + y + z) + phase) - (v[2] * v[1])
params = numpy.array([0.1 * j for j in range(8)], dtype=i)
order = [phase] + v[:] + [x, y, z]
param_dict = dict(zip(order, params))
bound_value = expr.bind(param_dict)
self.assertAlmostEqual(float(bound_value), 0.09, delta=1e-4)
def test_parameter_order(self):
"""Test the parameters are sorted by name but parameter vector order takes precedence.
This means that the following set of parameters
{a, z, x[0], x[1], x[2], x[3], x[10], x[11]}
will be sorted as
[a, x[0], x[1], x[2], x[3], x[10], x[11], z]
"""
a, b, some_name, z = (Parameter(name) for name in ["a", "b", "some_name", "z"])
x = ParameterVector("x", 12)
a_vector = ParameterVector("a_vector", 15)
qc = QuantumCircuit(2)
qc.p(z, 0)
for i, x_i in enumerate(reversed(x)):
qc.rx(x_i, i % 2)
qc.cry(a, 0, 1)
qc.crz(some_name, 1, 0)
for v_i in a_vector[::2]:
qc.p(v_i, 0)
for v_i in a_vector[1::2]:
qc.p(v_i, 1)
qc.p(b, 0)
expected_order = [a] + a_vector[:] + [b, some_name] + x[:] + [z]
actual_order = qc.parameters
self.assertListEqual(expected_order, list(actual_order))
@data(True, False)
def test_parameter_order_compose(self, front):
"""Test the parameter order is correctly maintained upon composing circuits."""
x = Parameter("x")
y = Parameter("y")
qc1 = QuantumCircuit(1)
qc1.p(x, 0)
qc2 = QuantumCircuit(1)
qc2.rz(y, 0)
order = [x, y]
composed = qc1.compose(qc2, front=front)
self.assertListEqual(list(composed.parameters), order)
def test_parameter_order_append(self):
"""Test the parameter order is correctly maintained upon appending circuits."""
x = Parameter("x")
y = Parameter("y")
qc1 = QuantumCircuit(1)
qc1.p(x, 0)
qc2 = QuantumCircuit(1)
qc2.rz(y, 0)
qc1.append(qc2, [0])
self.assertListEqual(list(qc1.parameters), [x, y])
def test_parameter_order_composing_nested_circuit(self):
"""Test the parameter order after nesting circuits and instructions."""
x = ParameterVector("x", 5)
inner = QuantumCircuit(1)
inner.rx(x[0], [0])
mid = QuantumCircuit(2)
mid.p(x[1], 1)
mid.append(inner, [0])
mid.p(x[2], 0)
mid.append(inner, [0])
outer = QuantumCircuit(2)
outer.compose(mid, inplace=True)
outer.ryy(x[3], 0, 1)
outer.compose(inner, inplace=True)
outer.rz(x[4], 0)
order = [x[0], x[1], x[2], x[3], x[4]]
self.assertListEqual(list(outer.parameters), order)
def test_is_parameterized(self):
"""Test checking if a gate is parameterized (bound/unbound)"""
from qiskit.circuit.library.standard_gates.h import HGate
from qiskit.circuit.library.standard_gates.rx import RXGate
theta = Parameter("θ")
rxg = RXGate(theta)
self.assertTrue(rxg.is_parameterized())
theta_bound = theta.bind({theta: 3.14})
rxg = RXGate(theta_bound)
self.assertFalse(rxg.is_parameterized())
h_gate = HGate()
self.assertFalse(h_gate.is_parameterized())
def test_fix_variable(self):
"""Test setting a variable to a constant value"""
theta = Parameter("θ")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
qc.u(0, theta, 0, qr)
# test for both `bind_parameters` and `assign_parameters`
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
bqc = getattr(qc, assign_fun)({theta: 0.5})
self.assertEqual(float(bqc.data[0].operation.params[0]), 0.5)
self.assertEqual(float(bqc.data[1].operation.params[1]), 0.5)
bqc = getattr(qc, assign_fun)({theta: 0.6})
self.assertEqual(float(bqc.data[0].operation.params[0]), 0.6)
self.assertEqual(float(bqc.data[1].operation.params[1]), 0.6)
def test_multiple_parameters(self):
"""Test setting multiple parameters"""
theta = Parameter("θ")
x = Parameter("x")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
qc.u(0, theta, x, qr)
self.assertEqual(qc.parameters, {theta, x})
def test_multiple_named_parameters(self):
"""Test setting multiple named/keyword argument based parameters"""
theta = Parameter(name="θ")
x = Parameter(name="x")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
qc.u(0, theta, x, qr)
self.assertEqual(theta.name, "θ")
self.assertEqual(qc.parameters, {theta, x})
@named_data(
["int", 2, int],
["float", 2.5, float],
["float16", numpy.float16(2.5), float],
["float32", numpy.float32(2.5), float],
["float64", numpy.float64(2.5), float],
)
def test_circuit_assignment_to_numeric(self, value, type_):
"""Test binding a numeric value to a circuit instruction"""
x = Parameter("x")
qc = QuantumCircuit(1)
qc.append(Instruction("inst", 1, 0, [x]), (0,))
qc.assign_parameters({x: value}, inplace=True)
bound = qc.data[0].operation.params[0]
self.assertIsInstance(bound, type_)
self.assertEqual(bound, value)
def test_partial_binding(self):
"""Test that binding a subset of circuit parameters returns a new parameterized circuit."""
theta = Parameter("θ")
x = Parameter("x")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
qc.u(0, theta, x, qr)
# test for both `bind_parameters` and `assign_parameters`
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
pqc = getattr(qc, assign_fun)({theta: 2})
self.assertEqual(pqc.parameters, {x})
self.assertEqual(float(pqc.data[0].operation.params[0]), 2)
self.assertEqual(float(pqc.data[1].operation.params[1]), 2)
@data(True, False)
def test_mixed_binding(self, inplace):
"""Test we can bind a mixed dict with Parameter objects and floats."""
theta = Parameter("θ")
x, new_x = Parameter("x"), Parameter("new_x")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
qc.u(0, theta, x, qr)
pqc = qc.assign_parameters({theta: 2, x: new_x}, inplace=inplace)
if inplace:
self.assertEqual(qc.parameters, {new_x})
else:
self.assertEqual(pqc.parameters, {new_x})
def test_expression_partial_binding(self):
"""Test that binding a subset of expression parameters returns a new
parameterized circuit."""
theta = Parameter("θ")
phi = Parameter("phi")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta + phi, qr)
# test for both `bind_parameters` and `assign_parameters`
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
pqc = getattr(qc, assign_fun)({theta: 2})
self.assertEqual(pqc.parameters, {phi})
self.assertTrue(isinstance(pqc.data[0].operation.params[0], ParameterExpression))
self.assertEqual(str(pqc.data[0].operation.params[0]), "phi + 2")
fbqc = getattr(pqc, assign_fun)({phi: 1.0})
self.assertEqual(fbqc.parameters, set())
self.assertIsInstance(fbqc.data[0].operation.params[0], float)
self.assertEqual(float(fbqc.data[0].operation.params[0]), 3)
def test_two_parameter_expression_binding(self):
"""Verify that for a circuit with parameters theta and phi that
we can correctly assign theta to -phi.
"""
theta = Parameter("theta")
phi = Parameter("phi")
qc = QuantumCircuit(1)
qc.rx(theta, 0)
qc.ry(phi, 0)
self.assertEqual(len(qc._parameter_table[theta]), 1)
self.assertEqual(len(qc._parameter_table[phi]), 1)
qc.assign_parameters({theta: -phi}, inplace=True)
self.assertEqual(len(qc._parameter_table[phi]), 2)
def test_expression_partial_binding_zero(self):
"""Verify that binding remains possible even if a previous partial bind
would reduce the expression to zero.
"""
theta = Parameter("theta")
phi = Parameter("phi")
qc = QuantumCircuit(1)
qc.p(theta * phi, 0)
# test for both `bind_parameters` and `assign_parameters`
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
pqc = getattr(qc, assign_fun)({theta: 0})
self.assertEqual(pqc.parameters, {phi})
self.assertTrue(isinstance(pqc.data[0].operation.params[0], ParameterExpression))
self.assertEqual(str(pqc.data[0].operation.params[0]), "0")
fbqc = getattr(pqc, assign_fun)({phi: 1})
self.assertEqual(fbqc.parameters, set())
self.assertIsInstance(fbqc.data[0].operation.params[0], int)
self.assertEqual(float(fbqc.data[0].operation.params[0]), 0)
def test_raise_if_assigning_params_not_in_circuit(self):
"""Verify binding parameters which are not present in the circuit raises an error."""
x = Parameter("x")
y = Parameter("y")
z = ParameterVector("z", 3)
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
# test for both `bind_parameters` and `assign_parameters`
for assign_fun in ["bind_parameters", "assign_parameters"]:
qc = QuantumCircuit(qr)
with self.subTest(assign_fun=assign_fun):
qc.p(0.1, qr[0])
self.assertRaises(CircuitError, getattr(qc, assign_fun), {x: 1})
qc.p(x, qr[0])
self.assertRaises(CircuitError, getattr(qc, assign_fun), {x: 1, y: 2})
qc.p(z[1], qr[0])
self.assertRaises(CircuitError, getattr(qc, assign_fun), {z: [3, 4, 5]})
self.assertRaises(CircuitError, getattr(qc, assign_fun), {"a_str": 6})
self.assertRaises(CircuitError, getattr(qc, assign_fun), {None: 7})
def test_gate_multiplicity_binding(self):
"""Test binding when circuit contains multiple references to same gate"""
qc = QuantumCircuit(1)
theta = Parameter("theta")
gate = RZGate(theta)
qc.append(gate, [0], [])
qc.append(gate, [0], [])
# test for both `bind_parameters` and `assign_parameters`
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
qc2 = getattr(qc, assign_fun)({theta: 1.0})
self.assertEqual(len(qc2._parameter_table), 0)
for instruction in qc2.data:
self.assertEqual(float(instruction.operation.params[0]), 1.0)
def test_calibration_assignment(self):
"""That that calibration mapping and the schedules they map are assigned together."""
theta = Parameter("theta")
circ = QuantumCircuit(3, 3)
circ.append(Gate("rxt", 1, [theta]), [0])
circ.measure(0, 0)
rxt_q0 = pulse.Schedule(
pulse.Play(
pulse.library.Gaussian(duration=128, sigma=16, amp=0.2 * theta / 3.14),
pulse.DriveChannel(0),
)
)
circ.add_calibration("rxt", [0], rxt_q0, [theta])
circ = circ.assign_parameters({theta: 3.14})
instruction = circ.data[0]
cal_key = (
tuple(circ.find_bit(q).index for q in instruction.qubits),
tuple(instruction.operation.params),
)
self.assertEqual(cal_key, ((0,), (3.14,)))
# Make sure that key from instruction data matches the calibrations dictionary
self.assertIn(cal_key, circ.calibrations["rxt"])
sched = circ.calibrations["rxt"][cal_key]
self.assertEqual(sched.instructions[0][1].pulse.amp, 0.2)
def test_calibration_assignment_doesnt_mutate(self):
"""That that assignment doesn't mutate the original circuit."""
theta = Parameter("theta")
circ = QuantumCircuit(3, 3)
circ.append(Gate("rxt", 1, [theta]), [0])
circ.measure(0, 0)
rxt_q0 = pulse.Schedule(
pulse.Play(
pulse.library.Gaussian(duration=128, sigma=16, amp=0.2 * theta / 3.14),
pulse.DriveChannel(0),
)
)
circ.add_calibration("rxt", [0], rxt_q0, [theta])
circ_copy = copy.deepcopy(circ)
assigned_circ = circ.assign_parameters({theta: 3.14})
self.assertEqual(circ.calibrations, circ_copy.calibrations)
self.assertNotEqual(assigned_circ.calibrations, circ.calibrations)
def test_calibration_assignment_w_expressions(self):
"""That calibrations with multiple parameters are assigned correctly"""
theta = Parameter("theta")
sigma = Parameter("sigma")
circ = QuantumCircuit(3, 3)
circ.append(Gate("rxt", 1, [theta / 2, sigma]), [0])
circ.measure(0, 0)
rxt_q0 = pulse.Schedule(
pulse.Play(
pulse.library.Gaussian(duration=128, sigma=4 * sigma, amp=0.2 * theta / 3.14),
pulse.DriveChannel(0),
)
)
circ.add_calibration("rxt", [0], rxt_q0, [theta / 2, sigma])
circ = circ.assign_parameters({theta: 3.14, sigma: 4})
instruction = circ.data[0]
cal_key = (
tuple(circ.find_bit(q).index for q in instruction.qubits),
tuple(instruction.operation.params),
)
self.assertEqual(cal_key, ((0,), (3.14 / 2, 4)))
# Make sure that key from instruction data matches the calibrations dictionary
self.assertIn(cal_key, circ.calibrations["rxt"])
sched = circ.calibrations["rxt"][cal_key]
self.assertEqual(sched.instructions[0][1].pulse.amp, 0.2)
self.assertEqual(sched.instructions[0][1].pulse.sigma, 16)
def test_substitution(self):
"""Test Parameter substitution (vs bind)."""
alpha = Parameter("⍺")
beta = Parameter("beta")
schedule = pulse.Schedule(pulse.ShiftPhase(alpha, pulse.DriveChannel(0)))
circ = QuantumCircuit(3, 3)
circ.append(Gate("my_rz", 1, [alpha]), [0])
circ.add_calibration("my_rz", [0], schedule, [alpha])
circ = circ.assign_parameters({alpha: 2 * beta})
circ = circ.assign_parameters({beta: 1.57})
cal_sched = circ.calibrations["my_rz"][((0,), (3.14,))]
self.assertEqual(float(cal_sched.instructions[0][1].phase), 3.14)
def test_partial_assignment(self):
"""Expressions of parameters with partial assignment."""
alpha = Parameter("⍺")
beta = Parameter("beta")
gamma = Parameter("γ")
phi = Parameter("ϕ")
with pulse.build() as my_cal:
pulse.set_frequency(alpha + beta, pulse.DriveChannel(0))
pulse.shift_frequency(gamma + beta, pulse.DriveChannel(0))
pulse.set_phase(phi, pulse.DriveChannel(1))
circ = QuantumCircuit(2, 2)
circ.append(Gate("custom", 2, [alpha, beta, gamma, phi]), [0, 1])
circ.add_calibration("custom", [0, 1], my_cal, [alpha, beta, gamma, phi])
# Partial bind
delta = 1e9
freq = 4.5e9
shift = 0.5e9
phase = 3.14 / 4
circ = circ.assign_parameters({alpha: freq - delta})
cal_sched = list(circ.calibrations["custom"].values())[0]
self.assertEqual(cal_sched.instructions[0][1].frequency, freq - delta + beta)
circ = circ.assign_parameters({beta: delta})
cal_sched = list(circ.calibrations["custom"].values())[0]
self.assertEqual(float(cal_sched.instructions[0][1].frequency), freq)
self.assertEqual(cal_sched.instructions[1][1].frequency, gamma + delta)
circ = circ.assign_parameters({gamma: shift - delta})
cal_sched = list(circ.calibrations["custom"].values())[0]
self.assertEqual(float(cal_sched.instructions[1][1].frequency), shift)
self.assertEqual(cal_sched.instructions[2][1].phase, phi)
circ = circ.assign_parameters({phi: phase})
cal_sched = list(circ.calibrations["custom"].values())[0]
self.assertEqual(float(cal_sched.instructions[2][1].phase), phase)
def test_circuit_generation(self):
"""Test creating a series of circuits parametrically"""
theta = Parameter("θ")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.rx(theta, qr)
backend = BasicAer.get_backend("qasm_simulator")
qc_aer = transpile(qc, backend)
# generate list of circuits
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
circs = []
theta_list = numpy.linspace(0, numpy.pi, 20)
for theta_i in theta_list:
circs.append(getattr(qc_aer, assign_fun)({theta: theta_i}))
qobj = assemble(circs)
for index, theta_i in enumerate(theta_list):
res = float(qobj.experiments[index].instructions[0].params[0])
self.assertTrue(math.isclose(res, theta_i), f"{res} != {theta_i}")
def test_circuit_composition(self):
"""Test preservation of parameters when combining circuits."""
theta = Parameter("θ")
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc1 = QuantumCircuit(qr, cr)
qc1.rx(theta, qr)
phi = Parameter("phi")
qc2 = QuantumCircuit(qr, cr)
qc2.ry(phi, qr)
qc2.h(qr)
qc2.measure(qr, cr)
qc3 = qc1.compose(qc2)
self.assertEqual(qc3.parameters, {theta, phi})
def test_composite_instruction(self):
"""Test preservation of parameters via parameterized instructions."""
theta = Parameter("θ")
qr1 = QuantumRegister(1, name="qr1")
qc1 = QuantumCircuit(qr1)
qc1.rx(theta, qr1)
qc1.rz(numpy.pi / 2, qr1)
qc1.ry(theta, qr1)
gate = qc1.to_instruction()
self.assertEqual(gate.params, [theta])
phi = Parameter("phi")
qr2 = QuantumRegister(3, name="qr2")
qc2 = QuantumCircuit(qr2)
qc2.ry(phi, qr2[0])
qc2.h(qr2)
qc2.append(gate, qargs=[qr2[1]])
self.assertEqual(qc2.parameters, {theta, phi})
def test_parameter_name_conflicts_raises(self):
"""Verify attempting to add different parameters with matching names raises an error."""
theta1 = Parameter("theta")
theta2 = Parameter("theta")
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.p(theta1, 0)
self.assertRaises(CircuitError, qc.p, theta2, 0)
def test_bind_ryrz_vector(self):
"""Test binding a list of floats to a ParameterVector"""
qc = QuantumCircuit(4)
depth = 4
theta = ParameterVector("θ", length=len(qc.qubits) * depth * 2)
theta_iter = iter(theta)
for _ in range(depth):
for q in qc.qubits:
qc.ry(next(theta_iter), q)
qc.rz(next(theta_iter), q)
for i, q in enumerate(qc.qubits[:-1]):
qc.cx(qc.qubits[i], qc.qubits[i + 1])
qc.barrier()
theta_vals = numpy.linspace(0, 1, len(theta)) * numpy.pi
self.assertEqual(set(qc.parameters), set(theta.params))
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
bqc = getattr(qc, assign_fun)({theta: theta_vals})
for instruction in bqc.data:
if hasattr(instruction.operation, "params") and instruction.operation.params:
self.assertIn(float(instruction.operation.params[0]), theta_vals)
def test_compile_vector(self):
"""Test compiling a circuit with an unbound ParameterVector"""
qc = QuantumCircuit(4)
depth = 4
theta = ParameterVector("θ", length=len(qc.qubits) * depth * 2)
theta_iter = iter(theta)
for _ in range(depth):
for q in qc.qubits:
qc.ry(next(theta_iter), q)
qc.rz(next(theta_iter), q)
for i, q in enumerate(qc.qubits[:-1]):
qc.cx(qc.qubits[i], qc.qubits[i + 1])
qc.barrier()
backend = BasicAer.get_backend("qasm_simulator")
qc_aer = transpile(qc, backend)
for param in theta:
self.assertIn(param, qc_aer.parameters)
def test_instruction_ryrz_vector(self):
"""Test constructing a circuit from instructions with remapped ParameterVectors"""
qubits = 5
depth = 4
ryrz = QuantumCircuit(qubits, name="ryrz")
theta = ParameterVector("θ0", length=len(ryrz.qubits) * 2)
theta_iter = iter(theta)
for q in ryrz.qubits:
ryrz.ry(next(theta_iter), q)
ryrz.rz(next(theta_iter), q)
cxs = QuantumCircuit(qubits - 1, name="cxs")
for i, _ in enumerate(cxs.qubits[:-1:2]):
cxs.cx(cxs.qubits[2 * i], cxs.qubits[2 * i + 1])
paramvecs = []
qc = QuantumCircuit(qubits)
for i in range(depth):
theta_l = ParameterVector(f"θ{i + 1}", length=len(ryrz.qubits) * 2)
ryrz_inst = ryrz.to_instruction(parameter_map={theta: theta_l})
paramvecs += [theta_l]
qc.append(ryrz_inst, qargs=qc.qubits)
qc.append(cxs, qargs=qc.qubits[1:])
qc.append(cxs, qargs=qc.qubits[:-1])
qc.barrier()
backend = BasicAer.get_backend("qasm_simulator")
qc_aer = transpile(qc, backend)
for vec in paramvecs:
for param in vec:
self.assertIn(param, qc_aer.parameters)
@data("single", "vector")
def test_parameter_equality_through_serialization(self, ptype):
"""Verify parameters maintain their equality after serialization."""
if ptype == "single":
x1 = Parameter("x")
x2 = Parameter("x")
else:
x1 = ParameterVector("x", 2)[0]
x2 = ParameterVector("x", 2)[0]
x1_p = pickle.loads(pickle.dumps(x1))
x2_p = pickle.loads(pickle.dumps(x2))
self.assertEqual(x1, x1_p)
self.assertEqual(x2, x2_p)
self.assertNotEqual(x1, x2_p)
self.assertNotEqual(x2, x1_p)
def test_binding_parameterized_circuits_built_in_multiproc(self):
"""Verify subcircuits built in a subprocess can still be bound."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2429
num_processes = 4
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
parameters = [Parameter(f"x{i}") for i in range(num_processes)]
results = parallel_map(
_construct_circuit, parameters, task_args=(qr,), num_processes=num_processes
)
for qc in results:
circuit.compose(qc, inplace=True)
parameter_values = [{x: 1.0 for x in parameters}]
qobj = assemble(
circuit,
backend=BasicAer.get_backend("qasm_simulator"),
parameter_binds=parameter_values,
)
self.assertEqual(len(qobj.experiments), 1)
self.assertEqual(len(qobj.experiments[0].instructions), 4)
self.assertTrue(
all(
len(inst.params) == 1
and isinstance(inst.params[0], float)
and float(inst.params[0]) == 1
for inst in qobj.experiments[0].instructions
)
)
def test_transpiling_multiple_parameterized_circuits(self):
"""Verify several parameterized circuits can be transpiled at once."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2864
qr = QuantumRegister(1)
qc1 = QuantumCircuit(qr)
qc2 = QuantumCircuit(qr)
theta = Parameter("theta")
qc1.u(theta, 0, 0, qr[0])
qc2.u(theta, 3.14, 0, qr[0])
circuits = [qc1, qc2]
job = execute(
circuits,
BasicAer.get_backend("unitary_simulator"),
shots=512,
parameter_binds=[{theta: 1}],
)
self.assertTrue(len(job.result().results), 2)
@data(0, 1, 2, 3)
def test_transpile_across_optimization_levels(self, opt_level):
"""Verify parameterized circuits can be transpiled with all default pass managers."""
qc = QuantumCircuit(5, 5)
theta = Parameter("theta")
phi = Parameter("phi")
qc.rx(theta, 0)
qc.x(0)
for i in range(5 - 1):
qc.rxx(phi, i, i + 1)
qc.measure(range(5 - 1), range(5 - 1))
transpile(qc, FakeOurense(), optimization_level=opt_level)
def test_repeated_gates_to_dag_and_back(self):
"""Verify circuits with repeated parameterized gates can be converted
to DAG and back, maintaining consistency of circuit._parameter_table."""
from qiskit.converters import circuit_to_dag, dag_to_circuit
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.p(theta, qr[0])
double_qc = qc.compose(qc)
test_qc = dag_to_circuit(circuit_to_dag(double_qc))
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
bound_test_qc = getattr(test_qc, assign_fun)({theta: 1})
self.assertEqual(len(bound_test_qc.parameters), 0)
def test_rebinding_instruction_copy(self):
"""Test rebinding a copied instruction does not modify the original."""
theta = Parameter("th")
qc = QuantumCircuit(1)
qc.rx(theta, 0)
instr = qc.to_instruction()
qc1 = QuantumCircuit(1)
qc1.append(instr, [0])
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
output1 = getattr(qc1, assign_fun)({theta: 0.1}).decompose()
output2 = getattr(qc1, assign_fun)({theta: 0.2}).decompose()
expected1 = QuantumCircuit(1)
expected1.rx(0.1, 0)
expected2 = QuantumCircuit(1)
expected2.rx(0.2, 0)
self.assertEqual(expected1, output1)
self.assertEqual(expected2, output2)
@combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"])
def test_decompose_propagates_bound_parameters(self, target_type, parameter_type):
"""Verify bind-before-decompose preserves bound values."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2482
theta = Parameter("th")
qc = QuantumCircuit(1)
qc.rx(theta, 0)
if target_type == "gate":
inst = qc.to_gate()
elif target_type == "instruction":
inst = qc.to_instruction()
qc2 = QuantumCircuit(1)
qc2.append(inst, [0])
if parameter_type == "numbers":
bound_qc2 = qc2.assign_parameters({theta: 0.5})
expected_parameters = set()
expected_qc2 = QuantumCircuit(1)
expected_qc2.rx(0.5, 0)
else:
phi = Parameter("ph")
bound_qc2 = qc2.assign_parameters({theta: phi})
expected_parameters = {phi}
expected_qc2 = QuantumCircuit(1)
expected_qc2.rx(phi, 0)
decomposed_qc2 = bound_qc2.decompose()
with self.subTest(msg="testing parameters of initial circuit"):
self.assertEqual(qc2.parameters, {theta})
with self.subTest(msg="testing parameters of bound circuit"):
self.assertEqual(bound_qc2.parameters, expected_parameters)
with self.subTest(msg="testing parameters of deep decomposed bound circuit"):
self.assertEqual(decomposed_qc2.parameters, expected_parameters)
with self.subTest(msg="testing deep decomposed circuit"):
self.assertEqual(decomposed_qc2, expected_qc2)
@combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"])
def test_decompose_propagates_deeply_bound_parameters(self, target_type, parameter_type):
"""Verify bind-before-decompose preserves deeply bound values."""
theta = Parameter("th")
qc1 = QuantumCircuit(1)
qc1.rx(theta, 0)
if target_type == "gate":
inst = qc1.to_gate()
elif target_type == "instruction":
inst = qc1.to_instruction()
qc2 = QuantumCircuit(1)
qc2.append(inst, [0])
if target_type == "gate":
inst = qc2.to_gate()
elif target_type == "instruction":
inst = qc2.to_instruction()
qc3 = QuantumCircuit(1)
qc3.append(inst, [0])
if parameter_type == "numbers":
bound_qc3 = qc3.assign_parameters({theta: 0.5})
expected_parameters = set()
expected_qc3 = QuantumCircuit(1)
expected_qc3.rx(0.5, 0)
else:
phi = Parameter("ph")
bound_qc3 = qc3.assign_parameters({theta: phi})
expected_parameters = {phi}
expected_qc3 = QuantumCircuit(1)
expected_qc3.rx(phi, 0)
deep_decomposed_qc3 = bound_qc3.decompose().decompose()
with self.subTest(msg="testing parameters of initial circuit"):
self.assertEqual(qc3.parameters, {theta})
with self.subTest(msg="testing parameters of bound circuit"):
self.assertEqual(bound_qc3.parameters, expected_parameters)
with self.subTest(msg="testing parameters of deep decomposed bound circuit"):
self.assertEqual(deep_decomposed_qc3.parameters, expected_parameters)
with self.subTest(msg="testing deep decomposed circuit"):
self.assertEqual(deep_decomposed_qc3, expected_qc3)
@data("gate", "instruction")
def test_executing_parameterized_instruction_bound_early(self, target_type):
"""Verify bind-before-execute preserves bound values."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2482
theta = Parameter("theta")
sub_qc = QuantumCircuit(2)
sub_qc.h(0)
sub_qc.cx(0, 1)
sub_qc.rz(theta, [0, 1])
sub_qc.cx(0, 1)
sub_qc.h(0)
if target_type == "gate":
sub_inst = sub_qc.to_gate()
elif target_type == "instruction":
sub_inst = sub_qc.to_instruction()
unbound_qc = QuantumCircuit(2, 1)
unbound_qc.append(sub_inst, [0, 1], [])
unbound_qc.measure(0, 0)
for assign_fun in ["bind_parameters", "assign_parameters"]:
with self.subTest(assign_fun=assign_fun):
bound_qc = getattr(unbound_qc, assign_fun)({theta: numpy.pi / 2})
shots = 1024
job = execute(bound_qc, backend=BasicAer.get_backend("qasm_simulator"), shots=shots)
self.assertDictAlmostEqual(job.result().get_counts(), {"1": shots}, 0.05 * shots)
def test_num_parameters(self):
"""Test the num_parameters property."""
with self.subTest(msg="standard case"):
theta = Parameter("θ")
x = Parameter("x")
qc = QuantumCircuit(1)
qc.rx(theta, 0)
qc.u(0, theta, x, 0)
self.assertEqual(qc.num_parameters, 2)
with self.subTest(msg="parameter vector"):
params = ParameterVector("x", length=3)
qc = QuantumCircuit(4)
qc.rx(params[0], 2)
qc.ry(params[1], 1)
qc.rz(params[2], 3)
self.assertEqual(qc.num_parameters, 3)
with self.subTest(msg="no params"):
qc = QuantumCircuit(1)
qc.x(0)
self.assertEqual(qc.num_parameters, 0)
def test_execute_result_names(self):
"""Test unique names for list of parameter binds."""
theta = Parameter("θ")
reps = 5
qc = QuantumCircuit(1, 1)
qc.rx(theta, 0)
qc.measure(0, 0)
plist = [{theta: i} for i in range(reps)]
simulator = BasicAer.get_backend("qasm_simulator")
result = execute(qc, backend=simulator, parameter_binds=plist).result()
result_names = {res.name for res in result.results}
self.assertEqual(reps, len(result_names))
def test_to_instruction_after_inverse(self):
"""Verify converting an inverse generates a valid ParameterTable"""
# ref: https://github.com/Qiskit/qiskit-terra/issues/4235
qc = QuantumCircuit(1)
theta = Parameter("theta")
qc.rz(theta, 0)
inv_instr = qc.inverse().to_instruction()
self.assertIsInstance(inv_instr, Instruction)
def test_repeated_circuit(self):
"""Test repeating a circuit maintains the parameters."""
qc = QuantumCircuit(1)
theta = Parameter("theta")
qc.rz(theta, 0)
rep = qc.repeat(3)
self.assertEqual(rep.parameters, {theta})
def test_copy_after_inverse(self):
"""Verify circuit.inverse generates a valid ParameterTable."""
qc = QuantumCircuit(1)
theta = Parameter("theta")
qc.rz(theta, 0)
inverse = qc.inverse()
self.assertIn(theta, inverse.parameters)
raise_if_parameter_table_invalid(inverse)
def test_copy_after_reverse(self):
"""Verify circuit.reverse generates a valid ParameterTable."""
qc = QuantumCircuit(1)
theta = Parameter("theta")
qc.rz(theta, 0)
reverse = qc.reverse_ops()
self.assertIn(theta, reverse.parameters)
raise_if_parameter_table_invalid(reverse)
def test_copy_after_dot_data_setter(self):
"""Verify setting circuit.data generates a valid ParameterTable."""
qc = QuantumCircuit(1)
theta = Parameter("theta")
qc.rz(theta, 0)
qc.data = []
self.assertEqual(qc.parameters, set())
raise_if_parameter_table_invalid(qc)
def test_circuit_with_ufunc(self):
"""Test construction of circuit and binding of parameters
after we apply universal functions."""
from math import pi
phi = Parameter(name="phi")
theta = Parameter(name="theta")
qc = QuantumCircuit(2)
qc.p(numpy.abs(-phi), 0)
qc.p(numpy.cos(phi), 0)
qc.p(numpy.sin(phi), 0)
qc.p(numpy.tan(phi), 0)
qc.rz(numpy.arccos(theta), 1)
qc.rz(numpy.arctan(theta), 1)
qc.rz(numpy.arcsin(theta), 1)
qc.assign_parameters({phi: pi, theta: 1}, inplace=True)
qc_ref = QuantumCircuit(2)
qc_ref.p(pi, 0)
qc_ref.p(-1, 0)
qc_ref.p(0, 0)
qc_ref.p(0, 0)
qc_ref.rz(0, 1)
qc_ref.rz(pi / 4, 1)
qc_ref.rz(pi / 2, 1)
self.assertEqual(qc, qc_ref)
def test_compile_with_ufunc(self):
"""Test compiling of circuit with unbound parameters
after we apply universal functions."""
from math import pi
theta = ParameterVector("theta", length=7)
qc = QuantumCircuit(7)
qc.rx(numpy.abs(theta[0]), 0)
qc.rx(numpy.cos(theta[1]), 1)
qc.rx(numpy.sin(theta[2]), 2)
qc.rx(numpy.tan(theta[3]), 3)
qc.rx(numpy.arccos(theta[4]), 4)
qc.rx(numpy.arctan(theta[5]), 5)
qc.rx(numpy.arcsin(theta[6]), 6)
# transpile to different basis
transpiled = transpile(qc, basis_gates=["rz", "sx", "x", "cx"], optimization_level=0)
for x in theta:
self.assertIn(x, transpiled.parameters)
bound = transpiled.bind_parameters({theta: [-1, pi, pi, pi, 1, 1, 1]})
expected = QuantumCircuit(7)
expected.rx(1.0, 0)
expected.rx(-1.0, 1)
expected.rx(0.0, 2)
expected.rx(0.0, 3)
expected.rx(0.0, 4)
expected.rx(pi / 4, 5)
expected.rx(pi / 2, 6)
expected = transpile(expected, basis_gates=["rz", "sx", "x", "cx"], optimization_level=0)
self.assertEqual(expected, bound)
def test_parametervector_resize(self):
"""Test the resize method of the parameter vector."""
vec = ParameterVector("x", 2)
element = vec[1] # store an entry for instancecheck later on
with self.subTest("shorten"):
vec.resize(1)
self.assertEqual(len(vec), 1)
self.assertListEqual([param.name for param in vec], _paramvec_names("x", 1))
with self.subTest("enlargen"):
vec.resize(3)
self.assertEqual(len(vec), 3)
# ensure we still have the same instance not a copy with the same name
# this is crucial for adding parameters to circuits since we cannot use the same
# name if the instance is not the same
self.assertIs(element, vec[1])
self.assertListEqual([param.name for param in vec], _paramvec_names("x", 3))
def test_raise_if_sub_unknown_parameters(self):
"""Verify we raise if asked to sub a parameter not in self."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
with self.assertRaisesRegex(CircuitError, "not present"):
x.subs({y: z})
def test_sub_allow_unknown_parameters(self):
"""Verify we raise if asked to sub a parameter not in self."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
subbed = x.subs({y: z}, allow_unknown_parameters=True)
self.assertEqual(subbed, x)
def _construct_circuit(param, qr):
qc = QuantumCircuit(qr)
qc.ry(param, qr[0])
return qc
def _paramvec_names(prefix, length):
return [f"{prefix}[{i}]" for i in range(length)]
@ddt
class TestParameterExpressions(QiskitTestCase):
"""Test expressions of Parameters."""
supported_operations = [add, sub, mul, truediv]
def test_compare_to_value_when_bound(self):
"""Verify expression can be compared to a fixed value
when fully bound."""
x = Parameter("x")
bound_expr = x.bind({x: 2.3})
self.assertEqual(bound_expr, 2.3)
def test_abs_function_when_bound(self):
"""Verify expression can be used with
abs functions when bound."""
x = Parameter("x")
xb_1 = x.bind({x: 2.0})
xb_2 = x.bind({x: 3.0 + 4.0j})
self.assertEqual(abs(xb_1), 2.0)
self.assertEqual(abs(-xb_1), 2.0)
self.assertEqual(abs(xb_2), 5.0)
def test_abs_function_when_not_bound(self):
"""Verify expression can be used with
abs functions when not bound."""
x = Parameter("x")
y = Parameter("y")
self.assertEqual(abs(x), abs(-x))
self.assertEqual(abs(x) * abs(y), abs(x * y))
self.assertEqual(abs(x) / abs(y), abs(x / y))
def test_cast_to_complex_when_bound(self):
"""Verify that the cast to complex works for bound objects."""
x = Parameter("x")
y = Parameter("y")
bound_expr = (x + y).bind({x: 1.0, y: 1j})
self.assertEqual(complex(bound_expr), 1 + 1j)
def test_raise_if_cast_to_complex_when_not_fully_bound(self):
"""Verify raises if casting to complex and not fully bound."""
x = Parameter("x")
y = Parameter("y")
bound_expr = (x + y).bind({x: 1j})
with self.assertRaisesRegex(TypeError, "unbound parameters"):
complex(bound_expr)
def test_cast_to_float_when_bound(self):
"""Verify expression can be cast to a float when fully bound."""
x = Parameter("x")
bound_expr = x.bind({x: 2.3})
self.assertEqual(float(bound_expr), 2.3)
def test_cast_to_float_when_underlying_expression_bound(self):
"""Verify expression can be cast to a float when it still contains unbound parameters, but
the underlying symbolic expression has a knowable value."""
x = Parameter("x")
expr = x - x + 2.3
self.assertEqual(float(expr), 2.3)
def test_cast_to_float_intermediate_complex_value(self):
"""Verify expression can be cast to a float when it is fully bound, but an intermediate part
of the expression evaluation involved complex types. Sympy is generally more permissive
than symengine here, and sympy's tends to be the expected behaviour for our users."""
x = Parameter("x")
bound_expr = (x + 1.0 + 1.0j).bind({x: -1.0j})
self.assertEqual(float(bound_expr), 1.0)
def test_cast_to_float_of_complex_fails(self):
"""Test that an attempt to produce a float from a complex value fails if there is an
imaginary part, with a sensible error message."""
x = Parameter("x")
bound_expr = (x + 1.0j).bind({x: 1.0})
with self.assertRaisesRegex(TypeError, "could not cast expression to float"):
float(bound_expr)
def test_raise_if_cast_to_float_when_not_fully_bound(self):
"""Verify raises if casting to float and not fully bound."""
x = Parameter("x")
y = Parameter("y")
bound_expr = (x + y).bind({x: 2.3})
with self.assertRaisesRegex(TypeError, "unbound parameters"):
float(bound_expr)
def test_cast_to_int_when_bound(self):
"""Verify expression can be cast to an int when fully bound."""
x = Parameter("x")
bound_expr = x.bind({x: 2.3})
self.assertEqual(int(bound_expr), 2)
def test_cast_to_int_when_bound_truncates_after_evaluation(self):
"""Verify expression can be cast to an int when fully bound, but
truncated only after evaluation."""
x = Parameter("x")
y = Parameter("y")
bound_expr = (x + y).bind({x: 2.3, y: 0.8})
self.assertEqual(int(bound_expr), 3)
def test_cast_to_int_when_underlying_expression_bound(self):
"""Verify expression can be cast to a int when it still contains unbound parameters, but the
underlying symbolic expression has a knowable value."""
x = Parameter("x")
expr = x - x + 2.3
self.assertEqual(int(expr), 2)
def test_raise_if_cast_to_int_when_not_fully_bound(self):
"""Verify raises if casting to int and not fully bound."""
x = Parameter("x")
y = Parameter("y")
bound_expr = (x + y).bind({x: 2.3})
with self.assertRaisesRegex(TypeError, "unbound parameters"):
int(bound_expr)
def test_raise_if_sub_unknown_parameters(self):
"""Verify we raise if asked to sub a parameter not in self."""
x = Parameter("x")
expr = x + 2
y = Parameter("y")
z = Parameter("z")
with self.assertRaisesRegex(CircuitError, "not present"):
expr.subs({y: z})
def test_sub_allow_unknown_parameters(self):
"""Verify we raise if asked to sub a parameter not in self."""
x = Parameter("x")
expr = x + 2
y = Parameter("y")
z = Parameter("z")
subbed = expr.subs({y: z}, allow_unknown_parameters=True)
self.assertEqual(subbed, expr)
def test_raise_if_subbing_in_parameter_name_conflict(self):
"""Verify we raise if substituting in conflicting parameter names."""
x = Parameter("x")
y_first = Parameter("y")
expr = x + y_first
y_second = Parameter("y")
# Replacing an existing name is okay.
expr.subs({y_first: y_second})
with self.assertRaisesRegex(CircuitError, "Name conflict"):
expr.subs({x: y_second})
def test_expressions_of_parameter_with_constant(self):
"""Verify operating on a Parameter with a constant."""
good_constants = [2, 1.3, 0, -1, -1.0, numpy.pi, 1j]
x = Parameter("x")
for op in self.supported_operations:
for const in good_constants:
expr = op(const, x)
bound_expr = expr.bind({x: 2.3})
self.assertEqual(complex(bound_expr), op(const, 2.3))
# Division by zero will raise. Tested elsewhere.
if const == 0 and op == truediv:
continue
# Repeat above, swapping position of Parameter and constant.
expr = op(x, const)
bound_expr = expr.bind({x: 2.3})
res = complex(bound_expr)
expected = op(2.3, const)
self.assertTrue(cmath.isclose(res, expected), f"{res} != {expected}")
def test_complex_parameter_bound_to_real(self):
"""Test a complex parameter expression can be real if bound correctly."""
x, y = Parameter("x"), Parameter("y")
with self.subTest("simple 1j * x"):
qc = QuantumCircuit(1)
qc.rx(1j * x, 0)
bound = qc.bind_parameters({x: 1j})
ref = QuantumCircuit(1)
ref.rx(-1, 0)
self.assertEqual(bound, ref)
with self.subTest("more complex expression"):
qc = QuantumCircuit(1)
qc.rx(0.5j * x - y * y + 2 * y, 0)
bound = qc.bind_parameters({x: -4, y: 1j})
ref = QuantumCircuit(1)
ref.rx(1, 0)
self.assertEqual(bound, ref)
def test_complex_angle_raises_when_not_supported(self):
"""Test parameters are validated when fully bound and errors are raised accordingly."""
x = Parameter("x")
qc = QuantumCircuit(1)
qc.r(x, 1j * x, 0)
with self.subTest("binding x to 0 yields real parameters"):
bound = qc.bind_parameters({x: 0})
ref = QuantumCircuit(1)
ref.r(0, 0, 0)
self.assertEqual(bound, ref)
with self.subTest("binding x to 1 yields complex parameters"):
# RGate does not support complex parameters
with self.assertRaises(CircuitError):
bound = qc.bind_parameters({x: 1})
def test_operating_on_a_parameter_with_a_non_float_will_raise(self):
"""Verify operations between a Parameter and a non-float will raise."""
bad_constants = ["1", numpy.Inf, numpy.NaN, None, {}, []]
x = Parameter("x")
for op in self.supported_operations:
for const in bad_constants:
with self.subTest(op=op, const=const):
with self.assertRaises(TypeError):
_ = op(const, x)
with self.assertRaises(TypeError):
_ = op(x, const)
def test_expressions_division_by_zero(self):
"""Verify dividing a Parameter by 0, or binding 0 as a denominator raises."""
x = Parameter("x")
with self.assertRaises(ZeroDivisionError):
_ = x / 0
with self.assertRaises(ZeroDivisionError):
_ = x / 0.0
expr = 2 / x
with self.assertRaises(ZeroDivisionError):
_ = expr.bind({x: 0})
with self.assertRaises(ZeroDivisionError):
_ = expr.bind({x: 0.0})
def test_expressions_of_parameter_with_parameter(self):
"""Verify operating on two Parameters."""
x = Parameter("x")
y = Parameter("y")
for op in self.supported_operations:
expr = op(x, y)
partially_bound_expr = expr.bind({x: 2.3})
self.assertEqual(partially_bound_expr.parameters, {y})
fully_bound_expr = partially_bound_expr.bind({y: -numpy.pi})
self.assertEqual(fully_bound_expr.parameters, set())
self.assertEqual(float(fully_bound_expr), op(2.3, -numpy.pi))
bound_expr = expr.bind({x: 2.3, y: -numpy.pi})
self.assertEqual(bound_expr.parameters, set())
self.assertEqual(float(bound_expr), op(2.3, -numpy.pi))
def test_expressions_operation_order(self):
"""Verify ParameterExpressions respect order of operations."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
# Parenthesis before multiplication/division
expr = (x + y) * z
bound_expr = expr.bind({x: 1, y: 2, z: 3})
self.assertEqual(float(bound_expr), 9)
expr = x * (y + z)
bound_expr = expr.bind({x: 1, y: 2, z: 3})
self.assertEqual(float(bound_expr), 5)
# Multiplication/division before addition/subtraction
expr = x + y * z
bound_expr = expr.bind({x: 1, y: 2, z: 3})
self.assertEqual(float(bound_expr), 7)
expr = x * y + z
bound_expr = expr.bind({x: 1, y: 2, z: 3})
self.assertEqual(float(bound_expr), 5)
def test_nested_expressions(self):
"""Verify ParameterExpressions can also be the target of operations."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
expr1 = x * y
expr2 = expr1 + z
bound_expr2 = expr2.bind({x: 1, y: 2, z: 3})
self.assertEqual(float(bound_expr2), 5)
def test_negated_expression(self):
"""Verify ParameterExpressions can be negated."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
expr1 = -x + y
expr2 = -expr1 * (-z)
bound_expr2 = expr2.bind({x: 1, y: 2, z: 3})
self.assertEqual(float(bound_expr2), 3)
def test_standard_cu3(self):
"""This tests parameter negation in standard extension gate cu3."""
from qiskit.circuit.library import CU3Gate
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
qc = qiskit.QuantumCircuit(2)
qc.append(CU3Gate(x, y, z), [0, 1])
try:
qc.decompose()
except TypeError:
self.fail("failed to decompose cu3 gate with negated parameter expression")
def test_name_collision(self):
"""Verify Expressions of distinct Parameters of shared name raises."""
x = Parameter("p")
y = Parameter("p")
# Expression of the same Parameter are valid.
_ = x + x
_ = x - x
_ = x * x
_ = x / x
with self.assertRaises(CircuitError):
_ = x + y
with self.assertRaises(CircuitError):
_ = x - y
with self.assertRaises(CircuitError):
_ = x * y
with self.assertRaises(CircuitError):
_ = x / y
@combine(target_type=["gate", "instruction"], order=["bind-decompose", "decompose-bind"])
def test_to_instruction_with_expression(self, target_type, order):
"""Test preservation of expressions via parameterized instructions.
┌───────┐┌──────────┐┌───────────┐
qr1_0: |0>┤ Rx(θ) ├┤ Rz(pi/2) ├┤ Ry(phi*θ) ├
└───────┘└──────────┘└───────────┘
┌───────────┐
qr2_0: |0>───┤ Ry(delta) ├───
┌──┴───────────┴──┐
qr2_1: |0>┤ Circuit0(phi,θ) ├
└─────────────────┘
qr2_2: |0>───────────────────
"""
theta = Parameter("θ")
phi = Parameter("phi")
qr1 = QuantumRegister(1, name="qr1")
qc1 = QuantumCircuit(qr1)
qc1.rx(theta, qr1)
qc1.rz(numpy.pi / 2, qr1)
qc1.ry(theta * phi, qr1)
if target_type == "gate":
gate = qc1.to_gate()
elif target_type == "instruction":
gate = qc1.to_instruction()
self.assertEqual(gate.params, [phi, theta])
delta = Parameter("delta")
qr2 = QuantumRegister(3, name="qr2")
qc2 = QuantumCircuit(qr2)
qc2.ry(delta, qr2[0])
qc2.append(gate, qargs=[qr2[1]])
self.assertEqual(qc2.parameters, {delta, theta, phi})
binds = {delta: 1, theta: 2, phi: 3}
expected_qc = QuantumCircuit(qr2)
expected_qc.rx(2, 1)
expected_qc.rz(numpy.pi / 2, 1)
expected_qc.ry(3 * 2, 1)
expected_qc.r(1, numpy.pi / 2, 0)
if order == "bind-decompose":
decomp_bound_qc = qc2.assign_parameters(binds).decompose()
elif order == "decompose-bind":
decomp_bound_qc = qc2.decompose().assign_parameters(binds)
self.assertEqual(decomp_bound_qc.parameters, set())
self.assertEqual(decomp_bound_qc, expected_qc)
@combine(target_type=["gate", "instruction"], order=["bind-decompose", "decompose-bind"])
def test_to_instruction_expression_parameter_map(self, target_type, order):
"""Test preservation of expressions via instruction parameter_map."""
theta = Parameter("θ")
phi = Parameter("phi")
qr1 = QuantumRegister(1, name="qr1")
qc1 = QuantumCircuit(qr1)
qc1.rx(theta, qr1)
qc1.rz(numpy.pi / 2, qr1)
qc1.ry(theta * phi, qr1)
theta_p = Parameter("theta")
phi_p = Parameter("phi")
if target_type == "gate":
gate = qc1.to_gate(parameter_map={theta: theta_p, phi: phi_p})
elif target_type == "instruction":
gate = qc1.to_instruction(parameter_map={theta: theta_p, phi: phi_p})
self.assertListEqual(gate.params, [theta_p, phi_p])
delta = Parameter("delta")
qr2 = QuantumRegister(3, name="qr2")
qc2 = QuantumCircuit(qr2)
qc2.ry(delta, qr2[0])
qc2.append(gate, qargs=[qr2[1]])
self.assertListEqual(list(qc2.parameters), [delta, phi_p, theta_p])
binds = {delta: 1, theta_p: 2, phi_p: 3}
expected_qc = QuantumCircuit(qr2)
expected_qc.rx(2, 1)
expected_qc.rz(numpy.pi / 2, 1)
expected_qc.ry(3 * 2, 1)
expected_qc.r(1, numpy.pi / 2, 0)
if order == "bind-decompose":
decomp_bound_qc = qc2.assign_parameters(binds).decompose()
elif order == "decompose-bind":
decomp_bound_qc = qc2.decompose().assign_parameters(binds)
self.assertEqual(decomp_bound_qc.parameters, set())
self.assertEqual(decomp_bound_qc, expected_qc)
def test_binding_across_broadcast_instruction(self):
"""Bind a parameter which was included via a broadcast instruction."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/3008
theta = Parameter("θ")
n = 5
qc = QuantumCircuit(n, 1)
qc.h(0)
for i in range(n - 1):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(theta, range(n))
qc.barrier()
for i in reversed(range(n - 1)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
theta_range = numpy.linspace(0, 2 * numpy.pi, 128)
circuits = [qc.assign_parameters({theta: theta_val}) for theta_val in theta_range]
self.assertEqual(len(circuits), len(theta_range))
for theta_val, bound_circ in zip(theta_range, circuits):
rz_gates = [
inst.operation for inst in bound_circ.data if isinstance(inst.operation, RZGate)
]
self.assertEqual(len(rz_gates), n)
self.assertTrue(all(float(gate.params[0]) == theta_val for gate in rz_gates))
def test_substituting_parameter_with_simple_expression(self):
"""Substitute a simple parameter expression for a parameter."""
x = Parameter("x")
y = Parameter("y")
sub_ = y / 2
updated_expr = x.subs({x: sub_})
expected = y / 2
self.assertEqual(updated_expr, expected)
def test_substituting_parameter_with_compound_expression(self):
"""Substitute a simple parameter expression for a parameter."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
sub_ = y * z
updated_expr = x.subs({x: sub_})
expected = y * z
self.assertEqual(updated_expr, expected)
def test_substituting_simple_with_simple_expression(self):
"""Substitute a simple parameter expression in a parameter expression."""
x = Parameter("x")
expr = x * x
y = Parameter("y")
sub_ = y / 2
updated_expr = expr.subs({x: sub_})
expected = y * y / 4
self.assertEqual(updated_expr, expected)
def test_substituting_compound_expression(self):
"""Substitute a compound parameter expression in a parameter expression."""
x = Parameter("x")
expr = x * x
y = Parameter("y")
z = Parameter("z")
sub_ = y + z
updated_expr = expr.subs({x: sub_})
expected = (y + z) * (y + z)
self.assertEqual(updated_expr, expected)
def test_conjugate(self):
"""Test calling conjugate on a ParameterExpression."""
x = Parameter("x")
self.assertEqual((x.conjugate() + 1j), (x - 1j).conjugate())
@data(
circlib.RGate,
circlib.RXGate,
circlib.RYGate,
circlib.RZGate,
circlib.RXXGate,
circlib.RYYGate,
circlib.RZXGate,
circlib.RZZGate,
circlib.CRXGate,
circlib.CRYGate,
circlib.CRZGate,
circlib.XXPlusYYGate,
)
def test_bound_gate_to_matrix(self, gate_class):
"""Test to_matrix works if previously free parameters are bound.
The conversion might fail, if trigonometric functions such as cos are called on the
parameters and the parameters are still of type ParameterExpression.
"""
num_parameters = 2 if gate_class == circlib.RGate else 1
params = list(range(1, 1 + num_parameters))
free_params = ParameterVector("th", num_parameters)
gate = gate_class(*params)
num_qubits = gate.num_qubits
circuit = QuantumCircuit(num_qubits)
circuit.append(gate_class(*free_params), list(range(num_qubits)))
bound_circuit = circuit.assign_parameters({free_params: params})
numpy.testing.assert_array_almost_equal(Operator(bound_circuit).data, gate.to_matrix())
def test_parameter_expression_grad(self):
"""Verify correctness of ParameterExpression gradients."""
x = Parameter("x")
y = Parameter("y")
z = Parameter("z")
with self.subTest(msg="first order gradient"):
expr = (x + y) * z
self.assertEqual(expr.gradient(x), z)
self.assertEqual(expr.gradient(z), (x + y))
with self.subTest(msg="second order gradient"):
expr = x * x
self.assertEqual(expr.gradient(x), 2 * x)
self.assertEqual(expr.gradient(x).gradient(x), 2)
def test_bound_expression_is_real(self):
"""Test is_real on bound parameters."""
x = Parameter("x")
self.assertEqual(x.is_real(), None)
self.assertEqual((1j * x).is_real(), None)
expr = 1j * x
bound = expr.bind({x: 2})
self.assertEqual(bound.is_real(), False)
bound = x.bind({x: 0 + 0j})
self.assertEqual(bound.is_real(), True)
bound = x.bind({x: 0 + 1j})
self.assertEqual(bound.is_real(), False)
bound = x.bind({x: 1 + 0j})
self.assertEqual(bound.is_real(), True)
bound = x.bind({x: 1 + 1j})
self.assertEqual(bound.is_real(), False)
class TestParameterEquality(QiskitTestCase):
"""Test equality of Parameters and ParameterExpressions."""
def test_parameter_equal_self(self):
"""Verify a parameter is equal to it self."""
theta = Parameter("theta")
self.assertEqual(theta, theta)
def test_parameter_not_equal_param_of_same_name(self):
"""Verify a parameter is not equal to a Parameter of the same name."""
theta1 = Parameter("theta")
theta2 = Parameter("theta")
self.assertNotEqual(theta1, theta2)
def test_parameter_expression_equal_to_self(self):
"""Verify an expression is equal to itself."""
theta = Parameter("theta")
expr = 2 * theta
self.assertEqual(expr, expr)
def test_parameter_expression_equal_to_identical(self):
"""Verify an expression is equal an identical expression."""
theta = Parameter("theta")
expr1 = 2 * theta
expr2 = 2 * theta
self.assertEqual(expr1, expr2)
def test_parameter_expression_equal_floats_to_ints(self):
"""Verify an expression with float and int is identical."""
theta = Parameter("theta")
expr1 = 2.0 * theta
expr2 = 2 * theta
self.assertEqual(expr1, expr2)
def test_parameter_expression_not_equal_if_params_differ(self):
"""Verify expressions not equal if parameters are different."""
theta1 = Parameter("theta")
theta2 = Parameter("theta")
expr1 = 2 * theta1
expr2 = 2 * theta2
self.assertNotEqual(expr1, expr2)
def test_parameter_equal_to_identical_expression(self):
"""Verify parameters and ParameterExpressions can be equal if identical."""
theta = Parameter("theta")
phi = Parameter("phi")
expr = (theta + phi).bind({phi: 0})
self.assertEqual(expr, theta)
self.assertEqual(theta, expr)
def test_parameter_symbol_equal_after_ufunc(self):
"""Verfiy ParameterExpression phi
and ParameterExpression cos(phi) have the same symbol map"""
phi = Parameter("phi")
cos_phi = numpy.cos(phi)
self.assertEqual(phi._parameter_symbols, cos_phi._parameter_symbols)
class TestParameterReferences(QiskitTestCase):
"""Test the ParameterReferences class."""
def test_equal_inst_diff_instance(self):
"""Different value equal instructions are treated as distinct."""
theta = Parameter("theta")
gate1 = RZGate(theta)
gate2 = RZGate(theta)
self.assertIsNot(gate1, gate2)
self.assertEqual(gate1, gate2)
refs = ParameterReferences(((gate1, 0), (gate2, 0)))
# test __contains__
self.assertIn((gate1, 0), refs)
self.assertIn((gate2, 0), refs)
gate_ids = {id(gate1), id(gate2)}
self.assertEqual(gate_ids, {id(gate) for gate, _ in refs})
self.assertTrue(all(idx == 0 for _, idx in refs))
def test_pickle_unpickle(self):
"""Membership testing after pickle/unpickle."""
theta = Parameter("theta")
gate1 = RZGate(theta)
gate2 = RZGate(theta)
self.assertIsNot(gate1, gate2)
self.assertEqual(gate1, gate2)
refs = ParameterReferences(((gate1, 0), (gate2, 0)))
to_pickle = (gate1, refs)
pickled = pickle.dumps(to_pickle)
(gate1_new, refs_new) = pickle.loads(pickled)
self.assertEqual(len(refs_new), len(refs))
self.assertNotIn((gate1, 0), refs_new)
self.assertIn((gate1_new, 0), refs_new)
def test_equal_inst_same_instance(self):
"""Referentially equal instructions are treated as same."""
theta = Parameter("theta")
gate = RZGate(theta)
refs = ParameterReferences(((gate, 0), (gate, 0)))
self.assertIn((gate, 0), refs)
self.assertEqual(len(refs), 1)
self.assertIs(next(iter(refs))[0], gate)
self.assertEqual(next(iter(refs))[1], 0)
def test_extend_refs(self):
"""Extending references handles duplicates."""
theta = Parameter("theta")
ref0 = (RZGate(theta), 0)
ref1 = (RZGate(theta), 0)
ref2 = (RZGate(theta), 0)
refs = ParameterReferences((ref0,))
refs |= ParameterReferences((ref0, ref1, ref2, ref1, ref0))
self.assertEqual(refs, ParameterReferences((ref0, ref1, ref2)))
def test_copy_param_refs(self):
"""Copy of parameter references is a shallow copy."""
theta = Parameter("theta")
ref0 = (RZGate(theta), 0)
ref1 = (RZGate(theta), 0)
ref2 = (RZGate(theta), 0)
ref3 = (RZGate(theta), 0)
refs = ParameterReferences((ref0, ref1))
refs_copy = refs.copy()
# Check same gate instances in copy
gate_ids = {id(ref0[0]), id(ref1[0])}
self.assertEqual({id(gate) for gate, _ in refs_copy}, gate_ids)
# add new ref to original and check copy not modified
refs.add(ref2)
self.assertNotIn(ref2, refs_copy)
self.assertEqual(refs_copy, ParameterReferences((ref0, ref1)))
# add new ref to copy and check original not modified
refs_copy.add(ref3)
self.assertNotIn(ref3, refs)
self.assertEqual(refs, ParameterReferences((ref0, ref1, ref2)))
class TestParameterTable(QiskitTestCase):
"""Test the ParameterTable class."""
def test_init_param_table(self):
"""Parameter table init from mapping."""
p1 = Parameter("theta")
p2 = Parameter("theta")
ref0 = (RZGate(p1), 0)
ref1 = (RZGate(p1), 0)
ref2 = (RZGate(p2), 0)
mapping = {p1: ParameterReferences((ref0, ref1)), p2: ParameterReferences((ref2,))}
table = ParameterTable(mapping)
# make sure editing mapping doesn't change `table`
del mapping[p1]
self.assertEqual(table[p1], ParameterReferences((ref0, ref1)))
self.assertEqual(table[p2], ParameterReferences((ref2,)))
def test_set_references(self):
"""References replacement by parameter key."""
p1 = Parameter("theta")
ref0 = (RZGate(p1), 0)
ref1 = (RZGate(p1), 0)
table = ParameterTable()
table[p1] = ParameterReferences((ref0, ref1))
self.assertEqual(table[p1], ParameterReferences((ref0, ref1)))
table[p1] = ParameterReferences((ref1,))
self.assertEqual(table[p1], ParameterReferences((ref1,)))
def test_set_references_from_iterable(self):
"""Parameter table init from iterable."""
p1 = Parameter("theta")
ref0 = (RZGate(p1), 0)
ref1 = (RZGate(p1), 0)
ref2 = (RZGate(p1), 0)
table = ParameterTable({p1: ParameterReferences((ref0, ref1))})
table[p1] = (ref2, ref1, ref0)
self.assertEqual(table[p1], ParameterReferences((ref2, ref1, ref0)))
class TestParameterView(QiskitTestCase):
"""Test the ParameterView object."""
def setUp(self):
super().setUp()
x, y, z = Parameter("x"), Parameter("y"), Parameter("z")
self.params = [x, y, z]
self.view1 = ParameterView([x, y])
self.view2 = ParameterView([y, z])
self.view3 = ParameterView([x])
def test_and(self):
"""Test __and__."""
self.assertEqual(self.view1 & self.view2, {self.params[1]})
def test_or(self):
"""Test __or__."""
self.assertEqual(self.view1 | self.view2, set(self.params))
def test_xor(self):
"""Test __xor__."""
self.assertEqual(self.view1 ^ self.view2, {self.params[0], self.params[2]})
def test_len(self):
"""Test __len__."""
self.assertEqual(len(self.view1), 2)
def test_le(self):
"""Test __le__."""
self.assertTrue(self.view1 <= self.view1)
self.assertFalse(self.view1 <= self.view3)
def test_lt(self):
"""Test __lt__."""
self.assertTrue(self.view3 < self.view1)
def test_ge(self):
"""Test __ge__."""
self.assertTrue(self.view1 >= self.view1)
self.assertFalse(self.view3 >= self.view1)
def test_gt(self):
"""Test __lt__."""
self.assertTrue(self.view1 > self.view3)
def test_eq(self):
"""Test __eq__."""
self.assertTrue(self.view1 == self.view1)
self.assertFalse(self.view3 == self.view1)
def test_ne(self):
"""Test __eq__."""
self.assertTrue(self.view1 != self.view2)
self.assertFalse(self.view3 != self.view3)
if __name__ == "__main__":
unittest.main()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
|
https://github.com/a-giovagnoli/QAOA-Qiskit
|
a-giovagnoli
|
#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/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
| |
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
import numpy as np
from qiskit import QuantumCircuit
from matplotlib import pyplot
circ = QuantumCircuit(3)
# Create 3-qubit GHZ state: (1/sqrt(2))*(|000> + |111>)
circ.h(0)
circ.cx(0,1)
circ.cx(1,2)
### Visualize Circuit
circ.draw('mpl')
pyplot.show()
### Simulate Circuit
from qiskit.quantum_info import Statevector
state = Statevector.from_int(0,2**3)
state = state.evolve(circ)
lat = state.draw('latex') # This is not working in Pycharm - I think this needs to be a jupyter notebook
qsp = state.draw('qsphere')
hin = state.draw('hinton')
pyplot.show()
### Unitary Representation of Circuit
from qiskit.quantum_info import Operator
U = Operator(circ)
print(U.data) # show results
### OpenQASM Backend Simulation
meas = QuantumCircuit(3,3)
meas.barrier(range(3))
meas.measure(range(3), range(3))
qc = meas.compose(circ, range(3), front=True)
qc.draw('mpl')
pyplot.show()
from qiskit import transpile
from qiskit.providers.aer import QasmSimulator
backend = QasmSimulator()
qc_compiled = transpile(qc, backend)
job_sim = backend.run(qc_compiled, shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(qc_compiled)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
pyplot.show()
|
https://github.com/jwalaQ/my-qiskit-textbook-solutions
|
jwalaQ
|
from qiskit import *
from math import pi
import numpy as np
from qiskit.visualization import plot_bloch_multivector,plot_histogram
from qiskit_textbook.tools import array_to_latex
backend_s = Aer.get_backend('statevector_simulator')
backend_u = Aer.get_backend('unitary_simulator')
qc = QuantumCircuit(2)
qc.x(0) # NOT gate to convert default 0 state to 1
qc.draw('mpl')
result_statevector = execute(qc,backend_s).result().get_statevector()
array_to_latex(result_statevector,pretext = "\\text{Result = }")
plot_bloch_multivector(result_statevector)
qc = QuantumCircuit(2)
qc.h(0)
qc.draw('mpl')
result_statevector = execute(qc,backend_s).result().get_statevector()
array_to_latex(result_statevector,pretext = "\\text{Result = }")
plot_bloch_multivector(result_statevector)
qc = QuantumCircuit(2)
qc.x(0)
qc.h(1)
qc.draw('mpl')
result_statevector = execute(qc,backend_s).result().get_statevector()
array_to_latex(result_statevector,pretext = "\\text{Result = }")
plot_bloch_multivector(result_statevector)
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.h(1)
qc.draw('mpl')
result_statevector = execute(qc,backend_s).result().get_statevector()
array_to_latex(result_statevector,pretext = "\\text{Result = }")
plot_bloch_multivector(result_statevector)
qc = QuantumCircuit(1)
qc.x(0)
qc.z(0)
qc.h(0)
qc.draw('mpl')
result_unitary = execute(qc,backend_u).result().get_unitary()
array_to_latex(result_unitary,pretext = "\\text{U = XZH = }")
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.draw('mpl')
array_to_latex(execute(qc,backend_u).result().get_unitary())
qc = QuantumCircuit(2)
qc.h(0)
qc.draw('mpl')
array_to_latex(execute(qc,backend_u).result().get_unitary())
qc = QuantumCircuit(2)
qc.sdg(1)
qc.z(0)
qc.draw('mpl')
array_to_latex(execute(qc,backend_u).result().get_unitary())
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.cx(0,1)
qc.draw('mpl')
entangled = execute(qc,backend_s).result()
entangled_statevector = entangled.get_statevector()
entangled_counts = entangled.get_counts()
array_to_latex(entangled_statevector, pretext = "\\text{Statevector = }")
plot_histogram(entangled_counts)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
p = 0.01
P = 3 * p**2 * (1-p) + p**3
print('Probability of a single reply being garbled:',p)
print('Probability of a the majority of three replies being garbled:',P)
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error
def get_noise(p_meas,p_gate):
error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])
error_gate1 = depolarizing_error(p_gate, 1)
error_gate2 = error_gate1.tensor(error_gate1)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error_meas, "measure") # measurement error is applied to measurements
noise_model.add_all_qubit_quantum_error(error_gate1, ["x"]) # single qubit gate error is applied to x gates
noise_model.add_all_qubit_quantum_error(error_gate2, ["cx"]) # two qubit gate error is applied to cx gates
return noise_model
noise_model = get_noise(0.01,0.01)
qc0 = QuantumCircuit(3,3,name='0') # initialize circuit with three qubits in the 0 state
qc0.measure(qc0.qregs[0],qc0.cregs[0]) # measure the qubits
# run the circuit with th noise model and extract the counts
counts = execute( qc0, Aer.get_backend('qasm_simulator'),noise_model=noise_model,shots=10000).result().get_counts()
print(counts)
qc1 = QuantumCircuit(3,3,name='0') # initialize circuit with three qubits in the 0 state
qc1.x(qc1.qregs[0]) # flip each 0 to 1
qc1.measure(qc1.qregs[0],qc1.cregs[0]) # measure the qubits
# run the circuit with th noise model and extract the counts
counts = execute( qc1, Aer.get_backend('qasm_simulator'),noise_model=noise_model,shots=10000).result().get_counts()
print(counts)
noise_model = get_noise(0.5,0.0)
counts = execute( qc1, Aer.get_backend('qasm_simulator'),noise_model=noise_model,shots=10000).result().get_counts()
print(counts)
from qiskit import *
cq = QuantumRegister(2,'code_qubit')
lq = QuantumRegister(1,'ancilla_qubit')
sb = ClassicalRegister(1,'syndrome_bit')
qc = QuantumCircuit(cq,lq,sb)
qc.cx(cq[0],lq[0])
qc.cx(cq[1],lq[0])
qc.measure(lq,sb)
print(qc)
qc_init = QuantumCircuit(cq)
print(qc_init+qc)
counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator'),shots=10000).result().get_counts()
print('\nResults:',counts)
qc_init = QuantumCircuit(cq)
qc_init.x(cq)
print(qc_init+qc)
counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator'),shots=10000).result().get_counts()
print('\nResults:',counts)
qc_init = QuantumCircuit(cq)
qc_init.h(cq[0])
qc_init.cx(cq[0],cq[1])
print(qc_init+qc)
counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator'),shots=10000).result().get_counts()
print('\nResults:',counts)
qc_init = QuantumCircuit(cq)
qc_init.h(cq[0])
qc_init.cx(cq[0],cq[1])
qc_init.x(cq[0])
print(qc_init+qc)
counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator'),shots=10000).result().get_counts()
print('\nResults:',counts)
from qiskit.ignis.verification.topological_codes import RepetitionCode
from qiskit.ignis.verification.topological_codes import lookuptable_decoding
n = 3
T = 1
code = RepetitionCode(n,T)
code.qubit_registers
code.code_qubit
for log in ['0','1']:
print('\n========= logical',log,'=========\n')
print( code.circuit[log] )
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator') )
for log in ['0','1']:
print('\nLogical',log,':',job.result().get_counts(log))
code = RepetitionCode(n,4)
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator') )
for log in ['0','1']:
print('\nLogical',log,':',job.result().get_counts(log))
code = RepetitionCode(5,4)
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator') )
for log in ['0','1']:
print('\nLogical',log,':',job.result().get_counts(log))
code = RepetitionCode(n,4)
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator') )
for log in ['0','1']:
print('\nLogical',log,':',job.result().get_counts(log))
code = RepetitionCode(3,1)
noise_model = get_noise(0.2,0.2)
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator'), noise_model=noise_model )
raw_results = {}
for log in ['0','1']:
raw_results[log] = job.result().get_counts(log)
print('\n========= logical',log,'=========\n')
print(raw_results[log])
job = execute( circuits, Aer.get_backend('qasm_simulator'), noise_model=noise_model, shots=10000 )
table_results = {}
for log in ['0','1']:
table_results[log] = job.result().get_counts(log)
P = lookuptable_decoding(raw_results,table_results)
print('P =',P)
code = RepetitionCode(3,1)
noise_model = get_noise(0.1,0.1)
circuits = code.get_circuit_list()
job = execute( circuits, Aer.get_backend('qasm_simulator'), noise_model=noise_model )
raw_results = {}
for log in ['0','1']:
raw_results[log] = job.result().get_counts(log)
job = execute( circuits, Aer.get_backend('qasm_simulator'), noise_model=noise_model, shots=10000 )
table_results = {}
for log in ['0','1']:
table_results[log] = job.result().get_counts(log)
P = lookuptable_decoding(raw_results,table_results)
print('P =',P)
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.translators import from_docplex_mp
# Make a Docplex model
from docplex.mp.model import Model
mdl = Model("docplex model")
x = mdl.binary_var("x")
y = mdl.integer_var(lb=-1, ub=5, name="y")
mdl.minimize(x + 2 * y)
mdl.add_constraint(x - y == 3)
mdl.add_constraint((x + y) * (x - y) <= 1)
print(mdl.export_as_lp_string())
# load from a Docplex model
mod = from_docplex_mp(mdl)
print(type(mod))
print()
print(mod.prettyprint())
# make an empty problem
mod = QuadraticProgram("my problem")
print(mod.prettyprint())
# Add variables
mod.binary_var(name="x")
mod.integer_var(name="y", lowerbound=-1, upperbound=5)
mod.continuous_var(name="z", lowerbound=-1, upperbound=5)
print(mod.prettyprint())
# Add objective function using dictionaries
mod.minimize(constant=3, linear={"x": 1}, quadratic={("x", "y"): 2, ("z", "z"): -1})
print(mod.prettyprint())
# Add objective function using lists/arrays
mod.minimize(constant=3, linear=[1, 0, 0], quadratic=[[0, 1, 0], [1, 0, 0], [0, 0, -1]])
print(mod.prettyprint())
print("constant:\t\t\t", mod.objective.constant)
print("linear dict:\t\t\t", mod.objective.linear.to_dict())
print("linear array:\t\t\t", mod.objective.linear.to_array())
print("linear array as sparse matrix:\n", mod.objective.linear.coefficients, "\n")
print("quadratic dict w/ index:\t", mod.objective.quadratic.to_dict())
print("quadratic dict w/ name:\t\t", mod.objective.quadratic.to_dict(use_name=True))
print(
"symmetric quadratic dict w/ name:\t",
mod.objective.quadratic.to_dict(use_name=True, symmetric=True),
)
print("quadratic matrix:\n", mod.objective.quadratic.to_array(), "\n")
print("symmetric quadratic matrix:\n", mod.objective.quadratic.to_array(symmetric=True), "\n")
print("quadratic matrix as sparse matrix:\n", mod.objective.quadratic.coefficients)
# Add linear constraints
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="==", rhs=3, name="lin_eq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="<=", rhs=3, name="lin_leq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense=">=", rhs=3, name="lin_geq")
print(mod.prettyprint())
# Add quadratic constraints
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="==",
rhs=1,
name="quad_eq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="<=",
rhs=1,
name="quad_leq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense=">=",
rhs=1,
name="quad_geq",
)
print(mod.prettyprint())
lin_geq = mod.get_linear_constraint("lin_geq")
print("lin_geq:", lin_geq.linear.to_dict(use_name=True), lin_geq.sense, lin_geq.rhs)
quad_geq = mod.get_quadratic_constraint("quad_geq")
print(
"quad_geq:",
quad_geq.linear.to_dict(use_name=True),
quad_geq.quadratic.to_dict(use_name=True),
quad_geq.sense,
lin_geq.rhs,
)
# Remove constraints
mod.remove_linear_constraint("lin_eq")
mod.remove_quadratic_constraint("quad_leq")
print(mod.prettyprint())
sub = mod.substitute_variables(constants={"x": 0}, variables={"y": ("z", -1)})
print(sub.prettyprint())
sub = mod.substitute_variables(constants={"x": -1})
print(sub.status)
from qiskit_optimization import QiskitOptimizationError
try:
sub = mod.substitute_variables(constants={"x": -1}, variables={"y": ("x", 1)})
except QiskitOptimizationError as e:
print("Error: {}".format(e))
mod = QuadraticProgram()
mod.binary_var(name="e")
mod.binary_var(name="f")
mod.continuous_var(name="g")
mod.minimize(linear=[1, 2, 3])
print(mod.export_as_lp_string())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""NumTensorFactors pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import NumTensorFactors
from qiskit.test import QiskitTestCase
class TestNumTensorsFactorPass(QiskitTestCase):
"""Tests for NumTensorFactors analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 number of tensor factors."""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and 1 tensor factor."""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 1)
def test_depth_one(self):
"""A dag with operations in parallel (2 tensor factors)"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
dag = circuit_to_dag(circuit)
pass_ = NumTensorFactors()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["num_tensor_factors"], 2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# =============================================================================
"""Test Sampler Gradients"""
import unittest
from typing import List
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit
from qiskit_algorithms.gradients import (
FiniteDiffSamplerGradient,
LinCombSamplerGradient,
ParamShiftSamplerGradient,
SPSASamplerGradient,
)
from qiskit.circuit import Parameter
from qiskit.circuit.library import EfficientSU2, RealAmplitudes
from qiskit.circuit.library.standard_gates import RXXGate
from qiskit.primitives import Sampler
from qiskit.result import QuasiDistribution
from qiskit.test import QiskitTestCase
from .logging_primitives import LoggingSampler
gradient_factories = [
lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="central"),
lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="forward"),
lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="backward"),
ParamShiftSamplerGradient,
LinCombSamplerGradient,
]
@ddt
class TestSamplerGradient(QiskitTestCase):
"""Test Sampler Gradient"""
@data(*gradient_factories)
def test_single_circuit(self, grad):
"""Test the sampler gradient for a single circuit"""
sampler = Sampler()
a = Parameter("a")
qc = QuantumCircuit(1)
qc.h(0)
qc.p(a, 0)
qc.h(0)
qc.measure_all()
gradient = grad(sampler)
param_list = [[np.pi / 4], [0], [np.pi / 2]]
expected = [
[{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}],
[{0: 0, 1: 0}],
[{0: -0.499999, 1: 0.499999}],
]
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [param]).result().gradients[0]
array1 = _quasi2array(gradients, num_qubits=1)
array2 = _quasi2array(expected[i], num_qubits=1)
np.testing.assert_allclose(array1, array2, atol=1e-3)
@data(*gradient_factories)
def test_gradient_p(self, grad):
"""Test the sampler gradient for p"""
sampler = Sampler()
a = Parameter("a")
qc = QuantumCircuit(1)
qc.h(0)
qc.p(a, 0)
qc.h(0)
qc.measure_all()
gradient = grad(sampler)
param_list = [[np.pi / 4], [0], [np.pi / 2]]
expected = [
[{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}],
[{0: 0, 1: 0}],
[{0: -0.499999, 1: 0.499999}],
]
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [param]).result().gradients[0]
array1 = _quasi2array(gradients, num_qubits=1)
array2 = _quasi2array(expected[i], num_qubits=1)
np.testing.assert_allclose(array1, array2, atol=1e-3)
@data(*gradient_factories)
def test_gradient_u(self, grad):
"""Test the sampler gradient for u"""
sampler = Sampler()
a = Parameter("a")
b = Parameter("b")
c = Parameter("c")
qc = QuantumCircuit(1)
qc.h(0)
qc.u(a, b, c, 0)
qc.h(0)
qc.measure_all()
gradient = grad(sampler)
param_list = [[np.pi / 4, 0, 0], [np.pi / 4, np.pi / 4, np.pi / 4]]
expected = [
[{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}, {0: 0, 1: 0}, {0: 0, 1: 0}],
[{0: -0.176777, 1: 0.176777}, {0: -0.426777, 1: 0.426777}, {0: -0.426777, 1: 0.426777}],
]
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [param]).result().gradients[0]
array1 = _quasi2array(gradients, num_qubits=1)
array2 = _quasi2array(expected[i], num_qubits=1)
np.testing.assert_allclose(array1, array2, atol=1e-3)
@data(*gradient_factories)
def test_gradient_efficient_su2(self, grad):
"""Test the sampler gradient for EfficientSU2"""
sampler = Sampler()
qc = EfficientSU2(2, reps=1)
qc.measure_all()
gradient = grad(sampler)
param_list = [
[np.pi / 4 for param in qc.parameters],
[np.pi / 2 for param in qc.parameters],
]
expected = [
[
{
0: -0.11963834764831836,
1: -0.05713834764831845,
2: -0.21875000000000003,
3: 0.39552669529663675,
},
{
0: -0.32230339059327373,
1: -0.031250000000000014,
2: 0.2339150429449554,
3: 0.11963834764831843,
},
{
0: 0.012944173824159189,
1: -0.01294417382415923,
2: 0.07544417382415919,
3: -0.07544417382415919,
},
{
0: 0.2080266952966367,
1: -0.03125000000000002,
2: -0.11963834764831842,
3: -0.057138347648318405,
},
{
0: -0.11963834764831838,
1: 0.11963834764831838,
2: -0.21875000000000003,
3: 0.21875,
},
{
0: -0.2781092167691146,
1: -0.0754441738241592,
2: 0.27810921676911443,
3: 0.07544417382415924,
},
{0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0},
{0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0},
],
[
{
0: -4.163336342344337e-17,
1: 2.7755575615628914e-17,
2: -4.163336342344337e-17,
3: 0.0,
},
{0: 0.0, 1: -1.3877787807814457e-17, 2: 4.163336342344337e-17, 3: 0.0},
{
0: -0.24999999999999994,
1: 0.24999999999999994,
2: 0.24999999999999994,
3: -0.24999999999999994,
},
{
0: 0.24999999999999994,
1: 0.24999999999999994,
2: -0.24999999999999994,
3: -0.24999999999999994,
},
{
0: -4.163336342344337e-17,
1: 4.163336342344337e-17,
2: -4.163336342344337e-17,
3: 5.551115123125783e-17,
},
{
0: -0.24999999999999994,
1: 0.24999999999999994,
2: 0.24999999999999994,
3: -0.24999999999999994,
},
{0: 0.0, 1: 2.7755575615628914e-17, 2: 0.0, 3: 2.7755575615628914e-17},
{0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0},
],
]
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [param]).result().gradients[0]
array1 = _quasi2array(gradients, num_qubits=2)
array2 = _quasi2array(expected[i], num_qubits=2)
np.testing.assert_allclose(array1, array2, atol=1e-3)
@data(*gradient_factories)
def test_gradient_2qubit_gate(self, grad):
"""Test the sampler gradient for 2 qubit gates"""
sampler = Sampler()
for gate in [RXXGate]:
param_list = [[np.pi / 4], [np.pi / 2]]
correct_results = [
[{0: -0.5 / np.sqrt(2), 1: 0, 2: 0, 3: 0.5 / np.sqrt(2)}],
[{0: -0.5, 1: 0, 2: 0, 3: 0.5}],
]
for i, param in enumerate(param_list):
a = Parameter("a")
qc = QuantumCircuit(2)
qc.append(gate(a), [qc.qubits[0], qc.qubits[1]], [])
qc.measure_all()
gradient = grad(sampler)
gradients = gradient.run([qc], [param]).result().gradients[0]
array1 = _quasi2array(gradients, num_qubits=2)
array2 = _quasi2array(correct_results[i], num_qubits=2)
np.testing.assert_allclose(array1, array2, atol=1e-3)
@data(*gradient_factories)
def test_gradient_parameter_coefficient(self, grad):
"""Test the sampler gradient for parameter variables with coefficients"""
sampler = Sampler()
qc = RealAmplitudes(num_qubits=2, reps=1)
qc.rz(qc.parameters[0].exp() + 2 * qc.parameters[1], 0)
qc.rx(3.0 * qc.parameters[0] + qc.parameters[1].sin(), 1)
qc.u(qc.parameters[0], qc.parameters[1], qc.parameters[3], 1)
qc.p(2 * qc.parameters[0] + 1, 0)
qc.rxx(qc.parameters[0] + 2, 0, 1)
qc.measure_all()
gradient = grad(sampler)
param_list = [[np.pi / 4 for _ in qc.parameters], [np.pi / 2 for _ in qc.parameters]]
correct_results = [
[
{
0: 0.30014831912265927,
1: -0.6634809704357856,
2: 0.343589357193753,
3: 0.019743294119373426,
},
{
0: 0.16470607453981906,
1: -0.40996282450610577,
2: 0.08791803062881773,
3: 0.15733871933746948,
},
{
0: 0.27036068339663866,
1: -0.273790986018701,
2: 0.12752010079553433,
3: -0.12408979817347202,
},
{
0: -0.2098616294167757,
1: -0.2515823946449894,
2: 0.21929102305386305,
3: 0.24215300100790207,
},
],
[
{
0: -1.844810060881004,
1: 0.04620532700836027,
2: 1.6367366426074323,
3: 0.16186809126521057,
},
{
0: 0.07296073407769421,
1: -0.021774869186331716,
2: 0.02177486918633173,
3: -0.07296073407769456,
},
{
0: -0.07794369186049102,
1: -0.07794369186049122,
2: 0.07794369186049117,
3: 0.07794369186049112,
},
{
0: 0.0,
1: 0.0,
2: 0.0,
3: 0.0,
},
],
]
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [param]).result().gradients[0]
array1 = _quasi2array(gradients, num_qubits=2)
array2 = _quasi2array(correct_results[i], num_qubits=2)
np.testing.assert_allclose(array1, array2, atol=1e-3)
@data(*gradient_factories)
def test_gradient_parameters(self, grad):
"""Test the sampler gradient for parameters"""
sampler = Sampler()
a = Parameter("a")
b = Parameter("b")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc.rz(b, 0)
qc.measure_all()
gradient = grad(sampler)
param_list = [[np.pi / 4, np.pi / 2]]
expected = [
[{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}],
]
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [param], parameters=[[a]]).result().gradients[0]
array1 = _quasi2array(gradients, num_qubits=1)
array2 = _quasi2array(expected[i], num_qubits=1)
np.testing.assert_allclose(array1, array2, atol=1e-3)
# parameter order
with self.subTest(msg="The order of gradients"):
c = Parameter("c")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc.rz(b, 0)
qc.rx(c, 0)
qc.measure_all()
param_values = [[np.pi / 4, np.pi / 2, np.pi / 3]]
params = [[a, b, c], [c, b, a], [a, c], [c, a]]
expected = [
[
{0: -0.17677666583387008, 1: 0.17677666583378482},
{0: 0.3061861668168149, 1: -0.3061861668167012},
{0: -0.3061861668168149, 1: 0.30618616681678645},
],
[
{0: -0.3061861668168149, 1: 0.30618616681678645},
{0: 0.3061861668168149, 1: -0.3061861668167012},
{0: -0.17677666583387008, 1: 0.17677666583378482},
],
[
{0: -0.17677666583387008, 1: 0.17677666583378482},
{0: -0.3061861668168149, 1: 0.30618616681678645},
],
[
{0: -0.3061861668168149, 1: 0.30618616681678645},
{0: -0.17677666583387008, 1: 0.17677666583378482},
],
]
for i, p in enumerate(params):
gradients = gradient.run([qc], param_values, parameters=[p]).result().gradients[0]
array1 = _quasi2array(gradients, num_qubits=1)
array2 = _quasi2array(expected[i], num_qubits=1)
np.testing.assert_allclose(array1, array2, atol=1e-3)
@data(*gradient_factories)
def test_gradient_multi_arguments(self, grad):
"""Test the sampler gradient for multiple arguments"""
sampler = Sampler()
a = Parameter("a")
b = Parameter("b")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc.measure_all()
qc2 = QuantumCircuit(1)
qc2.rx(b, 0)
qc2.measure_all()
gradient = grad(sampler)
param_list = [[np.pi / 4], [np.pi / 2]]
correct_results = [
[{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}],
[{0: -0.499999, 1: 0.499999}],
]
gradients = gradient.run([qc, qc2], param_list).result().gradients
for i, q_dists in enumerate(gradients):
array1 = _quasi2array(q_dists, num_qubits=1)
array2 = _quasi2array(correct_results[i], num_qubits=1)
np.testing.assert_allclose(array1, array2, atol=1e-3)
# parameters
with self.subTest(msg="Different parameters"):
c = Parameter("c")
qc3 = QuantumCircuit(1)
qc3.rx(c, 0)
qc3.ry(a, 0)
qc3.measure_all()
param_list2 = [[np.pi / 4], [np.pi / 4, np.pi / 4], [np.pi / 4, np.pi / 4]]
gradients = (
gradient.run([qc, qc3, qc3], param_list2, parameters=[[a], [c], None])
.result()
.gradients
)
correct_results = [
[{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}],
[{0: -0.25, 1: 0.25}],
[{0: -0.25, 1: 0.25}, {0: -0.25, 1: 0.25}],
]
for i, q_dists in enumerate(gradients):
array1 = _quasi2array(q_dists, num_qubits=1)
array2 = _quasi2array(correct_results[i], num_qubits=1)
np.testing.assert_allclose(array1, array2, atol=1e-3)
@data(*gradient_factories)
def test_gradient_validation(self, grad):
"""Test sampler gradient's validation"""
sampler = Sampler()
a = Parameter("a")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc.measure_all()
gradient = grad(sampler)
param_list = [[np.pi / 4], [np.pi / 2]]
with self.assertRaises(ValueError):
gradient.run([qc], param_list)
with self.assertRaises(ValueError):
gradient.run([qc, qc], param_list, parameters=[[a]])
with self.assertRaises(ValueError):
gradient.run([qc], [[np.pi / 4, np.pi / 4]])
def test_spsa_gradient(self):
"""Test the SPSA sampler gradient"""
sampler = Sampler()
with self.assertRaises(ValueError):
_ = SPSASamplerGradient(sampler, epsilon=-0.1)
a = Parameter("a")
b = Parameter("b")
c = Parameter("c")
qc = QuantumCircuit(2)
qc.rx(b, 0)
qc.rx(a, 1)
qc.measure_all()
param_list = [[1, 2]]
correct_results = [
[
{0: 0.2273244, 1: -0.6480598, 2: 0.2273244, 3: 0.1934111},
{0: -0.2273244, 1: 0.6480598, 2: -0.2273244, 3: -0.1934111},
],
]
gradient = SPSASamplerGradient(sampler, epsilon=1e-6, seed=123)
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [param]).result().gradients[0]
array1 = _quasi2array(gradients, num_qubits=2)
array2 = _quasi2array(correct_results[i], num_qubits=2)
np.testing.assert_allclose(array1, array2, atol=1e-3)
# multi parameters
with self.subTest(msg="Multiple parameters"):
param_list2 = [[1, 2], [1, 2], [3, 4]]
correct_results2 = [
[
{0: 0.2273244, 1: -0.6480598, 2: 0.2273244, 3: 0.1934111},
{0: -0.2273244, 1: 0.6480598, 2: -0.2273244, 3: -0.1934111},
],
[
{0: -0.2273244, 1: 0.6480598, 2: -0.2273244, 3: -0.1934111},
],
[
{0: -0.0141129, 1: -0.0564471, 2: -0.3642884, 3: 0.4348484},
{0: 0.0141129, 1: 0.0564471, 2: 0.3642884, 3: -0.4348484},
],
]
gradient = SPSASamplerGradient(sampler, epsilon=1e-6, seed=123)
gradients = (
gradient.run([qc] * 3, param_list2, parameters=[None, [b], None]).result().gradients
)
for i, result in enumerate(gradients):
array1 = _quasi2array(result, num_qubits=2)
array2 = _quasi2array(correct_results2[i], num_qubits=2)
np.testing.assert_allclose(array1, array2, atol=1e-3)
# batch size
with self.subTest(msg="Batch size"):
param_list = [[1, 1]]
gradient = SPSASamplerGradient(sampler, epsilon=1e-6, batch_size=4, seed=123)
gradients = gradient.run([qc], param_list).result().gradients
correct_results3 = [
[
{
0: -0.1620149622932887,
1: -0.25872053011771756,
2: 0.3723827084675668,
3: 0.04835278392088804,
},
{
0: -0.1620149622932887,
1: 0.3723827084675668,
2: -0.25872053011771756,
3: 0.04835278392088804,
},
]
]
for i, q_dists in enumerate(gradients):
array1 = _quasi2array(q_dists, num_qubits=2)
array2 = _quasi2array(correct_results3[i], num_qubits=2)
np.testing.assert_allclose(array1, array2, atol=1e-3)
# parameter order
with self.subTest(msg="The order of gradients"):
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc.rz(b, 0)
qc.rx(c, 0)
qc.measure_all()
param_list = [[np.pi / 4, np.pi / 2, np.pi / 3]]
param = [[a, b, c], [c, b, a], [a, c], [c, a]]
correct_results = [
[
{0: -0.17677624757590138, 1: 0.17677624757590138},
{0: 0.17677624757590138, 1: -0.17677624757590138},
{0: 0.17677624757590138, 1: -0.17677624757590138},
],
[
{0: 0.17677624757590138, 1: -0.17677624757590138},
{0: 0.17677624757590138, 1: -0.17677624757590138},
{0: -0.17677624757590138, 1: 0.17677624757590138},
],
[
{0: -0.17677624757590138, 1: 0.17677624757590138},
{0: 0.17677624757590138, 1: -0.17677624757590138},
],
[
{0: 0.17677624757590138, 1: -0.17677624757590138},
{0: -0.17677624757590138, 1: 0.17677624757590138},
],
]
for i, p in enumerate(param):
gradient = SPSASamplerGradient(sampler, epsilon=1e-6, seed=123)
gradients = gradient.run([qc], param_list, parameters=[p]).result().gradients[0]
array1 = _quasi2array(gradients, num_qubits=1)
array2 = _quasi2array(correct_results[i], num_qubits=1)
np.testing.assert_allclose(array1, array2, atol=1e-3)
@data(ParamShiftSamplerGradient, LinCombSamplerGradient)
def test_gradient_random_parameters(self, grad):
"""Test param shift and lin comb w/ random parameters"""
rng = np.random.default_rng(123)
qc = RealAmplitudes(num_qubits=3, reps=1)
params = qc.parameters
qc.rx(3.0 * params[0] + params[1].sin(), 0)
qc.ry(params[0].exp() + 2 * params[1], 1)
qc.rz(params[0] * params[1] - params[2], 2)
qc.p(2 * params[0] + 1, 0)
qc.u(params[0].sin(), params[1] - 2, params[2] * params[3], 1)
qc.sx(2)
qc.rxx(params[0].sin(), 1, 2)
qc.ryy(params[1].cos(), 2, 0)
qc.rzz(params[2] * 2, 0, 1)
qc.crx(params[0].exp(), 1, 2)
qc.cry(params[1].arctan(), 2, 0)
qc.crz(params[2] * -2, 0, 1)
qc.dcx(0, 1)
qc.csdg(0, 1)
qc.toffoli(0, 1, 2)
qc.iswap(0, 2)
qc.swap(1, 2)
qc.global_phase = params[0] * params[1] + params[2].cos().exp()
qc.measure_all()
sampler = Sampler()
findiff = FiniteDiffSamplerGradient(sampler, 1e-6)
gradient = grad(sampler)
num_qubits = qc.num_qubits
num_tries = 10
param_values = rng.normal(0, 2, (num_tries, qc.num_parameters)).tolist()
result1 = findiff.run([qc] * num_tries, param_values).result().gradients
result2 = gradient.run([qc] * num_tries, param_values).result().gradients
self.assertEqual(len(result1), len(result2))
for res1, res2 in zip(result1, result2):
array1 = _quasi2array(res1, num_qubits)
array2 = _quasi2array(res2, num_qubits)
np.testing.assert_allclose(array1, array2, rtol=1e-4)
@data(
FiniteDiffSamplerGradient,
ParamShiftSamplerGradient,
LinCombSamplerGradient,
SPSASamplerGradient,
)
def test_options(self, grad):
"""Test sampler gradient's run options"""
a = Parameter("a")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc.measure_all()
sampler = Sampler(options={"shots": 100})
with self.subTest("sampler"):
if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient:
gradient = grad(sampler, epsilon=1e-6)
else:
gradient = grad(sampler)
options = gradient.options
result = gradient.run([qc], [[1]]).result()
self.assertEqual(result.options.get("shots"), 100)
self.assertEqual(options.get("shots"), 100)
with self.subTest("gradient init"):
if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient:
gradient = grad(sampler, epsilon=1e-6, options={"shots": 200})
else:
gradient = grad(sampler, options={"shots": 200})
options = gradient.options
result = gradient.run([qc], [[1]]).result()
self.assertEqual(result.options.get("shots"), 200)
self.assertEqual(options.get("shots"), 200)
with self.subTest("gradient update"):
if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient:
gradient = grad(sampler, epsilon=1e-6, options={"shots": 200})
else:
gradient = grad(sampler, options={"shots": 200})
gradient.update_default_options(shots=100)
options = gradient.options
result = gradient.run([qc], [[1]]).result()
self.assertEqual(result.options.get("shots"), 100)
self.assertEqual(options.get("shots"), 100)
with self.subTest("gradient run"):
if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient:
gradient = grad(sampler, epsilon=1e-6, options={"shots": 200})
else:
gradient = grad(sampler, options={"shots": 200})
options = gradient.options
result = gradient.run([qc], [[1]], shots=300).result()
self.assertEqual(result.options.get("shots"), 300)
# Only default + sampler options. Not run.
self.assertEqual(options.get("shots"), 200)
@data(
FiniteDiffSamplerGradient,
ParamShiftSamplerGradient,
LinCombSamplerGradient,
SPSASamplerGradient,
)
def test_operations_preserved(self, gradient_cls):
"""Test non-parameterized instructions are preserved and not unrolled."""
x = Parameter("x")
circuit = QuantumCircuit(2)
circuit.initialize(np.array([1, 1, 0, 0]) / np.sqrt(2)) # this should remain as initialize
circuit.crx(x, 0, 1) # this should get unrolled
circuit.measure_all()
values = [np.pi / 2]
expect = [{0: 0, 1: -0.25, 2: 0, 3: 0.25}]
ops = []
def operations_callback(op):
ops.append(op)
sampler = LoggingSampler(operations_callback=operations_callback)
if gradient_cls in [SPSASamplerGradient, FiniteDiffSamplerGradient]:
gradient = gradient_cls(sampler, epsilon=0.01)
else:
gradient = gradient_cls(sampler)
job = gradient.run([circuit], [values])
result = job.result()
with self.subTest(msg="assert initialize is preserved"):
self.assertTrue(all("initialize" in ops_i[0].keys() for ops_i in ops))
with self.subTest(msg="assert result is correct"):
array1 = _quasi2array(result.gradients[0], num_qubits=2)
array2 = _quasi2array(expect, num_qubits=2)
np.testing.assert_allclose(array1, array2, atol=1e-5)
def _quasi2array(quasis: List[QuasiDistribution], num_qubits: int) -> np.ndarray:
ret = np.zeros((len(quasis), 2**num_qubits))
for i, quasi in enumerate(quasis):
ret[i, list(quasi.keys())] = list(quasi.values())
return ret
if __name__ == "__main__":
unittest.main()
|
https://github.com/hephaex/Quantum-Computing-Awesome-List
|
hephaex
|
import cirq
import random
def make_quantum_teleportation_circuit(ranX, ranY):
circuit = cirq.Circuit()
msg, alice, bob = cirq.LineQubit.range(3)
## Bell State
circuit.append([cirq.H(alice), cirq.CNOT(alice, bob)])
## Adding random message in message qubit
circuit.append([cirq.X(msg)**ranX, cirq.Y(msg)**ranY])
## Entangling msg and Alice qubits
circuit.append([cirq.CNOT(msg, alice), cirq.H(msg)])
## Measurements
circuit.append([cirq.measure(alice, msg)])
## We use two classical bit from the bell measurement to recover the state of qubit
circuit.append([cirq.CNOT(alice, bob), cirq.CZ(msg, bob)])
return msg, circuit
def main():
## Creating random variable
ranX = random.random()
ranY = random.random()
msg, circuit = make_quantum_teleportation_circuit(ranX, ranY)
## Simulating the circuit
sim = cirq.Simulator()
message = sim.simulate(cirq.Circuit.from_ops([cirq.X(msg)**ranX, cirq.Y(msg)**ranY]))
print("Block Spehere of Alice Qubit")
b0x, b0y, b0z = cirq.bloch_vector_from_state_vector(message.final_state, 0)
print("X: ", round(b0x, 4),
"Y: ", round(b0y, 4),
"Z: ", round(b0z, 4))
print("\n Circuit:")
print(circuit)
final_results = sim.simulate(circuit)
print("\n Block Spehere of Bob's Qubits:")
b2x, b2y, b2z = cirq.bloch_vector_from_state_vector(final_results.final_state, 2)
print("X: ", round(b2x, 4),
"Y: ", round(b2y, 4),
"Z: ", round(b2z, 4))
if __name__ == '__main__':
main()
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
""" This file contains quantum code in support of Shor's Algorithm
"""
""" Imports from qiskit"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
import sys
import math
import numpy as np
""" ********* QFT Functions *** """
""" Function to create QFT """
def create_QFT(circuit,up_reg,n,with_swaps):
i=n-1
""" Apply the H gates and Cphases"""
""" The Cphases with |angle| < threshold are not created because they do
nothing. The threshold is put as being 0 so all CPhases are created,
but the clause is there so if wanted just need to change the 0 of the
if-clause to the desired value """
while i>=0:
circuit.h(up_reg[i])
j=i-1
while j>=0:
if (np.pi)/(pow(2,(i-j))) > 0:
circuit.cu1( (np.pi)/(pow(2,(i-j))) , up_reg[i] , up_reg[j] )
j=j-1
i=i-1
""" If specified, apply the Swaps at the end """
if with_swaps==1:
i=0
while i < ((n-1)/2):
circuit.swap(up_reg[i], up_reg[n-1-i])
i=i+1
""" Function to create inverse QFT """
def create_inverse_QFT(circuit,up_reg,n,with_swaps):
""" If specified, apply the Swaps at the beginning"""
if with_swaps==1:
i=0
while i < ((n-1)/2):
circuit.swap(up_reg[i], up_reg[n-1-i])
i=i+1
""" Apply the H gates and Cphases"""
""" The Cphases with |angle| < threshold are not created because they do
nothing. The threshold is put as being 0 so all CPhases are created,
but the clause is there so if wanted just need to change the 0 of the
if-clause to the desired value """
i=0
while i<n:
circuit.h(up_reg[i])
if i != n-1:
j=i+1
y=i
while y>=0:
if (np.pi)/(pow(2,(j-y))) > 0:
circuit.cu1( - (np.pi)/(pow(2,(j-y))) , up_reg[j] , up_reg[y] )
y=y-1
i=i+1
""" ********* Arithmetic Functions *** """
""" Helper Functions """
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
"""Function that calculates the angle of a phase shift in the sequential QFT based on the binary digits of a."""
"""a represents a possible value of the classical register"""
def getAngle(a, N):
"""convert the number a to a binary string with length N"""
s=bin(int(a))[2:].zfill(N)
angle = 0
for i in range(0, N):
"""if the digit is 1, add the corresponding value to the angle"""
if s[N-1-i] == '1':
angle += math.pow(2, -(N-i))
angle *= np.pi
return angle
"""Function that calculates the array of angles to be used in the addition in Fourier Space"""
def getAngles(a,N):
s=bin(int(a))[2:].zfill(N)
angles=np.zeros([N])
for i in range(0, N):
for j in range(i,N):
if s[j]=='1':
angles[N-i-1]+=math.pow(2, -(j-i))
angles[N-i-1]*=np.pi
return angles
"""Creation of a doubly controlled phase gate"""
def ccphase(circuit, angle, ctl1, ctl2, tgt):
circuit.cu1(angle/2,ctl1,tgt)
circuit.cx(ctl2,ctl1)
circuit.cu1(-angle/2,ctl1,tgt)
circuit.cx(ctl2,ctl1)
circuit.cu1(angle/2,ctl2,tgt)
"""Creation of the circuit that performs addition by a in Fourier Space"""
"""Can also be used for subtraction by setting the parameter inv to a value different from 0"""
def phiADD(circuit, q, a, N, inv):
angle=getAngles(a,N)
for i in range(0,N):
if inv==0:
circuit.u1(angle[i],q[i])
"""addition"""
else:
circuit.u1(-angle[i],q[i])
"""subtraction"""
"""Single controlled version of the phiADD circuit"""
def cphiADD(circuit, q, ctl, a, n, inv):
angle=getAngles(a,n)
for i in range(0,n):
if inv==0:
circuit.cu1(angle[i],ctl,q[i])
else:
circuit.cu1(-angle[i],ctl,q[i])
"""Doubly controlled version of the phiADD circuit"""
def ccphiADD(circuit,q,ctl1,ctl2,a,n,inv):
angle=getAngles(a,n)
for i in range(0,n):
if inv==0:
ccphase(circuit,angle[i],ctl1,ctl2,q[i])
else:
ccphase(circuit,-angle[i],ctl1,ctl2,q[i])
"""Circuit that implements doubly controlled modular addition by a"""
def ccphiADDmodN(circuit, q, ctl1, ctl2, aux, a, N, n):
ccphiADD(circuit, q, ctl1, ctl2, a, n, 0)
phiADD(circuit, q, N, n, 1)
create_inverse_QFT(circuit, q, n, 0)
circuit.cx(q[n-1],aux)
create_QFT(circuit,q,n,0)
cphiADD(circuit, q, aux, N, n, 0)
ccphiADD(circuit, q, ctl1, ctl2, a, n, 1)
create_inverse_QFT(circuit, q, n, 0)
circuit.x(q[n-1])
circuit.cx(q[n-1], aux)
circuit.x(q[n-1])
create_QFT(circuit,q,n,0)
ccphiADD(circuit, q, ctl1, ctl2, a, n, 0)
"""Circuit that implements the inverse of doubly controlled modular addition by a"""
def ccphiADDmodN_inv(circuit, q, ctl1, ctl2, aux, a, N, n):
ccphiADD(circuit, q, ctl1, ctl2, a, n, 1)
create_inverse_QFT(circuit, q, n, 0)
circuit.x(q[n-1])
circuit.cx(q[n-1],aux)
circuit.x(q[n-1])
create_QFT(circuit, q, n, 0)
ccphiADD(circuit, q, ctl1, ctl2, a, n, 0)
cphiADD(circuit, q, aux, N, n, 1)
create_inverse_QFT(circuit, q, n, 0)
circuit.cx(q[n-1], aux)
create_QFT(circuit, q, n, 0)
phiADD(circuit, q, N, n, 0)
ccphiADD(circuit, q, ctl1, ctl2, a, n, 1)
"""Circuit that implements single controlled modular multiplication by a"""
def cMULTmodN(circuit, ctl, q, aux, a, N, n):
create_QFT(circuit,aux,n+1,0)
for i in range(0, n):
ccphiADDmodN(circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1)
create_inverse_QFT(circuit, aux, n+1, 0)
for i in range(0, n):
circuit.cswap(ctl,q[i],aux[i])
a_inv = modinv(a, N)
create_QFT(circuit, aux, n+1, 0)
i = n-1
while i >= 0:
ccphiADDmodN_inv(circuit, aux, q[i], ctl, aux[n+1], math.pow(2,i)*a_inv % N, N, n+1)
i -= 1
create_inverse_QFT(circuit, aux, n+1, 0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.