repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
The Boolean Logical AND and OR Gates.
"""
import logging
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.qasm import pi
from qiskit.aqua import AquaError
from .multi_control_toffoli_gate import mct
logger = logging.getLogger(__name__)
def _logical_and(circuit, variable_register, flags, target_qubit, ancillary_register, mct_mode):
if flags is not None:
zvf = list(zip(variable_register, flags))
ctl_bits = [v for v, f in zvf if f]
anc_bits = None
if ancillary_register:
anc_bits = [ancillary_register[idx] for idx in range(np.count_nonzero(flags) - 2)]
[circuit.u3(pi, 0, pi, v) for v, f in zvf if f < 0]
circuit.mct(ctl_bits, target_qubit, anc_bits, mode=mct_mode)
[circuit.u3(pi, 0, pi, v) for v, f in zvf if f < 0]
def _logical_or(circuit, qr_variables, flags, qb_target, qr_ancillae, mct_mode):
circuit.u3(pi, 0, pi, qb_target)
if flags is not None:
zvf = list(zip(qr_variables, flags))
ctl_bits = [v for v, f in zvf if f]
anc_bits = [qr_ancillae[idx] for idx in range(np.count_nonzero(flags) - 2)] if qr_ancillae else None
[circuit.u3(pi, 0, pi, v) for v, f in zvf if f > 0]
circuit.mct(ctl_bits, qb_target, anc_bits, mode=mct_mode)
[circuit.u3(pi, 0, pi, v) for v, f in zvf if f > 0]
def _do_checks(flags, qr_variables, qb_target, qr_ancillae, circuit):
# check flags
if flags is None:
flags = [1 for i in range(len(qr_variables))]
else:
if len(flags) > len(qr_variables):
raise AquaError('`flags` cannot be longer than `qr_variables`.')
# check variables
# TODO: improve the check
if isinstance(qr_variables, QuantumRegister) or isinstance(qr_variables, list):
variable_qubits = [qb for qb, i in zip(qr_variables, flags) if not i == 0]
else:
raise ValueError('A QuantumRegister or list of qubits is expected for variables.')
# check target
if isinstance(qb_target, tuple):
target_qubit = qb_target
else:
raise ValueError('A single qubit is expected for the target.')
# check ancilla
if qr_ancillae is None:
ancillary_qubits = []
elif isinstance(qr_ancillae, QuantumRegister):
ancillary_qubits = [qb for qb in qr_ancillae]
elif isinstance(qr_ancillae, list):
ancillary_qubits = qr_ancillae
else:
raise ValueError('An optional list of qubits or a QuantumRegister is expected for ancillae.')
all_qubits = variable_qubits + [target_qubit] + ancillary_qubits
circuit._check_qargs(all_qubits)
circuit._check_dups(all_qubits)
return flags
def logical_and(self, qr_variables, qb_target, qr_ancillae, flags=None, mct_mode='basic'):
"""
Build a collective conjunction (AND) circuit in place using mct.
Args:
self (QuantumCircuit): The QuantumCircuit object to build the conjunction on.
variable_register (QuantumRegister): The QuantumRegister holding the variable qubits.
flags (list): A list of +1/-1/0 to mark negations or omissions of qubits.
target_qubit (tuple(QuantumRegister, int)): The target qubit to hold the conjunction result.
ancillary_register (QuantumRegister): The ancillary QuantumRegister for building the mct.
mct_mode (str): The mct building mode.
"""
flags = _do_checks(flags, qr_variables, qb_target, qr_ancillae, self)
_logical_and(self, qr_variables, flags, qb_target, qr_ancillae, mct_mode)
def logical_or(self, qr_variables, qb_target, qr_ancillae, flags=None, mct_mode='basic'):
"""
Build a collective disjunction (OR) circuit in place using mct.
Args:
self (QuantumCircuit): The QuantumCircuit object to build the disjunction on.
qr_variables (QuantumRegister): The QuantumRegister holding the variable qubits.
flags (list): A list of +1/-1/0 to mark negations or omissions of qubits.
qb_target (tuple(QuantumRegister, int)): The target qubit to hold the disjunction result.
qr_ancillae (QuantumRegister): The ancillary QuantumRegister for building the mct.
mct_mode (str): The mct building mode.
"""
flags = _do_checks(flags, qr_variables, qb_target, qr_ancillae, self)
_logical_or(self, qr_variables, flags, qb_target, qr_ancillae, mct_mode)
QuantumCircuit.AND = logical_and
QuantumCircuit.OR = logical_or
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Controlled-Hadamard (ch) Gate.
"""
import logging
from math import pi
from qiskit import QuantumCircuit
from qiskit.aqua import AquaError
from qiskit.aqua.utils.circuit_utils import is_qubit
logger = logging.getLogger(__name__)
def ch(self, q_control, q_target):
"""
Apply Controlled-Hadamard (ch) Gate.
Note that this implementation of the ch uses a single cx gate,
which is more efficient than what's currently provided in Terra.
Args:
self (QuantumCircuit): The circuit to apply the ch gate on.
q_control ((QuantumRegister, int)): The control qubit.
q_target ((QuantumRegister, int)): The target qubit.
"""
if not is_qubit(q_control):
raise AquaError('A qubit is expected for the control.')
if not self.has_register(q_control[0]):
raise AquaError('The control qubit is expected to be part of the circuit.')
if not is_qubit(q_target):
raise AquaError('A qubit is expected for the target.')
if not self.has_register(q_target[0]):
raise AquaError('The target qubit is expected to be part of the circuit.')
if q_control == q_target:
raise AquaError('The control and target need to be different qubits.')
self.u3(-7 / 4 * pi, 0, 0, q_target)
self.cx(q_control, q_target)
self.u3(7 / 4 * pi, 0, 0, q_target)
return self
QuantumCircuit.ch = ch
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Controlled-RY (cry) and Multiple-Control RY (mcry) Gates
"""
import logging
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.aqua import AquaError
from qiskit.aqua.utils.circuit_utils import is_qubit
logger = logging.getLogger(__name__)
def cry(self, theta, q_control, q_target):
"""
Apply Controlled-RY (cry) Gate.
Args:
self (QuantumCircuit): The circuit to apply the ch gate on.
theta (float): The rotation angle.
q_control ((QuantumRegister, int)): The control qubit.
q_target ((QuantumRegister, int)): The target qubit.
"""
if not is_qubit(q_control):
raise AquaError('A qubit is expected for the control.')
if not self.has_register(q_control[0]):
raise AquaError('The control qubit is expected to be part of the circuit.')
if not is_qubit(q_target):
raise AquaError('A qubit is expected for the target.')
if not self.has_register(q_target[0]):
raise AquaError('The target qubit is expected to be part of the circuit.')
if q_control == q_target:
raise AquaError('The control and target need to be different qubits.')
self.u3(theta / 2, 0, 0, q_target)
self.cx(q_control, q_target)
self.u3(-theta / 2, 0, 0, q_target)
self.cx(q_control, q_target)
return self
def mcry(self, theta, q_controls, q_target, q_ancillae):
"""
Apply Multiple-Control RY (mcry) Gate.
Args:
self (QuantumCircuit): The circuit to apply the ch gate on.
theta (float): The rotation angle.
q_controls (QuantumRegister | (QuantumRegister, int)): The control qubits.
q_target ((QuantumRegister, int)): The target qubit.
q_ancillae (QuantumRegister | (QuantumRegister, int)): The ancillary qubits.
"""
# check controls
if isinstance(q_controls, QuantumRegister):
control_qubits = [qb for qb in q_controls]
elif isinstance(q_controls, list):
control_qubits = q_controls
else:
raise AquaError('The mcry gate needs a list of qubits or a quantum register for controls.')
# check target
if is_qubit(q_target):
target_qubit = q_target
else:
raise AquaError('The mcry gate needs a single qubit as target.')
# check ancilla
if q_ancillae is None:
ancillary_qubits = []
elif isinstance(q_ancillae, QuantumRegister):
ancillary_qubits = [qb for qb in q_ancillae]
elif isinstance(q_ancillae, list):
ancillary_qubits = q_ancillae
else:
raise AquaError('The mcry gate needs None or a list of qubits or a quantum register for ancilla.')
all_qubits = control_qubits + [target_qubit] + ancillary_qubits
self._check_qargs(all_qubits)
self._check_dups(all_qubits)
self.u3(theta / 2, 0, 0, q_target)
self.mct(q_controls, q_target, q_ancillae)
self.u3(-theta / 2, 0, 0, q_target)
self.mct(q_controls, q_target, q_ancillae)
return self
QuantumCircuit.cry = cry
QuantumCircuit.mcry = mcry
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Multiple-Control, Multiple-Target Gate.
"""
import logging
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.aqua import AquaError
logger = logging.getLogger(__name__)
def _ccx_v_chain_compute(qc, control_qubits, ancillary_qubits):
"""
First half (compute) of the multi-control basic mode. It progressively compute the
ccx of the control qubits and put the final result in the last ancillary
qubit
Args:
qc: the QuantumCircuit
control_qubits: the list of control qubits
ancillary_qubits: the list of ancillary qubits
"""
anci_idx = 0
qc.ccx(control_qubits[0], control_qubits[1], ancillary_qubits[anci_idx])
for idx in range(2, len(control_qubits)):
assert anci_idx + 1 < len(
ancillary_qubits
), "Insufficient number of ancillary qubits {0}.".format(
len(ancillary_qubits))
qc.ccx(control_qubits[idx], ancillary_qubits[anci_idx],
ancillary_qubits[anci_idx + 1])
anci_idx += 1
def _ccx_v_chain_uncompute(qc, control_qubits, ancillary_qubits):
"""
Second half (uncompute) of the multi-control basic mode. It progressively compute the
ccx of the control qubits and put the final result in the last ancillary
qubit
Args:
qc: the QuantumCircuit
control_qubits: the list of control qubits
ancillary_qubits: the list of ancillary qubits
"""
anci_idx = len(ancillary_qubits) - 1
for idx in (range(2, len(control_qubits)))[::-1]:
qc.ccx(control_qubits[idx], ancillary_qubits[anci_idx - 1],
ancillary_qubits[anci_idx])
anci_idx -= 1
qc.ccx(control_qubits[0], control_qubits[1], ancillary_qubits[anci_idx])
def mcmt(self,
q_controls,
q_ancillae,
single_control_gate_fun,
q_targets,
mode="basic"):
"""
Apply a Multi-Control, Multi-Target using a generic gate.
It can also be used to implement a generic Multi-Control gate, as the target could also be of length 1.
Args:
q_controls: The list of control qubits
q_ancillae: The list of ancillary qubits
single_control_gate_fun: The single control gate function (e.g QuantumCircuit.cz or QuantumCircuit.ch)
q_targets: A list of qubits or a QuantumRegister to which the gate function should be applied.
mode (string): The implementation mode to use (at the moment, only the basic mode is supported)
"""
# check controls
if isinstance(q_controls, QuantumRegister):
control_qubits = [qb for qb in q_controls]
elif isinstance(q_controls, list):
control_qubits = q_controls
else:
raise AquaError(
'MCT needs a list of qubits or a quantum register for controls.')
# check target
if isinstance(q_targets, QuantumRegister):
target_qubits = [qb for qb in q_targets]
elif isinstance(q_targets, list):
target_qubits = q_targets
else:
raise AquaError(
'MCT needs a list of qubits or a quantum register for targets.')
# check ancilla
if q_ancillae is None:
ancillary_qubits = []
elif isinstance(q_ancillae, QuantumRegister):
ancillary_qubits = [qb for qb in q_ancillae]
elif isinstance(q_ancillae, list):
ancillary_qubits = q_ancillae
else:
raise AquaError(
'MCT needs None or a list of qubits or a quantum register for ancilla.'
)
all_qubits = control_qubits + target_qubits + ancillary_qubits
self._check_qargs(all_qubits)
self._check_dups(all_qubits)
if len(q_controls) == 1:
for qubit in target_qubits:
single_control_gate_fun(self, q_controls[0], qubit)
return
if mode == 'basic':
# last ancillary qubit is the control of the gate
ancn = len(ancillary_qubits)
_ccx_v_chain_compute(self, control_qubits, ancillary_qubits)
for qubit in target_qubits:
single_control_gate_fun(self, ancillary_qubits[ancn - 1], qubit)
_ccx_v_chain_uncompute(self, control_qubits, ancillary_qubits)
else:
raise AquaError(
'Unrecognized mode "{0}" for building mcmt circuit, at the moment only "basic" mode is supported.'
.format(mode))
QuantumCircuit.mcmt = mcmt
|
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.
"""
Multiple-Control Toffoli Gate.
"""
import logging
from math import pi, ceil
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.aqua import AquaError
from qiskit.aqua.utils.circuit_utils import is_qubit
logger = logging.getLogger(__name__)
def _ccx_v_chain(qc, control_qubits, target_qubit, ancillary_qubits, dirty_ancilla=False):
"""
Create new MCT circuit by chaining ccx gates into a V shape.
The dirty_ancilla mode is from https://arxiv.org/abs/quant-ph/9503016 Lemma 7.2
"""
if len(ancillary_qubits) < len(control_qubits) - 2:
raise AquaError('Insufficient number of ancillary qubits.')
if dirty_ancilla:
anci_idx = len(control_qubits) - 3
qc.ccx(control_qubits[len(control_qubits) - 1], ancillary_qubits[anci_idx], target_qubit)
for idx in reversed(range(2, len(control_qubits) - 1)):
qc.ccx(control_qubits[idx], ancillary_qubits[anci_idx - 1], ancillary_qubits[anci_idx])
anci_idx -= 1
anci_idx = 0
qc.ccx(control_qubits[0], control_qubits[1], ancillary_qubits[anci_idx])
for idx in range(2, len(control_qubits) - 1):
qc.ccx(control_qubits[idx], ancillary_qubits[anci_idx], ancillary_qubits[anci_idx + 1])
anci_idx += 1
qc.ccx(control_qubits[len(control_qubits) - 1], ancillary_qubits[anci_idx], target_qubit)
for idx in reversed(range(2, len(control_qubits) - 1)):
qc.ccx(control_qubits[idx], ancillary_qubits[anci_idx - 1], ancillary_qubits[anci_idx])
anci_idx -= 1
qc.ccx(control_qubits[0], control_qubits[1], ancillary_qubits[anci_idx])
if dirty_ancilla:
anci_idx = 0
for idx in range(2, len(control_qubits) - 1):
qc.ccx(control_qubits[idx], ancillary_qubits[anci_idx], ancillary_qubits[anci_idx + 1])
anci_idx += 1
def _cccx(qc, qrs, angle=pi / 4):
"""
a 3-qubit controlled-NOT.
An implementation based on Page 17 of Barenco et al.
Parameters:
qrs:
list of quantum registers. The last qubit is the target, the rest are controls
angle:
default pi/4 when x is not gate
set to pi/8 for square root of not
"""
assert len(qrs) == 4, "There must be exactly 4 qubits of quantum registers for cccx"
# controlled-V
qc.h(qrs[3])
qc.cu1(-angle, qrs[0], qrs[3])
qc.h(qrs[3])
# ------------
qc.cx(qrs[0], qrs[1])
# controlled-Vdag
qc.h(qrs[3])
qc.cu1(angle, qrs[1], qrs[3])
qc.h(qrs[3])
# ---------------
qc.cx(qrs[0], qrs[1])
# controlled-V
qc.h(qrs[3])
qc.cu1(-angle, qrs[1], qrs[3])
qc.h(qrs[3])
# ------------
qc.cx(qrs[1], qrs[2])
# controlled-Vdag
qc.h(qrs[3])
qc.cu1(angle, qrs[2], qrs[3])
qc.h(qrs[3])
# ---------------
qc.cx(qrs[0], qrs[2])
# controlled-V
qc.h(qrs[3])
qc.cu1(-angle, qrs[2], qrs[3])
qc.h(qrs[3])
# ------------
qc.cx(qrs[1], qrs[2])
# controlled-Vdag
qc.h(qrs[3])
qc.cu1(angle, qrs[2], qrs[3])
qc.h(qrs[3])
# ---------------
qc.cx(qrs[0], qrs[2])
# controlled-V
qc.h(qrs[3])
qc.cu1(-angle, qrs[2], qrs[3])
qc.h(qrs[3])
def _ccccx(qc, qrs):
"""
a 4-qubit controlled-NOT.
An implementation based on Page 21 (Lemma 7.5) of Barenco et al.
Parameters:
qrs:
list of quantum registers. The last qubit is the target, the rest are controls
"""
assert len(qrs) == 5, "There must be exactly 5 qubits for ccccx"
# controlled-V
qc.h(qrs[4])
qc.cu1(-pi / 2, qrs[3], qrs[4])
qc.h(qrs[4])
# ------------
_cccx(qc, qrs[:4])
# controlled-Vdag
qc.h(qrs[4])
qc.cu1(pi / 2, qrs[3], qrs[4])
qc.h(qrs[4])
# ------------
_cccx(qc, qrs[:4])
_cccx(qc, [qrs[0], qrs[1], qrs[2], qrs[4]], angle=pi / 8)
def _multicx(qc, qrs, qancilla=None):
"""
construct a circuit for multi-qubit controlled not
Parameters:
qc:
quantum circuit
qrs:
list of quantum registers of at least length 1
qancilla:
a quantum register. can be None if len(qrs) <= 5
Returns:
qc:
a circuit appended with multi-qubit cnot
"""
if len(qrs) <= 0:
pass
elif len(qrs) == 1:
qc.x(qrs[0])
elif len(qrs) == 2:
qc.cx(qrs[0], qrs[1])
elif len(qrs) == 3:
qc.ccx(qrs[0], qrs[1], qrs[2])
else:
_multicx_recursion(qc, qrs, qancilla)
def _multicx_recursion(qc, qrs, qancilla=None):
if len(qrs) == 4:
_cccx(qc, qrs)
elif len(qrs) == 5:
_ccccx(qc, qrs)
else: # qrs[0], qrs[n-2] is the controls, qrs[n-1] is the target, and qancilla as working qubit
assert qancilla is not None, "There must be an ancilla qubit not necesseraly initialized to zero"
n = len(qrs)
m1 = ceil(n / 2)
_multicx_recursion(qc, [*qrs[:m1], qancilla], qrs[m1])
_multicx_recursion(qc, [*qrs[m1:n - 1], qancilla, qrs[n - 1]], qrs[m1 - 1])
_multicx_recursion(qc, [*qrs[:m1], qancilla], qrs[m1])
_multicx_recursion(qc, [*qrs[m1:n - 1], qancilla, qrs[n - 1]], qrs[m1 - 1])
def _multicx_noancilla(qc, qrs):
"""
construct a circuit for multi-qubit controlled not without ancillary
qubits
Parameters:
qc:
quantum circuit
qrs:
list of quantum registers of at least length 1
Returns:
qc:
a circuit appended with multi-qubit cnot
"""
if len(qrs) <= 0:
pass
elif len(qrs) == 1:
qc.x(qrs[0])
elif len(qrs) == 2:
qc.cx(qrs[0], qrs[1])
else:
# qrs[0], qrs[n-2] is the controls, qrs[n-1] is the target
ctls = qrs[:-1]
tgt = qrs[-1]
qc.h(tgt)
qc.mcu1(pi, ctls, tgt)
qc.h(tgt)
def mct(self, q_controls, q_target, q_ancilla, mode='basic'):
"""
Apply Multiple-Control Toffoli operation
Args:
q_controls: The list of control qubits
q_target: The target qubit
q_ancilla: The list of ancillary qubits
mode (string): The implementation mode to use
"""
if len(q_controls) == 1: # cx
self.cx(q_controls[0], q_target)
elif len(q_controls) == 2: # ccx
self.ccx(q_controls[0], q_controls[1], q_target)
else:
# check controls
if isinstance(q_controls, QuantumRegister):
control_qubits = [qb for qb in q_controls]
elif isinstance(q_controls, list):
control_qubits = q_controls
else:
raise AquaError('MCT needs a list of qubits or a quantum register for controls.')
# check target
if is_qubit(q_target):
target_qubit = q_target
else:
raise AquaError('MCT needs a single qubit as target.')
# check ancilla
if q_ancilla is None:
ancillary_qubits = []
elif isinstance(q_ancilla, QuantumRegister):
ancillary_qubits = [qb for qb in q_ancilla]
elif isinstance(q_ancilla, list):
ancillary_qubits = q_ancilla
else:
raise AquaError('MCT needs None or a list of qubits or a quantum register for ancilla.')
all_qubits = control_qubits + [target_qubit] + ancillary_qubits
self._check_qargs(all_qubits)
self._check_dups(all_qubits)
if mode == 'basic':
_ccx_v_chain(self, control_qubits, target_qubit, ancillary_qubits, dirty_ancilla=False)
elif mode == 'basic-dirty-ancilla':
_ccx_v_chain(self, control_qubits, target_qubit, ancillary_qubits, dirty_ancilla=True)
elif mode == 'advanced':
_multicx(self, [*control_qubits, target_qubit], ancillary_qubits[0] if ancillary_qubits else None)
elif mode == 'noancilla':
_multicx_noancilla(self, [*control_qubits, target_qubit])
else:
raise AquaError('Unrecognized mode for building MCT circuit: {}.'.format(mode))
def cnx(self, *args, **kwargs):
logger.warning("The gate name 'cnx' will be deprecated. Please use 'mct' (Multiple-Control Toffoli) instead.")
return mct(self, *args, **kwargs)
QuantumCircuit.mct = mct
QuantumCircuit.cnx = cnx
|
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.
"""
Multiple-Control U1 gate. Not using ancillary qubits.
"""
import logging
from numpy import angle
from sympy.combinatorics.graycode import GrayCode
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.aqua.utils.controlled_circuit import apply_cu1
logger = logging.getLogger(__name__)
def _apply_mcu1(circuit, theta, ctls, tgt, global_phase=0):
"""Apply multi-controlled u1 gate from ctls to tgt with angle theta."""
n = len(ctls)
gray_code = list(GrayCode(n).generate_gray())
last_pattern = None
theta_angle = theta*(1/(2**(n-1)))
gp_angle = angle(global_phase)*(1/(2**(n-1)))
for pattern in gray_code:
if '1' not in pattern:
continue
if last_pattern is None:
last_pattern = pattern
#find left most set bit
lm_pos = list(pattern).index('1')
#find changed bit
comp = [i != j for i, j in zip(pattern, last_pattern)]
if True in comp:
pos = comp.index(True)
else:
pos = None
if pos is not None:
if pos != lm_pos:
circuit.cx(ctls[pos], ctls[lm_pos])
else:
indices = [i for i, x in enumerate(pattern) if x == '1']
for idx in indices[1:]:
circuit.cx(ctls[idx], ctls[lm_pos])
#check parity
if pattern.count('1') % 2 == 0:
#inverse
apply_cu1(circuit, -theta_angle, ctls[lm_pos], tgt)
if global_phase:
circuit.u1(-gp_angle, ctls[lm_pos])
else:
apply_cu1(circuit, theta_angle, ctls[lm_pos], tgt)
if global_phase:
circuit.u1(gp_angle, ctls[lm_pos])
last_pattern = pattern
def mcu1(self, theta, control_qubits, target_qubit):
"""
Apply Multiple-Controlled U1 gate
Args:
theta: angle theta
control_qubits: The list of control qubits
target_qubit: The target qubit
"""
if isinstance(target_qubit, QuantumRegister) and len(target_qubit) == 1:
target_qubit = target_qubit[0]
temp = []
self._check_qargs(control_qubits)
temp += control_qubits
self._check_qargs([target_qubit])
temp.append(target_qubit)
self._check_dups(temp)
n_c = len(control_qubits)
if n_c == 1: # cu1
apply_cu1(self, theta, control_qubits[0], target_qubit)
else:
_apply_mcu1(self, theta, control_qubits, target_qubit)
QuantumCircuit.mcu1 = mcu1
|
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.
"""
Multiple-Control U3 gate. Not using ancillary qubits.
"""
import logging
from sympy.combinatorics.graycode import GrayCode
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.aqua.utils.controlled_circuit import apply_cu3
logger = logging.getLogger(__name__)
def _apply_mcu3(circuit, theta, phi, lam, ctls, tgt):
"""Apply multi-controlled u3 gate from ctls to tgt with angles theta,
phi, lam."""
n = len(ctls)
gray_code = list(GrayCode(n).generate_gray())
last_pattern = None
theta_angle = theta*(1/(2**(n-1)))
phi_angle = phi*(1/(2**(n-1)))
lam_angle = lam*(1/(2**(n-1)))
for pattern in gray_code:
if not '1' in pattern:
continue
if last_pattern is None:
last_pattern = pattern
#find left most set bit
lm_pos = list(pattern).index('1')
#find changed bit
comp = [i != j for i, j in zip(pattern, last_pattern)]
if True in comp:
pos = comp.index(True)
else:
pos = None
if pos is not None:
if pos != lm_pos:
circuit.cx(ctls[pos], ctls[lm_pos])
else:
indices = [i for i, x in enumerate(pattern) if x == '1']
for idx in indices[1:]:
circuit.cx(ctls[idx], ctls[lm_pos])
#check parity
if pattern.count('1') % 2 == 0:
#inverse
apply_cu3(circuit, -theta_angle, phi_angle, lam_angle,
ctls[lm_pos], tgt)
else:
apply_cu3(circuit, theta_angle, phi_angle, lam_angle,
ctls[lm_pos], tgt)
last_pattern = pattern
def mcu3(self, theta, phi, lam, control_qubits, target_qubit):
"""
Apply Multiple-Controlled U3 gate
Args:
theta: angle theta
phi: angle phi
lam: angle lambda
control_qubits: The list of control qubits
target_qubit: The target qubit
"""
if isinstance(target_qubit, QuantumRegister) and len(target_qubit) == 1:
target_qubit = target_qubit[0]
temp = []
self._check_qargs(control_qubits)
temp += control_qubits
self._check_qargs([target_qubit])
temp.append(target_qubit)
self._check_dups(temp)
n_c = len(control_qubits)
if n_c == 1: # cu3
apply_cu3(self, theta, phi, lam, control_qubits[0], target_qubit)
else:
_apply_mcu3(self, theta, phi, lam, control_qubits, target_qubit)
QuantumCircuit.mcu3 = mcu3
|
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.
"""
This module contains the definition of a base class for eigenvalue estimators.
"""
from qiskit.aqua import Pluggable
from qiskit import QuantumCircuit
from abc import abstractmethod
class Eigenvalues(Pluggable):
"""Base class for eigenvalue estimation.
This method should initialize the module and its configuration, and
use an exception if a component of the module is available.
Args:
params (dict): configuration dictionary
"""
@abstractmethod
def __init__(self):
super().__init__()
@classmethod
def init_params(cls, params):
eigs_params = params.get(Pluggable.SECTION_KEY_EIGS)
args = {k: v for k, v in eigs_params.items() if k != 'name'}
return cls(**args)
@abstractmethod
def get_register_sizes(self):
raise NotImplementedError()
@abstractmethod
def get_scaling(self):
raise NotImplementedError()
@abstractmethod
def construct_circuit(self, mode, register=None):
"""Construct the eigenvalue estimation quantum circuit.
Args:
mode (str): 'matrix' or 'circuit'
register (QuantumRegister): register for circuit construction
where eigenvalues will be stored.
Returns:
QuantumCircuit object for the eigenvalue estimation circuit.
"""
raise NotImplementedError()
def construct_inverse(self, mode, circuit):
"""Construct the inverse eigenvalue estimation quantum circuit.
Args:
mode (str): consctruction mode, 'matrix' not supported
circuit (QuantumCircuit): the quantum circuit to invert
Returns:
QuantumCircuit object for of the inverted eigenvalue estimation
circuit.
"""
if mode == 'matrix':
raise NotImplementedError('The matrix mode is not supported.')
if circuit is None:
raise ValueError('Circuit was not constructed beforehand.')
self._inverse = circuit.inverse()
return self._inverse
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import QuantumRegister
from qiskit.aqua import Operator, AquaError
from qiskit.aqua import Pluggable, PluggableType, get_pluggable_class
from qiskit.aqua.components.eigs import Eigenvalues
from qiskit.aqua.circuits import PhaseEstimationCircuit
class EigsQPE(Eigenvalues):
""" This class embeds a PhaseEstimationCircuit for getting the eigenvalues of a matrix.
Specifically, this class is based on PhaseEstimationCircuit with no measurements and additional
handling of negative eigenvalues, e.g. for HHL. It uses many parameters
known from plain QPE. It depends on QFT and IQFT.
"""
CONFIGURATION = {
'name': 'EigsQPE',
'description': 'Quantum Phase Estimation for eigenvalues',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'eigsqpe_schema',
'type': 'object',
'properties': {
'num_time_slices': {
'type': 'integer',
'default': 1,
'minimum': 0
},
'expansion_mode': {
'type': 'string',
'default': 'trotter',
'oneOf': [
{'enum': [
'suzuki',
'trotter'
]}
]
},
'expansion_order': {
'type': 'integer',
'default': 1,
'minimum': 1
},
'num_ancillae': {
'type': 'integer',
'default': 1,
'minimum': 1
},
'evo_time': {
'type': ['number', 'null'],
'default': None
},
'negative_evals': {
'type': 'boolean',
'default': False
},
},
'additionalProperties': False
},
'depends': [
{'pluggable_type': 'iqft',
'default': {
'name': 'STANDARD',
}
},
{'pluggable_type': 'qft',
'default': {
'name': 'STANDARD',
}
},
],
}
def __init__(
self, operator, iqft,
num_time_slices=1,
num_ancillae=1,
expansion_mode='trotter',
expansion_order=1,
evo_time=None,
negative_evals=False,
ne_qfts=[None, None]
):
"""Constructor.
Args:
operator (Operator): the hamiltonian Operator object
iqft (IQFT): the Inverse Quantum Fourier Transform pluggable component
num_time_slices (int, optional): the number of time slices
num_ancillae (int, optional): the number of ancillary qubits to use for the measurement
expansion_mode (str, optional): the expansion mode (trotter|suzuki)
expansion_order (int, optional): the suzuki expansion order
evo_time (float, optional): the evolution time
negative_evals (bool, optional): indicate if negative eigenvalues need to be handled
ne_qfts ([QFT, IQFT], optional): the QFT and IQFT pluggable components for handling negative eigenvalues
"""
super().__init__()
super().validate(locals())
self._operator = operator
self._iqft = iqft
self._num_ancillae = num_ancillae
self._num_time_slices = num_time_slices
self._expansion_mode = expansion_mode
self._expansion_order = expansion_order
self._evo_time = evo_time
self._negative_evals = negative_evals
self._ne_qfts = ne_qfts
self._init_constants()
@classmethod
def init_params(cls, params, matrix):
"""
Initialize via parameters dictionary and algorithm input instance
Args:
params: parameters dictionary
matrix: two dimensional array which represents the operator
"""
if matrix is None:
raise AquaError("Operator instance is required.")
if not isinstance(matrix, np.ndarray):
matrix = np.array(matrix)
eigs_params = params.get(Pluggable.SECTION_KEY_EIGS)
args = {k: v for k, v in eigs_params.items() if k != 'name'}
num_ancillae = eigs_params['num_ancillae']
negative_evals = eigs_params['negative_evals']
# Adding an additional flag qubit for negative eigenvalues
if negative_evals:
num_ancillae += 1
args['num_ancillae'] = num_ancillae
args['operator'] = Operator(matrix=matrix)
# Set up iqft, we need to add num qubits to params which is our num_ancillae bits here
iqft_params = params.get(Pluggable.SECTION_KEY_IQFT)
iqft_params['num_qubits'] = num_ancillae
args['iqft'] = get_pluggable_class(PluggableType.IQFT,
iqft_params['name']).init_params(params)
# For converting the encoding of the negative eigenvalues, we need two
# additional instances for QFT and IQFT
if negative_evals:
ne_params = params
qft_num_qubits = iqft_params['num_qubits']
ne_qft_params = params.get(Pluggable.SECTION_KEY_QFT)
ne_qft_params['num_qubits'] = qft_num_qubits - 1
ne_iqft_params = params.get(Pluggable.SECTION_KEY_IQFT)
ne_iqft_params['num_qubits'] = qft_num_qubits - 1
ne_params['qft'] = ne_qft_params
ne_params['iqft'] = ne_iqft_params
args['ne_qfts'] = [get_pluggable_class(PluggableType.QFT,
ne_qft_params['name']).init_params(ne_params),
get_pluggable_class(PluggableType.IQFT,
ne_iqft_params['name']).init_params(ne_params)]
else:
args['ne_qfts'] = [None, None]
return cls(**args)
def _init_constants(self):
# estimate evolution time
self._operator._check_representation('paulis')
paulis = self._operator.paulis
if self._evo_time == None:
lmax = sum([abs(p[0]) for p in self._operator.paulis])
if not self._negative_evals:
self._evo_time = (1-2**-self._num_ancillae)*2*np.pi/lmax
else:
self._evo_time = (1/2-2**-self._num_ancillae)*2*np.pi/lmax
# check for identify paulis to get its coef for applying global phase shift on ancillae later
num_identities = 0
for p in self._operator.paulis:
if np.all(p[1].z == 0) and np.all(p[1].x == 0):
num_identities += 1
if num_identities > 1:
raise RuntimeError('Multiple identity pauli terms are present.')
self._ancilla_phase_coef = p[0].real if isinstance(p[0], complex) else p[0]
def get_register_sizes(self):
return self._operator.num_qubits, self._num_ancillae
def get_scaling(self):
return self._evo_time
def construct_circuit(self, mode, register=None):
""" Construct the eigenvalues estimation using the PhaseEstimationCircuit
Args:
mode (str): consctruction mode, 'matrix' not supported
register (QuantumRegister): the register to use for the quantum state
Returns:
the QuantumCircuit object for the constructed circuit
"""
if mode == 'matrix':
raise ValueError('QPE is only possible as a circuit not as a matrix.')
pe = PhaseEstimationCircuit(
operator=self._operator, state_in=None, iqft=self._iqft,
num_time_slices=self._num_time_slices, num_ancillae=self._num_ancillae,
expansion_mode=self._expansion_mode, expansion_order=self._expansion_order,
evo_time=self._evo_time
)
a = QuantumRegister(self._num_ancillae)
q = register
qc = pe.construct_circuit(state_register=q, ancillary_register=a)
# handle negative eigenvalues
if self._negative_evals:
self._handle_negative_evals(qc, a)
self._circuit = qc
self._output_register = a
self._input_register = q
return self._circuit
def _handle_negative_evals(self, qc, q):
sgn = q[0]
qs = [q[i] for i in range(1, len(q))]
for qi in qs:
qc.cx(sgn, qi)
self._ne_qfts[0].construct_circuit(mode='circuit', qubits=qs, circuit=qc, do_swaps=False)
for i, qi in enumerate(reversed(qs)):
qc.cu1(2*np.pi/2**(i+1), sgn, qi)
self._ne_qfts[1].construct_circuit(mode='circuit', qubits=qs, circuit=qc, do_swaps=False)
|
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.
"""
This module contains the definition of a base class for
feature map. Several types of commonly used approaches.
"""
from collections import OrderedDict
import copy
import itertools
import logging
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import Pauli
from qiskit.qasm import pi
from sympy.core.numbers import NaN, Float
from qiskit.aqua import Operator
from qiskit.aqua.components.feature_maps import FeatureMap, self_product
logger = logging.getLogger(__name__)
class PauliExpansion(FeatureMap):
"""
Mapping data with the second order expansion followed by entangling gates.
Refer to https://arxiv.org/pdf/1804.11326.pdf for details.
"""
CONFIGURATION = {
'name': 'PauliExpansion',
'description': 'Pauli expansion for feature map (any order)',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'Pauli_Expansion_schema',
'type': 'object',
'properties': {
'depth': {
'type': 'integer',
'default': 2,
'minimum': 1
},
'entangler_map': {
'type': ['array', 'null'],
'default': None
},
'entanglement': {
'type': 'string',
'default': 'full',
'oneOf': [
{'enum': ['full', 'linear']}
]
},
'paulis': {
'type': ['array'],
"items": {
"type": "string"
},
'default': ['Z', 'ZZ']
}
},
'additionalProperties': False
}
}
def __init__(self, feature_dimension, depth=2, entangler_map=None,
entanglement='full', paulis=['Z', 'ZZ'], data_map_func=self_product):
"""Constructor.
Args:
feature_dimension (int): number of features
depth (int): the number of repeated circuits
entangler_map (list[list]): describe the connectivity of qubits, each list describes
[source, target], or None for full entanglement.
Note that the order is the list is the order of
applying the two-qubit gate.
entanglement (str): ['full', 'linear'], generate the qubit connectivitiy by predefined
topology
paulis (str): a comma-seperated string for to-be-used paulis
data_map_func (Callable): a mapping function for data x
"""
self.validate(locals())
super().__init__()
self._num_qubits = self._feature_dimension = feature_dimension
self._depth = depth
if entangler_map is None:
self._entangler_map = self.get_entangler_map(entanglement, feature_dimension)
else:
self._entangler_map = self.validate_entangler_map(entangler_map, feature_dimension)
self._pauli_strings = self._build_subset_paulis_string(paulis)
self._data_map_func = data_map_func
self._magic_num = np.nan
self._param_pos = OrderedDict()
self._circuit_template = self._build_circuit_template()
def _build_subset_paulis_string(self, paulis):
# fill out the paulis to the number of qubits
temp_paulis = []
for pauli in paulis:
len_pauli = len(pauli)
for possible_pauli_idx in itertools.combinations(range(self._num_qubits), len_pauli):
string_temp = ['I'] * self._num_qubits
for idx in range(len(possible_pauli_idx)):
string_temp[-possible_pauli_idx[idx] - 1] = pauli[-idx - 1]
temp_paulis.append(''.join(string_temp))
# clean up string that can not be entangled.
final_paulis = []
for pauli in temp_paulis:
where_z = np.where(np.asarray(list(pauli[::-1])) != 'I')[0]
if len(where_z) == 1:
final_paulis.append(pauli)
else:
is_valid = True
for src, targ in itertools.combinations(where_z, 2):
if [src, targ] not in self._entangler_map:
is_valid = False
break
if is_valid:
final_paulis.append(pauli)
else:
logger.warning("Due to the limited entangler_map,"
" {} is skipped.".format(pauli))
logger.info("Pauli terms include: {}".format(final_paulis))
return final_paulis
def _build_circuit_template(self):
x = np.asarray([self._magic_num] * self._num_qubits)
qr = QuantumRegister(self._num_qubits, name='q')
qc = self.construct_circuit(x, qr)
for index in range(len(qc.data)):
gate_param = qc.data[index][0].params
param_sub_pos = []
for x in range(len(gate_param)):
if isinstance(gate_param[x], NaN):
param_sub_pos.append(x)
if param_sub_pos != []:
self._param_pos[index] = param_sub_pos
return qc
def _extract_data_for_rotation(self, pauli, x):
where_non_i = np.where(np.asarray(list(pauli[::-1])) != 'I')[0]
return x[where_non_i]
def _construct_circuit_with_template(self, x):
coeffs = [self._data_map_func(self._extract_data_for_rotation(pauli, x))
for pauli in self._pauli_strings] * self._depth
qc = copy.deepcopy(self._circuit_template)
data_idx = 0
for key, value in self._param_pos.items():
new_param = coeffs[data_idx]
for pos in value:
qc.data[key].params[pos] = Float(2. * new_param) # rotation angle is 2x
data_idx += 1
return qc
def construct_circuit(self, x, qr=None, inverse=False):
"""
Construct the second order expansion based on given data.
Args:
x (numpy.ndarray): 1-D to-be-transformed data.
qr (QauntumRegister): the QuantumRegister object for the circuit, if None,
generate new registers with name q.
inverse (bool): whether or not inverse the circuit
Returns:
QuantumCircuit: a quantum circuit transform data x.
"""
if not isinstance(x, np.ndarray):
raise TypeError("x must be numpy array.")
if x.ndim != 1:
raise ValueError("x must be 1-D array.")
if x.shape[0] != self._num_qubits:
raise ValueError("number of qubits and data dimension must be the same.")
if qr is None:
qc = self._construct_circuit_with_template(x)
else:
qc = QuantumCircuit(qr)
for _ in range(self._depth):
for i in range(self._num_qubits):
qc.u2(0, pi, qr[i])
for pauli in self._pauli_strings:
coeff = self._data_map_func(self._extract_data_for_rotation(pauli, x))
p = Pauli.from_label(pauli)
qc += Operator.construct_evolution_circuit([[coeff, p]], 1, 1, qr)
if inverse:
qc = qc.inverse()
return qc
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
This module contains the definition of a base class for
feature map. Several types of commonly used approaches.
"""
import logging
import numpy as np
from qiskit import QuantumCircuit
from qiskit.aqua.utils.arithmetic import next_power_of_2_base
from qiskit.aqua.components.feature_maps import FeatureMap
from qiskit.aqua.circuits import StateVectorCircuit
logger = logging.getLogger(__name__)
class RawFeatureVector(FeatureMap):
"""
Using raw feature vector as the initial state vector
"""
CONFIGURATION = {
'name': 'RawFeatureVector',
'description': 'Raw feature vector',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'raw_feature_vector_schema',
'type': 'object',
'properties': {
'feature_dimension': {
'type': 'integer',
'default': 2,
'minimum': 1
},
},
'additionalProperties': False
}
}
def __init__(self, feature_dimension=2):
"""Constructor.
Args:
feature_vector: The raw feature vector
"""
self.validate(locals())
super().__init__()
self._feature_dimension = feature_dimension
self._num_qubits = next_power_of_2_base(feature_dimension)
def construct_circuit(self, x, qr=None, inverse=False):
"""
Construct the second order expansion based on given data.
Args:
x (numpy.ndarray): 1-D to-be-encoded data.
qr (QauntumRegister): the QuantumRegister object for the circuit, if None,
generate new registers with name q.
Returns:
QuantumCircuit: a quantum circuit transform data x.
"""
if not isinstance(x, np.ndarray):
raise TypeError("x must be numpy array.")
if x.ndim != 1:
raise ValueError("x must be 1-D array.")
if x.shape[0] != self._feature_dimension:
raise ValueError("Unexpected feature vector dimension.")
state_vector = np.pad(x, (0, (1 << self.num_qubits) - len(x)), 'constant')
svc = StateVectorCircuit(state_vector)
return svc.construct_circuit(register=qr)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
import logging
from qiskit import QuantumRegister, QuantumCircuit
from qiskit import execute as q_execute
from qiskit import BasicAer
from qiskit.aqua import AquaError, aqua_globals
from qiskit.aqua.components.initial_states import InitialState
from qiskit.aqua.circuits import StateVectorCircuit
from qiskit.aqua.utils.arithmetic import normalize_vector
from qiskit.aqua.utils.circuit_utils import convert_to_basis_gates
logger = logging.getLogger(__name__)
class Custom(InitialState):
"""A custom initial state."""
CONFIGURATION = {
'name': 'CUSTOM',
'description': 'Custom initial state',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'custom_state_schema',
'type': 'object',
'properties': {
'state': {
'type': 'string',
'default': 'zero',
'oneOf': [
{'enum': ['zero', 'uniform', 'random']}
]
},
'state_vector': {
'type': ['array', 'null'],
"items": {
"type": "number"
},
'default': None
}
},
'additionalProperties': False
}
}
def __init__(self, num_qubits, state="zero", state_vector=None, circuit=None):
"""Constructor.
Args:
num_qubits (int): number of qubits
state (str): `zero`, `uniform` or `random`
state_vector: customized vector
circuit (QuantumCircuit): the actual custom circuit for the desired initial state
"""
loc = locals().copy()
# since state_vector is a numpy array of complex numbers which aren't json valid,
# remove it from validation
del loc['state_vector']
self.validate(loc)
super().__init__()
self._num_qubits = num_qubits
self._state = state
size = np.power(2, self._num_qubits)
self._circuit = None
if circuit is not None:
if circuit.width() != num_qubits:
logger.warning('The specified num_qubits and the provided custom circuit do not match.')
self._circuit = convert_to_basis_gates(circuit)
if state_vector is not None:
self._state = None
self._state_vector = None
logger.warning('The provided state_vector is ignored in favor of the provided custom circuit.')
else:
if state_vector is None:
if self._state == 'zero':
self._state_vector = np.array([1.0] + [0.0] * (size - 1))
elif self._state == 'uniform':
self._state_vector = np.array([1.0 / np.sqrt(size)] * size)
elif self._state == 'random':
self._state_vector = normalize_vector(aqua_globals.random.rand(size))
else:
raise AquaError('Unknown state {}'.format(self._state))
else:
if len(state_vector) != np.power(2, self._num_qubits):
raise AquaError('The state vector length {} is incompatible with the number of qubits {}'.format(
len(state_vector), self._num_qubits
))
self._state_vector = normalize_vector(state_vector)
self._state = None
def construct_circuit(self, mode, register=None):
"""
Construct the statevector of desired initial state.
Args:
mode (string): `vector` or `circuit`. The `vector` mode produces the vector.
While the `circuit` constructs the quantum circuit corresponding that
vector.
register (QuantumRegister): register for circuit construction.
Returns:
QuantumCircuit or numpy.ndarray: statevector.
Raises:
AquaError: when mode is not 'vector' or 'circuit'.
"""
if mode == 'vector':
if self._state_vector is None:
if self._circuit is not None:
self._state_vector = np.asarray(q_execute(self._circuit, BasicAer.get_backend(
'statevector_simulator')).result().get_statevector(self._circuit))
return self._state_vector
elif mode == 'circuit':
if self._circuit is None:
if register is None:
register = QuantumRegister(self._num_qubits, name='q')
# create emtpy quantum circuit
circuit = QuantumCircuit()
# if register is actually a list of qubits
if type(register) is list:
# loop over all qubits and add the required registers
for q in register:
if not circuit.has_register(q[0]):
circuit.add_register(q[0])
else:
# if an actual register is given, add it
circuit.add_register(register)
if self._state is None or self._state == 'random':
svc = StateVectorCircuit(self._state_vector)
svc.construct_circuit(circuit, register)
elif self._state == 'zero':
pass
elif self._state == 'uniform':
for i in range(self._num_qubits):
circuit.u2(0.0, np.pi, register[i])
else:
pass
self._circuit = circuit
return self._circuit.copy()
else:
raise AquaError('Mode should be either "vector" or "circuit"')
|
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.
from qiskit import QuantumRegister, QuantumCircuit
import numpy as np
from qiskit.aqua.components.initial_states import InitialState
class Zero(InitialState):
"""A zero (null/vacuum) state."""
CONFIGURATION = {
'name': 'ZERO',
'description': 'Zero initial state',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'zero_state_schema',
'type': 'object',
'properties': {
},
'additionalProperties': False
}
}
def __init__(self, num_qubits):
"""Constructor.
Args:
num_qubits (int): number of qubits.
"""
super().__init__()
self._num_qubits = num_qubits
def construct_circuit(self, mode, register=None):
"""
Construct the statevector of desired initial state.
Args:
mode (string): `vector` or `circuit`. The `vector` mode produces the vector.
While the `circuit` constructs the quantum circuit corresponding that
vector.
register (QuantumRegister): register for circuit construction.
Returns:
QuantumCircuit or numpy.ndarray: statevector.
Raises:
ValueError: when mode is not 'vector' or 'circuit'.
"""
if mode == 'vector':
return np.array([1.0] + [0.0] * (np.power(2, self._num_qubits) - 1))
elif mode == 'circuit':
if register is None:
register = QuantumRegister(self._num_qubits, name='q')
quantum_circuit = QuantumCircuit(register)
return quantum_circuit
else:
raise ValueError('Mode should be either "vector" or "circuit"')
|
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.
"""
This module contains the definition of a base class for inverse quantum fourier transforms.
"""
from abc import abstractmethod
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import Pluggable, AquaError
class IQFT(Pluggable):
"""Base class for Inverse QFT.
This method should initialize the module and its configuration, and
use an exception if a component of the module is
available.
Args:
configuration (dict): configuration dictionary
"""
@abstractmethod
def __init__(self, *args, **kwargs):
super().__init__()
@classmethod
def init_params(cls, params):
iqft_params = params.get(Pluggable.SECTION_KEY_IQFT)
kwargs = {k: v for k, v in iqft_params.items() if k != 'name'}
return cls(**kwargs)
@abstractmethod
def _build_matrix(self):
raise NotImplementedError
@abstractmethod
def _build_circuit(self, qubits=None, circuit=None, do_swaps=True):
raise NotImplementedError
def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True):
"""Construct the circuit.
Args:
mode (str): 'matrix' or 'circuit'
qubits (QuantumRegister or qubits): register or qubits to build the circuit on.
circuit (QuantumCircuit): circuit for construction.
do_swaps (bool): include the swaps.
Returns:
The matrix or circuit depending on the specified mode.
"""
if mode == 'circuit':
return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps)
elif mode == 'matrix':
return self._build_matrix()
else:
raise AquaError('Unrecognized mode: {}.'.format(mode))
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from copy import deepcopy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.aqua import aqua_globals
from qiskit.aqua.components.optimizers import ADAM
from qiskit.aqua.components.uncertainty_models import UniformDistribution, MultivariateUniformDistribution
from qiskit.aqua.components.uncertainty_models import UnivariateVariationalDistribution, \
MultivariateVariationalDistribution
from qiskit.aqua.components.variational_forms import RY
from qiskit.aqua import AquaError, Pluggable
from qiskit.aqua.components.neural_networks.generative_network import GenerativeNetwork
from qiskit.aqua.components.initial_states import Custom
class QuantumGenerator(GenerativeNetwork):
"""
Generator
"""
CONFIGURATION = {
'name': 'QuantumGenerator',
'description': 'qGAN Generator Network',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'generator_schema',
'type': 'object',
'properties': {
'bounds': {
'type': 'array'
},
'num_qubits': {
'type': 'array'
},
'init_params': {
'type': ['array', 'null'],
'default': None
},
'snapshot_dir': {
'type': ['string', 'null'],
'default': None
}
},
'additionalProperties': False
}
}
def __init__(self, bounds, num_qubits, generator_circuit=None, init_params=None, snapshot_dir=None):
"""
Initialize the generator network.
Args:
bounds: array, k min/max data values [[min_1,max_1],...,[min_k,max_k]], given input data dim k
num_qubits: array, k numbers of qubits to determine representation resolution,
i.e. n qubits enable the representation of 2**n values [n_1,..., n_k]
generator_circuit: UnivariateVariationalDistribution for univariate data/
MultivariateVariationalDistribution for multivariate data, Quantum circuit to implement the generator.
init_params: 1D numpy array or list, Initialization for the generator's parameters.
snapshot_dir: str or None, if not None save the optimizer's parameter after every update step to the given
directory
"""
self._bounds = bounds
self._num_qubits = num_qubits
self.generator_circuit = generator_circuit
if self.generator_circuit is None:
entangler_map = []
if np.sum(num_qubits) > 2:
for i in range(int(np.sum(num_qubits))):
entangler_map.append([i, int(np.mod(i + 1, np.sum(num_qubits)))])
else:
if np.sum(num_qubits) > 1:
entangler_map.append([0, 1])
if len(num_qubits)>1:
num_qubits = list(map(int, num_qubits))
low = bounds[:, 0].tolist()
high = bounds[:, 1].tolist()
init_dist = MultivariateUniformDistribution(num_qubits, low=low, high=high)
q = QuantumRegister(sum(num_qubits))
qc = QuantumCircuit(q)
init_dist.build(qc, q)
init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc)
# Set variational form
var_form = RY(sum(num_qubits), depth=1, initial_state=init_distribution, entangler_map=entangler_map,
entanglement_gate='cz')
if init_params is None:
init_params = aqua_globals.random.rand(var_form.num_parameters) * 2 * 1e-2
# Set generator circuit
self.generator_circuit = MultivariateVariationalDistribution(num_qubits, var_form, init_params,
low=low, high=high)
else:
init_dist = UniformDistribution(sum(num_qubits), low=bounds[0], high=bounds[1])
q = QuantumRegister(sum(num_qubits), name='q')
qc = QuantumCircuit(q)
init_dist.build(qc, q)
init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc)
var_form = RY(sum(num_qubits), depth=1, initial_state=init_distribution, entangler_map=entangler_map,
entanglement_gate='cz')
if init_params is None:
init_params = aqua_globals.random.rand(var_form.num_parameters) * 2 * 1e-2
# Set generator circuit
self.generator_circuit = UnivariateVariationalDistribution(int(np.sum(num_qubits)), var_form,
init_params, low=bounds[0], high=bounds[1])
if len(num_qubits) > 1:
if isinstance(self.generator_circuit, MultivariateVariationalDistribution):
pass
else:
raise AquaError('Set multivariate variational distribution to represent multivariate data')
else:
if isinstance(self.generator_circuit, UnivariateVariationalDistribution):
pass
else:
raise AquaError('Set univariate variational distribution to represent univariate data')
# Set optimizer for updating the generator network
self._optimizer = ADAM(maxiter=1, tol=1e-6, lr=1e-5, beta_1=0.9, beta_2=0.99, noise_factor=1e-8,
eps=1e-10, amsgrad=True, snapshot_dir=snapshot_dir)
if np.ndim(self._bounds) == 1:
bounds = np.reshape(self._bounds, (1, len(self._bounds)))
else:
bounds = self._bounds
for j, prec in enumerate(self._num_qubits):
grid = np.linspace(bounds[j, 0], bounds[j, 1], (2 ** prec)) # prepare data grid for dim j
if j == 0:
if len(self._num_qubits) > 1:
self._data_grid = [grid]
else:
self._data_grid = grid
self._grid_elements = grid
elif j == 1:
self._data_grid.append(grid)
temp = []
for g_e in self._grid_elements:
for g in grid:
temp0 = [g_e]
temp0.append(g)
temp.append(temp0)
self._grid_elements = temp
else:
self._data_grid.append(grid)
temp = []
for g_e in self._grid_elements:
for g in grid:
temp0 = deepcopy(g_e)
temp0.append(g)
temp.append(temp0)
self._grid_elements = deepcopy(temp)
self._data_grid = np.array(self._data_grid)
self._shots = None
self._discriminator = None
self._ret = {}
@classmethod
def init_params(cls, params):
"""
Initialize via parameters dictionary and algorithm input instance.
Args:
params (dict): parameters dictionary
Returns:
QuantumGenerator: vqe object
"""
generator_params = params.get(Pluggable.SECTION_KEY_GENERATIVE_NETWORK)
bounds = generator_params.get('bounds')
if bounds is None:
raise AquaError("Data value bounds are required.")
num_qubits = generator_params.get('num_qubits')
if num_qubits is None:
raise AquaError("Numbers of qubits per dimension required.")
init_params = generator_params.get('init_params')
snapshot_dir = generator_params.get('snapshot_dir')
return cls(bounds, num_qubits, generator_circuit=None, init_params=init_params, snapshot_dir=snapshot_dir)
@classmethod
def get_section_key_name(cls):
return Pluggable.SECTION_KEY_GENERATIVE_NETWORK
def set_seed(self, seed):
"""
Set seed.
Args:
seed: int, seed
Returns:
"""
aqua_globals.random_seed = seed
def set_discriminator(self, discriminator):
"""
Set discriminator
Args:
discriminator: Discriminator, Discriminator used to compute the loss function.
"""
self._discriminator = discriminator
return
def construct_circuit(self, quantum_instance, params=None):
"""
Construct generator circuit.
Args:
quantum_instance: QuantumInstance, used for running the generator circuit
params: array or None, parameters which should be used to run the generator, if None use self._params
Returns: QuantumCircuit, constructed quantum circuit
"""
q = QuantumRegister(sum(self._num_qubits), name='q')
qc = QuantumCircuit(q)
if params is None:
self.generator_circuit.build(qc=qc, q=q)
else:
generator_circuit_copy = deepcopy(self.generator_circuit)
generator_circuit_copy.params = params
generator_circuit_copy.build(qc=qc, q=q)
c = ClassicalRegister(q.size, name='c')
qc.add_register(c)
if quantum_instance.is_statevector:
return qc.copy(name='qc')
else:
qc.measure(q, c)
return qc.copy(name='qc')
def get_output(self, quantum_instance, params=None, shots=None):
"""
Get data samples from the generator.
Args:
quantum_instance: QuantumInstance, used to run the generator circuit.
params: array or None, parameters which should be used to run the generator, if None use self._params
shots: int, if not None use a number of shots that is different from the number set in quantum_instance
Returns: array: generated samples, array: sample occurence in percentage
"""
qc = self.construct_circuit(quantum_instance, params)
if shots is not None:
quantum_instance.set_config(shots=shots)
else:
quantum_instance.set_config(shots=self._shots)
result = quantum_instance.execute(qc)
generated_samples = []
if quantum_instance.is_statevector:
result = result.get_statevector(qc)
values = np.multiply(result, np.conj(result))
values = list(values.real)
keys = []
for j in range(len(values)):
keys.append(np.binary_repr(j, int(sum(self._num_qubits))))
else:
result = result.get_counts(qc)
keys = list(result)
values = list(result.values())
values = [float(v) / np.sum(values) for v in values]
generated_samples_weights = values
for i in range(len(keys)):
index = 0
temp = []
for k, p in enumerate(self._num_qubits):
bin_rep = 0
j = 0
while j < p:
bin_rep += int(keys[i][index]) * 2 ** (int(p) - j - 1)
j += 1
index += 1
if len(self._num_qubits) > 1:
temp.append(self._data_grid[k][int(bin_rep)])
else:
temp.append(self._data_grid[int(bin_rep)])
generated_samples.append(temp)
self.generator_circuit._probabilities = generated_samples_weights
return generated_samples, generated_samples_weights
def loss(self, x, weights):
"""
Loss function
Args:
x: array, sample label (equivalent to discriminator output)
weights: array, probability for measuring the sample
Returns: float, loss function
"""
return (-1)*np.dot(weights, np.log(x))
def _get_objective_function(self, quantum_instance, discriminator):
"""
Get objective function
Args:
quantum_instance: QuantumInstance, used to run the quantum circuit.
discriminator: torch.nn.Module, discriminator network to compute the sample labels.
Returns: objective function for quantum generator optimization
"""
def objective_function(params):
"""
Objective function
Args:
params: array, generator parameters
Returns: loss function
"""
generated_data, generated_prob = self.get_output(quantum_instance, params=params, shots=self._shots)
prediction_generated = discriminator.get_label(generated_data).detach().numpy()
return self.loss(prediction_generated, generated_prob)
return objective_function
def train(self, quantum_instance, shots=None):
"""
Perform one training step w.r.t to the generator's parameters
Args:
quantum_instance: QuantumInstance, used to run the generator circuit.
shots: int, Number of shots for hardware or qasm execution.
Returns: dict, generator loss(float) and updated parameters (array).
"""
self._shots = shots
# Force single optimization iteration
self._optimizer._maxiter = 1
self._optimizer._t = 0
objective = self._get_objective_function(quantum_instance, self._discriminator)
self.generator_circuit.params, loss, nfev = \
self._optimizer.optimize(num_vars=len(self.generator_circuit.params), objective_function=objective,
initial_point=self.generator_circuit.params)
self._ret['loss'] = loss[0]
self._ret['params'] = self.generator_circuit.params
return self._ret
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
The Custom Circuit-based Quantum Oracle.
"""
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.aqua import AquaError
from .oracle import Oracle
class CustomCircuitOracle(Oracle):
"""
The helper class for creating oracles from user-supplied quantum circuits
"""
def __init__(self, variable_register=None, output_register=None, ancillary_register=None, circuit=None):
"""
Constructor.
Args:
variable_register (QuantumRegister): The register holding variable qubit(s) for the oracle function
output_register (QuantumRegister): The register holding output qubit(s) for the oracle function
ancillary_register (QuantumRegister): The register holding ancillary qubit(s)
circuit (QuantumCircuit): The quantum circuit corresponding to the intended oracle function
"""
super().__init__()
if variable_register is None:
raise AquaError('Missing QuantumRegister for variables.')
if output_register is None:
raise AquaError('Missing QuantumRegister for output.')
if circuit is None:
raise AquaError('Missing custom QuantumCircuit for the oracle.')
self._variable_register = variable_register
self._output_register = output_register
self._ancillary_register = ancillary_register
self._circuit = circuit
@property
def variable_register(self):
return self._variable_register
@property
def output_register(self):
return self._output_register
@property
def ancillary_register(self):
return self._ancillary_register
@property
def circuit(self):
return self._circuit
def construct_circuit(self):
"""Construct the oracle circuit.
Returns:
A quantum circuit for the oracle.
"""
raise self._circuit
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
The General Logical Expression-based Quantum Oracle.
"""
import logging
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.aqua import AquaError
from qiskit.aqua.circuits import CNF, DNF
from .oracle import Oracle
from ._pyeda_check import _check_pluggable_valid as check_pyeda_valid
logger = logging.getLogger(__name__)
class LogicalExpressionOracle(Oracle):
CONFIGURATION = {
'name': 'LogicalExpressionOracle',
'description': 'Logical Expression Oracle',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'logical_expression_oracle_schema',
'type': 'object',
'properties': {
'expression': {
'type': ['string', 'null'],
'default': None
},
"optimization": {
"type": "string",
"default": "off",
'oneOf': [
{
'enum': [
'off',
'espresso'
]
}
]
},
'mct_mode': {
'type': 'string',
'default': 'basic',
'oneOf': [
{
'enum': [
'basic',
'basic-dirty-ancilla',
'advanced',
'noancilla'
]
}
]
},
},
'additionalProperties': False
}
}
def __init__(self, expression=None, optimization='off', mct_mode='basic'):
"""
Constructor.
Args:
expression (str): The string of the desired logical expression.
It could be either in the DIMACS CNF format,
or a general boolean logical expression, such as 'a ^ b' and 'v[0] & (~v[1] | v[2])'
optimization (str): The mode of optimization to use for minimizing the circuit.
Currently, besides no optimization ('off'), Aqua also supports an 'espresso' mode
<https://en.wikipedia.org/wiki/Espresso_heuristic_logic_minimizer>
mct_mode (str): The mode to use for building Multiple-Control Toffoli.
"""
self.validate(locals())
super().__init__()
self._mct_mode = mct_mode
self._optimization = optimization
from pyeda.boolalg.expr import ast2expr, expr
from pyeda.parsing.dimacs import parse_cnf
if expression is None:
raw_expr = expr(None)
else:
try:
raw_expr = expr(expression)
except:
try:
raw_expr = ast2expr(parse_cnf(expression.strip(), varname='v'))
except:
raise AquaError('Failed to parse the input expression: {}.'.format(expression))
self._expr = raw_expr
self._process_expr()
self.construct_circuit()
@staticmethod
def check_pluggable_valid():
check_pyeda_valid(LogicalExpressionOracle.CONFIGURATION['name'])
@staticmethod
def _normalize_literal_indices(raw_ast, raw_indices):
idx_mapping = {r: i + 1 for r, i in zip(sorted(raw_indices), range(len(raw_indices)))}
if raw_ast[0] == 'and' or raw_ast[0] == 'or':
clauses = []
for c in raw_ast[1:]:
if c[0] == 'lit':
clauses.append(('lit', (idx_mapping[c[1]]) if c[1] > 0 else (-idx_mapping[-c[1]])))
elif (c[0] == 'or' or c[0] == 'and') and (raw_ast[0] != c[0]):
clause = []
for l in c[1:]:
clause.append(('lit', (idx_mapping[l[1]]) if l[1] > 0 else (-idx_mapping[-l[1]])))
clauses.append((c[0], *clause))
else:
raise AquaError('Unrecognized logical expression: {}'.format(raw_ast))
elif raw_ast[0] == 'const' or raw_ast[0] == 'lit':
return raw_ast
else:
raise AquaError('Unrecognized root expression type: {}.'.format(raw_ast[0]))
return (raw_ast[0], *clauses)
def _process_expr(self):
from pyeda.inter import espresso_exprs
from pyeda.boolalg.expr import AndOp, OrOp, Variable
self._num_vars = self._expr.degree
ast = self._expr.to_ast() if self._expr.is_cnf() else self._expr.to_cnf().to_ast()
ast = LogicalExpressionOracle._normalize_literal_indices(ast, self._expr.usupport)
if self._optimization == 'off':
if ast[0] == 'or':
self._nf = DNF(ast, num_vars=self._num_vars)
else:
self._nf = CNF(ast, num_vars=self._num_vars)
else: # self._optimization == 'espresso':
expr_dnf = self._expr.to_dnf()
if expr_dnf.is_zero() or expr_dnf.is_one():
self._nf = CNF(('const', 0 if expr_dnf.is_zero() else 1), num_vars=self._num_vars)
else:
expr_dnf_m = espresso_exprs(expr_dnf)[0]
expr_dnf_m_ast = LogicalExpressionOracle._normalize_literal_indices(
expr_dnf_m.to_ast(), expr_dnf_m.usupport
)
if isinstance(expr_dnf_m, AndOp) or isinstance(expr_dnf_m, Variable):
self._nf = CNF(expr_dnf_m_ast, num_vars=self._num_vars)
elif isinstance(expr_dnf_m, OrOp):
self._nf = DNF(expr_dnf_m_ast, num_vars=self._num_vars)
else:
raise AquaError('Unexpected espresso optimization result expr: {}'.format(expr_dnf_m))
@property
def variable_register(self):
return self._variable_register
@property
def ancillary_register(self):
return self._ancillary_register
@property
def output_register(self):
return self._output_register
def construct_circuit(self):
if self._circuit is None:
if self._nf is not None:
self._circuit = self._nf.construct_circuit(mct_mode=self._mct_mode)
self._variable_register = self._nf.variable_register
self._output_register = self._nf.output_register
self._ancillary_register = self._nf.ancillary_register
else:
self._variable_register = QuantumRegister(self._num_vars, name='v')
self._output_register = QuantumRegister(1, name='o')
self._ancillary_register = None
self._circuit = QuantumCircuit(self._variable_register, self._output_register)
return self._circuit
def evaluate_classically(self, measurement):
from pyeda.boolalg.expr import AndOp, OrOp, Variable
assignment = [(var + 1) * (int(tf) * 2 - 1) for tf, var in zip(measurement[::-1], range(len(measurement)))]
if self._expr.is_zero():
return False, assignment
elif self._expr.is_one():
return True, assignment
else:
prime_implicants = self._expr.complete_sum()
if prime_implicants.is_zero():
sols = []
elif isinstance(prime_implicants, AndOp):
prime_implicants_ast = LogicalExpressionOracle._normalize_literal_indices(
prime_implicants.to_ast(), prime_implicants.usupport
)
sols = [[l[1] for l in prime_implicants_ast[1:]]]
elif isinstance(prime_implicants, OrOp):
expr_complete_sum = self._expr.complete_sum()
complete_sum_ast = LogicalExpressionOracle._normalize_literal_indices(
expr_complete_sum.to_ast(), expr_complete_sum.usupport
)
sols = [[c[1]] if c[0] == 'lit' else [l[1] for l in c[1:]] for c in complete_sum_ast[1:]]
elif isinstance(prime_implicants, Variable):
sols = [[prime_implicants.to_ast()[1]]]
else:
raise AquaError('Unexpected solution: {}'.format(prime_implicants))
for sol in sols:
if set(sol).issubset(assignment):
return True, assignment
else:
return False, assignment
|
https://github.com/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 Truth Table-based Quantum Oracle.
"""
import logging
import operator
import math
import numpy as np
from functools import reduce
from dlx import DLX
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import AquaError
from qiskit.aqua.circuits import ESOP
from qiskit.aqua.components.oracles import Oracle
from qiskit.aqua.utils.arithmetic import is_power_of_2
from ._pyeda_check import _check_pluggable_valid as check_pyeda_valid
logger = logging.getLogger(__name__)
def get_prime_implicants(ones=None, dcs=None):
"""
Compute all prime implicants for a truth table using the Quine-McCluskey Algorithm
Args:
ones (list of int): The list of integers corresponding to '1' outputs
dcs (list of int): The list of integers corresponding to don't-cares
Return:
list of lists of int, representing all prime implicants
"""
def combine_terms(terms, num1s_dict=None):
if num1s_dict is None:
num1s_dict = {}
for num in terms:
num1s = bin(num).count('1')
if num1s not in num1s_dict:
num1s_dict[num1s] = [num]
else:
num1s_dict[num1s].append(num)
new_implicants = {}
new_num1s_dict = {}
prime_dict = {mt: True for mt in sorted(terms)}
cur_num1s, max_num1s = min(num1s_dict.keys()), max(num1s_dict.keys())
while cur_num1s < max_num1s:
if cur_num1s in num1s_dict and (cur_num1s + 1) in num1s_dict:
for cur_term in sorted(num1s_dict[cur_num1s]):
for next_term in sorted(num1s_dict[cur_num1s + 1]):
if isinstance(cur_term, int):
diff_mask = dc_mask = cur_term ^ next_term
implicant_mask = cur_term & next_term
elif isinstance(cur_term, tuple):
if terms[cur_term][1] == terms[next_term][1]:
diff_mask = terms[cur_term][0] ^ terms[next_term][0]
dc_mask = diff_mask | terms[cur_term][1]
implicant_mask = terms[cur_term][0] & terms[next_term][0]
else:
continue
else:
raise AquaError('Unexpected type: {}.'.format(type(cur_term)))
if bin(diff_mask).count('1') == 1:
prime_dict[cur_term] = False
prime_dict[next_term] = False
if isinstance(cur_term, int):
cur_implicant = (cur_term, next_term)
elif isinstance(cur_term, tuple):
cur_implicant = tuple(sorted((*cur_term, *next_term)))
else:
raise AquaError('Unexpected type: {}.'.format(type(cur_term)))
new_implicants[cur_implicant] = (
implicant_mask,
dc_mask
)
num1s = bin(implicant_mask).count('1')
if num1s not in new_num1s_dict:
new_num1s_dict[num1s] = [cur_implicant]
else:
if cur_implicant not in new_num1s_dict[num1s]:
new_num1s_dict[num1s].append(cur_implicant)
cur_num1s += 1
return new_implicants, new_num1s_dict, prime_dict
terms = ones + dcs
cur_num1s_dict = None
prime_implicants = []
while True:
next_implicants, next_num1s_dict, cur_prime_dict = combine_terms(terms, num1s_dict=cur_num1s_dict)
for implicant in cur_prime_dict:
if cur_prime_dict[implicant]:
if isinstance(implicant, int):
if implicant not in dcs:
prime_implicants.append((implicant,))
else:
if not set.issubset(set(implicant), dcs):
prime_implicants.append(implicant)
if next_implicants:
terms = next_implicants
cur_num1s_dict = next_num1s_dict
else:
break
return prime_implicants
def get_exact_covers(cols, rows, num_cols=None):
"""
Use Algorithm X to get all solutions to the exact cover problem
https://en.wikipedia.org/wiki/Knuth%27s_Algorithm_X
Args:
cols (list of int): A list of integers representing the columns to be covered
rows (list of list of int): A list of lists of integers representing the rows
num_cols (int): The total number of columns
Returns:
All exact covers
"""
if num_cols is None:
num_cols = max(cols) + 1
ec = DLX([(c, 0 if c in cols else 1) for c in range(num_cols)])
ec.appendRows([[c] for c in cols])
ec.appendRows(rows)
exact_covers = []
for s in ec.solve():
cover = []
for i in s:
cover.append(ec.getRowList(i))
exact_covers.append(cover)
return exact_covers
class TruthTableOracle(Oracle):
CONFIGURATION = {
'name': 'TruthTableOracle',
'description': 'Truth Table Oracle',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'truth_table_oracle_schema',
'type': 'object',
'properties': {
'bitmaps': {
"type": "array",
"default": [],
"items": {
"type": "string"
}
},
"optimization": {
"type": "string",
"default": "off",
'oneOf': [
{
'enum': [
'off',
'qm-dlx'
]
}
]
},
'mct_mode': {
'type': 'string',
'default': 'basic',
'oneOf': [
{
'enum': [
'basic',
'basic-dirty-ancilla',
'advanced',
'noancilla',
]
}
]
},
},
'additionalProperties': False
}
}
def __init__(self, bitmaps, optimization='off', mct_mode='basic'):
"""
Constructor for Truth Table-based Oracle
Args:
bitmaps (str or [str]): A single binary string or a list of binary strings representing the desired
single- and multi-value truth table.
optimization (str): Optimization mode to use for minimizing the circuit.
Currently, besides no optimization ('off'), Aqua also supports a 'qm-dlx' mode,
which uses the Quine-McCluskey algorithm to compute the prime implicants of the truth table,
and then compute an exact cover to try to reduce the circuit.
mct_mode (str): The mode to use when constructing multiple-control Toffoli.
"""
if isinstance(bitmaps, str):
bitmaps = [bitmaps]
self.validate(locals())
super().__init__()
self._mct_mode = mct_mode
self._optimization = optimization
self._bitmaps = bitmaps
# check that the input bitmaps length is a power of 2
if not is_power_of_2(len(bitmaps[0])):
raise AquaError('Length of any bitmap must be a power of 2.')
for bitmap in bitmaps[1:]:
if not len(bitmap) == len(bitmaps[0]):
raise AquaError('Length of all bitmaps must be the same.')
self._nbits = int(math.log(len(bitmaps[0]), 2))
self._num_outputs = len(bitmaps)
esop_exprs = []
for bitmap in bitmaps:
esop_expr = self._get_esop_ast(bitmap)
esop_exprs.append(esop_expr)
self._esops = [
ESOP(esop_expr, num_vars=self._nbits) for esop_expr in esop_exprs
] if esop_exprs else None
self.construct_circuit()
@staticmethod
def check_pluggable_valid():
check_pyeda_valid(TruthTableOracle.CONFIGURATION['name'])
def _get_esop_ast(self, bitmap):
from pyeda.inter import exprvars, And, Xor
v = exprvars('v', self._nbits)
def binstr_to_vars(binstr):
return [
(~v[x[1] - 1] if x[0] == '0' else v[x[1] - 1])
for x in zip(binstr, reversed(range(1, self._nbits + 1)))
][::-1]
if self._optimization == 'off':
expression = Xor(*[
And(*binstr_to_vars(term)) for term in
[np.binary_repr(idx, self._nbits) for idx, v in enumerate(bitmap) if v == '1']])
else: # self._optimization == 'qm-dlx':
ones = [i for i, v in enumerate(bitmap) if v == '1']
if not ones:
return ('const', 0,)
dcs = [i for i, v in enumerate(bitmap) if v == '*' or v == '-' or v.lower() == 'x']
pis = get_prime_implicants(ones=ones, dcs=dcs)
cover = get_exact_covers(ones, pis)[-1]
clauses = []
for c in cover:
if len(c) == 1:
term = np.binary_repr(c[0], self._nbits)
clause = And(*[
v for i, v in enumerate(binstr_to_vars(term))
])
elif len(c) > 1:
c_or = reduce(operator.or_, c)
c_and = reduce(operator.and_, c)
_ = np.binary_repr(c_and ^ c_or, self._nbits)[::-1]
clause = And(*[
v for i, v in enumerate(binstr_to_vars(np.binary_repr(c_and, self._nbits))) if _[i] == '0'
])
else:
raise AquaError('Unexpected cover term size {}.'.format(len(c)))
if clause:
clauses.append(clause)
expression = Xor(*clauses)
raw_ast = expression.to_ast()
idx_mapping = {
u: v + 1 for u, v in zip(sorted(expression.usupport), [v.indices[0] for v in sorted(expression.support)])
}
if raw_ast[0] == 'and' or raw_ast[0] == 'or' or raw_ast[0] == 'xor':
clauses = []
for c in raw_ast[1:]:
if c[0] == 'lit':
clauses.append(('lit', (idx_mapping[c[1]]) if c[1] > 0 else (-idx_mapping[-c[1]])))
elif (c[0] == 'or' or c[0] == 'and') and (raw_ast[0] != c[0]):
clause = []
for l in c[1:]:
clause.append(('lit', (idx_mapping[l[1]]) if l[1] > 0 else (-idx_mapping[-l[1]])))
clauses.append((c[0], *clause))
else:
raise AquaError('Unrecognized logic expression: {}'.format(raw_ast))
elif raw_ast[0] == 'const' or raw_ast[0] == 'lit':
return raw_ast
else:
raise AquaError('Unrecognized root expression type: {}.'.format(raw_ast[0]))
ast = (raw_ast[0], *clauses)
return ast
@property
def variable_register(self):
return self._variable_register
@property
def ancillary_register(self):
return self._ancillary_register
@property
def output_register(self):
return self._output_register
def construct_circuit(self):
if self._circuit is not None:
return self._circuit
self._circuit = QuantumCircuit()
self._output_register = QuantumRegister(self._num_outputs, name='o')
if self._esops:
for i, e in enumerate(self._esops):
if e is not None:
ci = e.construct_circuit(output_register=self._output_register, output_idx=i)
self._circuit += ci
self._variable_register = self._ancillary_register = None
for qreg in self._circuit.qregs:
if qreg.name == 'v':
self._variable_register = qreg
elif qreg.name == 'a':
self._ancillary_register = qreg
else:
self._variable_register = QuantumRegister(self._nbits, name='v')
self._ancillary_register = None
self._circuit.add_register(self._variable_register, self._output_register)
return self._circuit
def evaluate_classically(self, measurement):
assignment = [(var + 1) * (int(tf) * 2 - 1) for tf, var in zip(measurement[::-1], range(len(measurement)))]
ret = [bitmap[int(measurement, 2)] == '1' for bitmap in self._bitmaps]
if self._num_outputs == 1:
return ret[0], assignment
else:
return ret, assignment
|
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.
"""
This module contains the definition of a base class for quantum fourier transforms.
"""
from abc import abstractmethod
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import Pluggable, AquaError
class QFT(Pluggable):
"""Base class for QFT.
This method should initialize the module and its configuration, and
use an exception if a component of the module is
available.
Args:
configuration (dict): configuration dictionary
"""
@abstractmethod
def __init__(self, *args, **kwargs):
super().__init__()
@classmethod
def init_params(cls, params):
qft_params = params.get(Pluggable.SECTION_KEY_QFT)
kwargs = {k: v for k, v in qft_params.items() if k != 'name'}
return cls(**kwargs)
@abstractmethod
def _build_matrix(self):
raise NotImplementedError
@abstractmethod
def _build_circuit(self, qubits=None, circuit=None, do_swaps=True):
raise NotImplementedError
def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True):
"""Construct the circuit.
Args:
mode (str): 'matrix' or 'circuit'
qubits (QuantumRegister or qubits): register or qubits to build the circuit on.
circuit (QuantumCircuit): circuit for construction.
do_swaps (bool): include the swaps.
Returns:
The matrix or circuit depending on the specified mode.
"""
if mode == 'circuit':
return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps)
elif mode == 'matrix':
return self._build_matrix()
else:
raise AquaError('Unrecognized mode: {}.'.format(mode))
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua.components.reciprocals import Reciprocal
from qiskit.aqua.circuits.gates import mct
class LongDivision(Reciprocal):
"""The Long Division Rotation for Reciprocals.
It finds the reciprocal with long division method and rotates the ancillary
qubit by C/lambda. This is a first order approximation of arcsin(C/lambda).
"""
CONFIGURATION = {
'name': 'LongDivision',
'description': 'reciprocal computation with long division and rotation of the ancilla qubit',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'reciprocal_long_division_schema',
'type': 'object',
'properties': {
'negative_evals': {
'type': 'boolean',
'default': False
},
'scale': {
'type': 'number',
'default': 0,
},
'precision': {
'type': ['integer', 'null'],
'default': None,
},
'evo_time': {
'type': ['number', 'null'],
'default': None
},
'lambda_min': {
'type': ['number', 'null'],
'default': None
}
},
'additionalProperties': False
},
}
def __init__(
self,
scale=0,
precision=None,
negative_evals=False,
evo_time=None,
lambda_min=None
):
"""Constructor.
Args:
scale (float, optional): the scale of rotation angle, corresponds to HHL constant C
precision (int, optional): number of qubits that defines the precision of long division
negative_evals (bool, optional): indicate if negative eigenvalues need to be handled
evo_time (float, optional): the evolution time
lambda_min (float, optional): the smallest expected eigenvalue
"""
self.validate(locals())
super().__init__()
self._negative_evals = negative_evals
self._scale = scale
self._precision = precision
self._evo_time = evo_time
self._lambda_min = lambda_min
self._circuit = None
self._ev = None
self._rec = None
self._anc = None
self._reg_size = 0
self._neg_offset = 0
self._n = 0
def sv_to_resvec(self, statevector, num_q):
half = int(len(statevector) / 2)
sv_good = statevector[half:]
vec = np.array([])
for i in range(2 ** num_q):
vec = np.append(vec, sum(x for x in sv_good[i::2 ** num_q]))
return vec
def _ld_circuit(self):
def subtract(a, b, b0, c, z,r, rj, n):
qc = QuantumCircuit(a, b0, b, c, z, r)
qc2 = QuantumCircuit(a, b0, b ,c, z,r)
def subtract_in(qc, a, b, b0, c , z, r, n):
"""subtraction realized with ripple carry adder"""
def maj(p, a, b, c):
p.cx(c, b)
p.cx(c, a)
p.ccx(a, b, c)
def uma(p, a, b, c):
p.ccx(a, b, c)
p.cx(c, a)
p.cx(a, b)
for i in range(n):
qc.x(a[i])
maj(qc, c[0], a[0], b[n-2])
for i in range(n-2):
maj(qc, b[n-2-i+self._neg_offset], a[i+1], b[n-3-i+self._neg_offset])
maj(qc, b[self._neg_offset+0], a[n-1], b0[0])
qc.cx(a[n-1], z[0])
uma(qc, b[self._neg_offset+0], a[n-1], b0[0])
for i in range(2, n):
uma(qc, b[self._neg_offset+i-1], a[n-i], b[self._neg_offset+i-2])
uma(qc, c[0], a[0], b[n-2+self._neg_offset])
for i in range(n):
qc.x(a[i])
qc.x(z[0])
def u_maj(p, a, b, c, r):
p.ccx(c, r, b)
p.ccx(c, r, a)
p.mct([r, a, b], c, None, mode='noancilla')
def u_uma(p, a, b, c, r):
p.mct([r, a, b], c, None, mode='noancilla')
p.ccx(c,r, a)
p.ccx(a, r, b)
def unsubtract(qc2, a, b, b0, c, z, r, n):
"""controlled inverse subtraction to uncompute the registers(when
the result of the subtraction is negative)"""
for i in range(n):
qc2.cx(r, a[i])
u_maj(qc2, c[0], a[0], b[n-2],r)
for i in range(n-2):
u_maj(qc2, b[n-2-i+self._neg_offset], a[i+1], b[n-3-i+self._neg_offset], r)
u_maj(qc2, b[self._neg_offset+0], a[n-1], b0[0], r)
qc2.ccx(a[n-1],r, z[0])
u_uma(qc2, b[self._neg_offset+0], a[n-1], b0[0], r)
for i in range(2, n):
u_uma(qc2, b[self._neg_offset+i-1], a[n-i], b[self._neg_offset+i-2], r)
u_uma(qc2, c[0], a[0], b[n-2+self._neg_offset], r)
for i in range(n):
qc2.cx(r, a[i])
un_qc = qc2.mirror()
un_qc.cx(r, z[0])
return un_qc
# assembling circuit for controlled subtraction
subtract_in(qc, a, b, b0, c, z, r[rj], n)
qc.x(a[n-1])
qc.cx(a[n-1], r[rj])
qc.x(a[n-1])
qc.x(r[rj])
qc += unsubtract(qc2, a, b, b0, c, z, r[rj], n)
qc.x(r[rj])
return qc
def shift_to_one(qc, b, anc, n):
"""controlled bit shifting for the initial alignment of the most
significant bits """
for i in range(n-2): # set all the anc1 qubits to 1
qc.x(anc[i])
for j2 in range(n-2): # if msb is 1, change ancilla j2 to 0
qc.cx(b[0+self._neg_offset], anc[j2])
for i in np.arange(0,n-2):
i = int(i) # which activates shifting with the 2 Toffoli gates
qc.ccx(anc[j2], b[i+1+self._neg_offset], b[i+self._neg_offset])
qc.ccx(anc[j2], b[i+self._neg_offset], b[i+1+self._neg_offset])
for i in range(n-2): # negate all the ancilla
qc.x(anc[i])
def shift_one_left(qc, b, n):
for i in np.arange(n-1,0, -1):
i = int(i)
qc.cx(b[i-1], b[i])
qc.cx(b[i], b[i-1])
def shift_one_leftc(qc, b, ctrl, n):
for i in np.arange(n-2,0, -1):
i = int(i)
qc.ccx(ctrl, b[i-1], b[i])
qc.ccx(ctrl, b[i], b[i-1])
return qc
def shift_one_rightc(qc, b, ctrl, n):
for i in np.arange(0, n-1):
i = int(i)
qc.ccx(ctrl, b[n-2-i+self._neg_offset], b[n-1-i+self._neg_offset])
qc.ccx(ctrl, b[n-1-i+self._neg_offset], b[n-2-i+self._neg_offset])
# executing long division:
self._circuit.x(self._a[self._n-2])
shift_to_one(self._circuit, self._ev, self._anc1, self._n) #initial alignment of most significant bits
for rj in range(self._precision): # iterated subtraction and shifting
self._circuit += subtract(self._a, self._ev, self._b0, self._c,
self._z, self._rec, rj, self._n)
shift_one_left(self._circuit, self._a, self._n)
for ish in range(self._n-2): # unshifting due to initial alignment
shift_one_leftc(self._circuit, self._rec, self._anc1[ish],
self._precision + self._num_ancillae)
self._circuit.x(self._anc1[ish])
shift_one_rightc(self._circuit, self._ev, self._anc1[ish], self._num_ancillae)
self._circuit.x(self._anc1[ish])
def _rotation(self):
qc = self._circuit
rec_reg = self._rec
ancilla = self._anc
if self._negative_evals:
for i in range(0, self._precision + self._num_ancillae):
qc.cu3(self._scale*2**(-i), 0, 0, rec_reg[i], ancilla)
qc.cu3(2*np.pi, 0, 0, self._ev[0], ancilla) #correcting the sign
else:
for i in range(0, self._precision + self._num_ancillae):
qc.cu3(self._scale*2**(-i), 0, 0, rec_reg[i], ancilla)
self._circuit = qc
self._rec = rec_reg
self._anc = ancilla
def construct_circuit(self, mode, inreg):
"""Construct the Long Division Rotation circuit.
Args:
mode (str): consctruction mode, 'matrix' not supported
inreg (QuantumRegister): input register, typically output register of Eigenvalues
Returns:
QuantumCircuit containing the Long Division Rotation circuit.
"""
if mode == 'matrix':
raise NotImplementedError('The matrix mode is not supported.')
self._ev = inreg
if self._scale == 0:
self._scale = 2**-len(inreg)
if self._negative_evals:
self._neg_offset = 1
self._num_ancillae = len(self._ev) - self._neg_offset
if self._num_ancillae < 3:
self._num_ancillae = 3
if self._negative_evals == True:
if self._num_ancillae < 4:
self._num_ancillae = 4
self._n = self._num_ancillae + 1
if self._precision is None:
self._precision = self._num_ancillae
self._a = QuantumRegister(self._n, 'one') #register storing 1
self._b0 = QuantumRegister(1, 'b0') #extension of b - required by subtraction
self._anc1 = QuantumRegister(self._num_ancillae-1, 'algn_anc') # ancilla for the initial shifting
self._z = QuantumRegister(1, 'z') #subtraction overflow
self._c = QuantumRegister(1, 'c') #carry
self._rec = QuantumRegister(self._precision + self._num_ancillae, 'res') #reciprocal result
self._anc = QuantumRegister(1, 'anc')
qc = QuantumCircuit(self._a, self._b0, self._ev, self._anc1, self._c,
self._z, self._rec, self._anc)
self._circuit = qc
self._ld_circuit()
self._rotation()
return self._circuit
|
https://github.com/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.
"""Controlled rotation for the HHL algorithm based on partial table lookup"""
import itertools
import logging
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua.components.reciprocals import Reciprocal
from qiskit.aqua.circuits.gates import mct
logger = logging.getLogger(__name__)
class LookupRotation(Reciprocal):
"""The Lookup Rotation for Reciprocals.
A calculation of reciprocals of eigenvalues is performed and controlled
rotation of ancillary qubit via a lookup method. It uses a partial table
lookup of rotation angles to rotate an ancillary qubit by arcsin(C/lambda).
Please refer to the HHL documentation for an explanation of this method.
"""
CONFIGURATION = {
'name': 'Lookup',
'description': 'approximate inversion for HHL based on table lookup',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'reciprocal_lookup_schema',
'type': 'object',
'properties': {
'pat_length': {
'type': ['integer', 'null'],
'default': None,
},
'subpat_length': {
'type': ['integer', 'null'],
'default': None,
},
'negative_evals': {
'type': 'boolean',
'default': False
},
'scale': {
'type': 'number',
'default': 0,
'minimum': 0,
'maximum': 1,
},
'evo_time': {
'type': ['number', 'null'],
'default': None
},
'lambda_min': {
'type': ['number', 'null'],
'default': None
}
},
'additionalProperties': False
},
}
def __init__(
self,
pat_length=None,
subpat_length=None,
scale=0,
negative_evals=False,
evo_time=None,
lambda_min=None
):
"""Constructor.
Args:
pat_length (int, optional): the number of qubits used for binning pattern
subpat_length (int, optional): the number of qubits used for binning sub-pattern
scale (float, optional): the scale of rotation angle, corresponds to HHL constant C
negative_evals (bool, optional): indicate if negative eigenvalues need to be handled
evo_time (float, optional): the evolution time
lambda_min (float, optional): the smallest expected eigenvalue
"""
self.validate(locals())
super().__init__()
self._pat_length = pat_length
self._subpat_length = subpat_length
self._negative_evals = negative_evals
self._scale = scale
self._evo_time = evo_time
self._lambda_min = lambda_min
self._anc = None
self._workq = None
self._msq = None
self._ev = None
self._circuit = None
self._reg_size = 0
def sv_to_resvec(self, statevector, num_q):
half = int(len(statevector) / 2)
vec = statevector[half:half + 2 ** num_q]
return vec
def _classic_approx(k, n, m, negative_evals=False):
"""Approximate arcsin(1/x) for controlled-rotation.
This method calculates the binning of arcsin(1/x) function using k
bits fixed point numbers and n bit accuracy.
Args:
k (int): register length
n (int): num bits following most-significant qubit taken into account
m (int): length of sub string of n-qubit pattern
negative_evals (bool): flag for using first qubit as sign bit
Returns:
Dictionary containing values of approximated and binned values.
"""
def bin_to_num(binary):
"""Convert to numeric"""
num = np.sum([2 ** -(n + 1) for n, i in enumerate(reversed(
binary)) if i == '1'])
return num
def get_est_lamb(pattern, fo, n, k):
"""Estimate the bin mid point and return the float value"""
if fo - n > 0:
remainder = sum([2 ** -i for i in range(k - (fo - n - 1),
k + 1)])
return bin_to_num(pattern)+remainder/2
return bin_to_num(pattern)
from collections import OrderedDict
output = OrderedDict()
fo = None
for fo in range(k - 1, n - 1, -1):
# skip first bit if negative ev are used
if negative_evals and fo == k - 1:
continue
# init bit string
vec = ['0'] * k
# set most significant bit
vec[fo] = '1'
# iterate over all 2^m combinations = sub string in n-bit pattern
for pattern_ in itertools.product('10', repeat=m):
app_pattern_array = []
lambda_array = []
fo_array = []
# iterate over all 2^(n-m) combinations
for appendpat in itertools.product('10', repeat=n - m):
# combine both generated patterns
pattern = pattern_ + appendpat
vec[fo - n:fo] = pattern
# estimate bin mid point
e_l = get_est_lamb(vec.copy(), fo, n, k)
lambda_array.append(e_l)
fo_array.append(fo)
app_pattern_array.append(list(reversed(appendpat)))
# rewrite first-one to correct index in QuantumRegister
fo_pos = k-fo-1
if fo_pos in list(output.keys()):
prev_res = output[fo_pos]
else:
prev_res = []
output.update(
{fo_pos: prev_res + [(list(reversed(pattern_)),
app_pattern_array, lambda_array)]})
# last iterations, only last n bits != 0
last_fo = fo
vec = ['0'] * k
for pattern_ in itertools.product('10', repeat=m):
app_pattern_array = []
lambda_array = []
fo_array = []
for appendpat in itertools.product('10', repeat=n - m):
pattern = list(pattern_ + appendpat).copy()
if '1' not in pattern and (not negative_evals):
continue
elif '1' not in pattern and negative_evals:
e_l = 0.5
else:
vec[last_fo - n:last_fo] = list(pattern)
e_l = get_est_lamb(vec.copy(), last_fo, n, k)
lambda_array.append(e_l)
fo_array.append(last_fo - 1)
app_pattern_array.append(list(reversed(appendpat)))
fo_pos = k-last_fo
if fo_pos in list(output.keys()):
prev_res = output[fo_pos]
else:
prev_res = []
output.update({fo_pos: prev_res + [(list(reversed(pattern_)),
app_pattern_array,
lambda_array)]})
return output
def _set_msq(self, msq, ev_reg, fo_pos, last_iteration=False):
"""Adds multi-controlled NOT gate to entangle |msq> qubit
with states having the correct first-one qubit
Args:
msq (QuantumRegister): most-significant qubit, this is a garbage qubit
ev_reg (QuantumRegister): register storing eigenvalues
fo_pos (int): position of first-one bit
last_iteration (bool): switch which is set for numbers where only the
last n bits is different from 0 in the binary string
"""
qc = self._circuit
ev = [ev_reg[i] for i in range(len(ev_reg))]
# last_iteration = no MSQ set, only the n-bit long pattern
if last_iteration:
if fo_pos == 1:
qc.x(ev[0])
qc.cx(ev[0], msq[0])
qc.x(ev[0])
elif fo_pos == 2:
qc.x(ev[0])
qc.x(ev[1])
qc.ccx(ev[0], ev[1], msq[0])
qc.x(ev[1])
qc.x(ev[0])
elif fo_pos > 2:
for idx in range(fo_pos):
qc.x(ev[idx])
qc.mct(ev[:fo_pos], msq[0], None, mode='noancilla')
for idx in range(fo_pos):
qc.x(ev[idx])
else:
qc.x(msq[0])
elif fo_pos == 0:
qc.cx(ev[0], msq)
elif fo_pos == 1:
qc.x(ev[0])
qc.ccx(ev[0], ev[1], msq[0])
qc.x(ev[0])
elif fo_pos > 1:
for idx in range(fo_pos):
qc.x(ev[idx])
qc.mct(ev[:fo_pos + 1], msq[0], None, mode='noancilla')
for idx in range(fo_pos):
qc.x(ev[idx])
else:
raise RuntimeError("first-one register index < 0")
def _set_bit_pattern(self, pattern, tgt, offset):
"""Add multi-controlled NOT gate to circuit that has negated/normal
controls according to the pattern specified
Args:
pattern (list): List of strings giving a bit string that negates
controls if '0'
tgt (QuantumRegister): target qubit
offset (int): start index for the control qubits
"""
qc = self._circuit
for c, i in enumerate(pattern):
if i == '0':
qc.x(self._ev[int(c + offset)])
if len(pattern) > 2:
temp_reg = [self._ev[i]
for i in range(offset, offset+len(pattern))]
qc.mct(temp_reg, tgt, None, mode='noancilla')
elif len(pattern) == 2:
qc.ccx(self._ev[offset], self._ev[offset + 1], tgt)
elif len(pattern) == 1:
qc.cx(self._ev[offset], tgt)
for c, i in enumerate(pattern):
if i == '0':
qc.x(self._ev[int(c + offset)])
def construct_circuit(self, mode, inreg):
"""Construct the Lookup Rotation circuit.
Args:
mode (str): consctruction mode, 'matrix' not supported
inreg (QuantumRegister): input register, typically output register of Eigenvalues
Returns:
QuantumCircuit containing the Lookup Rotation circuit.
"""
# initialize circuit
if mode == 'matrix':
raise NotImplementedError('The matrix mode is not supported.')
if self._lambda_min:
self._scale = self._lambda_min/2/np.pi*self._evo_time
if self._scale == 0:
self._scale = 2**-len(inreg)
self._ev = inreg
self._workq = QuantumRegister(1, 'work')
self._msq = QuantumRegister(1, 'msq')
self._anc = QuantumRegister(1, 'anc')
qc = QuantumCircuit(self._ev, self._workq, self._msq, self._anc)
self._circuit = qc
self._reg_size = len(inreg)
if self._pat_length is None:
if self._reg_size <= 6:
self._pat_length = self._reg_size - \
(2 if self._negative_evals else 1)
else:
self._pat_length = 5
if self._reg_size <= self._pat_length:
self._pat_length = self._reg_size - \
(2 if self._negative_evals else 1)
if self._subpat_length is None:
self._subpat_length = int(np.ceil(self._pat_length/2))
m = self._subpat_length
n = self._pat_length
k = self._reg_size
neg_evals = self._negative_evals
# get classically precomputed eigenvalue binning
approx_dict = LookupRotation._classic_approx(k, n, m,
negative_evals=neg_evals)
fo = None
old_fo = None
# for negative EV, we pass a pseudo register ev[1:] ign. sign bit
ev = [self._ev[i] for i in range(len(self._ev))]
for _, fo in enumerate(list(approx_dict.keys())):
# read m-bit and (n-m) bit patterns for current first-one and
# correct Lambdas
pattern_map = approx_dict[fo]
# set most-significant-qbit register and uncompute previous
if self._negative_evals:
if old_fo != fo:
if old_fo is not None:
self._set_msq(self._msq, ev[1:], int(old_fo - 1))
old_fo = fo
if fo + n == k:
self._set_msq(self._msq, ev[1:], int(fo - 1),
last_iteration=True)
else:
self._set_msq(self._msq, ev[1:], int(fo - 1),
last_iteration=False)
else:
if old_fo != fo:
if old_fo is not None:
self._set_msq(self._msq, self._ev, int(old_fo))
old_fo = fo
if fo + n == k:
self._set_msq(self._msq, self._ev, int(fo),
last_iteration=True)
else:
self._set_msq(self._msq, self._ev, int(fo),
last_iteration=False)
# offset = start idx for ncx gate setting and unsetting m-bit
# long bitstring
offset_mpat = fo + (n - m) if fo < k - n else fo + n - m - 1
for mainpat, subpat, lambda_ar in pattern_map:
# set m-bit pattern in register workq
self._set_bit_pattern(mainpat, self._workq[0], offset_mpat + 1)
# iterate of all 2**(n-m) combinations for fixed m-bit
for subpattern, lambda_ in zip(subpat, lambda_ar):
# calculate rotation angle
theta = 2*np.arcsin(min(1, self._scale / lambda_))
# offset for ncx gate checking subpattern
offset = fo + 1 if fo < k - n else fo
# rotation is happening here
# 1. rotate by half angle
qc.mcu3(theta / 2, 0, 0, [self._workq[0], self._msq[0]],
self._anc[0])
# 2. mct gate to reverse rotation direction
self._set_bit_pattern(subpattern, self._anc[0], offset)
# 3. rotate by inverse of halfangle to uncompute / complete
qc.mcu3(-theta / 2, 0, 0, [self._workq[0], self._msq[0]],
self._anc[0])
# 4. mct gate to uncompute first mct gate
self._set_bit_pattern(subpattern, self._anc[0], offset)
# uncompute m-bit pattern
self._set_bit_pattern(mainpat, self._workq[0], offset_mpat + 1)
last_fo = fo
# uncompute msq register
if self._negative_evals:
self._set_msq(self._msq, ev[1:], int(last_fo - 1),
last_iteration=True)
else:
self._set_msq(self._msq, self._ev, int(last_fo),
last_iteration=True)
# rotate by pi to fix sign for negative evals
if self._negative_evals:
qc.cu3(2*np.pi, 0, 0, self._ev[0], self._anc[0])
self._circuit = qc
return self._circuit
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.aqua import Pluggable, get_pluggable_class, PluggableType
from .multivariate_distribution import MultivariateDistribution
class MultivariateVariationalDistribution(MultivariateDistribution):
"""
The Multivariate Variational Distribution.
"""
CONFIGURATION = {
'name': 'MultivariateVariationalDistribution',
'description': 'Multivariate Variational Distribution',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'MultivariateVariationalDistribution_schema',
'type': 'object',
'properties': {
'num_qubits': {
'type': 'array',
"items": {
"type": "number"
}
},
'params': {
'type': 'array',
"items": {
"type": "number"
}
},
'low': {
'type': ['array', 'null'],
"items": {
"type": "number"
},
'default': None
},
'high': {
'type': ['array', 'null'],
"items": {
"type": "number"
},
'default': None
},
},
'additionalProperties': False
},
'depends': [
{
'pluggable_type': 'variational_form',
'default': {
'name': 'RY'
}
}
],
}
def __init__(self, num_qubits, var_form, params, low=None, high=None):
if low is None:
low = np.zeros(len(num_qubits))
if high is None:
high = np.ones(len(num_qubits))
self._num_qubits = num_qubits
self._var_form = var_form
self.params = params
probabilities = np.zeros(2 ** sum(num_qubits))
super().__init__(num_qubits, probabilities, low, high)
self._var_form = var_form
self.params = params
@classmethod
def init_params(cls, params):
"""
Initialize via parameters dictionary.
Args:
params: parameters dictionary
Returns:
An object instance of this class
"""
multi_var_params_params = params.get(Pluggable.SECTION_KEY_UNIVARIATE_DISTRIBUTION)
num_qubits = multi_var_params_params.get('num_qubits')
params = multi_var_params_params.get('params')
low = multi_var_params_params.get('low')
high = multi_var_params_params.get('high')
var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM)
var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM,
var_form_params['name']).init_params(params)
return cls(num_qubits, var_form, params, low, high)
def build(self, qc, q, q_ancillas=None):
circuit_var_form = self._var_form.construct_circuit(self.params, q)
qc.extend(circuit_var_form)
def set_probabilities(self, quantum_instance):
"""
Set Probabilities
Args:
quantum_instance: QuantumInstance
Returns:
"""
q_ = QuantumRegister(self._num_qubits, name='q')
qc_ = QuantumCircuit(q_)
circuit_var_form = self._var_form.construct_circuit(self.params, q_)
qc_ += circuit_var_form
if quantum_instance.is_statevector:
pass
else:
c_ = ClassicalRegister(self._num_qubits, name='c')
qc_.add_register(c_)
qc_.measure(q_, c_)
result = quantum_instance.execute(qc_)
if quantum_instance.is_statevector:
result = result.get_statevector(qc_)
values = np.multiply(result, np.conj(result))
values = list(values.real)
else:
result = result.get_counts(qc_)
keys = list(result)
values = list(result.values())
values = [float(v) / np.sum(values) for v in values]
values = [x for _, x in sorted(zip(keys, values))]
probabilities = values
self._probabilities = np.array(probabilities)
return
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import ClassicalRegister
from qiskit.aqua import Pluggable, get_pluggable_class, PluggableType
from .univariate_distribution import UnivariateDistribution
class UnivariateVariationalDistribution(UnivariateDistribution):
"""
The Univariate Variational Distribution.
"""
CONFIGURATION = {
'name': 'UnivariateVariationalDistribution',
'description': 'Univariate Variational Distribution',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'UnivariateVariationalDistribution_schema',
'type': 'object',
'properties': {
'num_qubits': {
'type': 'number',
},
'params': {
'type': 'array',
"items": {
"type": "number"
}
},
'low': {
'type': 'number',
'default': 0
},
'high': {
'type': 'number',
'default': 1
},
},
'additionalProperties': False
},
'depends': [
{
'pluggable_type': 'variational_form',
'default': {
'name': 'RY'
}
}
]
}
def __init__(self, num_qubits, var_form, params, low=0, high=1):
self._num_qubits = num_qubits
self._var_form = var_form
self.params = params
probabilities = list(np.zeros(2**num_qubits))
super().__init__(num_qubits, probabilities, low, high)
@classmethod
def init_params(cls, params):
"""
Initialize via parameters dictionary.
Args:
params: parameters dictionary
Returns:
An object instance of this class
"""
uni_var_params_params = params.get(Pluggable.SECTION_KEY_UNIVARIATE_DISTRIBUTION)
num_qubits = uni_var_params_params.get('num_qubits')
params = uni_var_params_params.get('params')
low = uni_var_params_params.get('low')
high = uni_var_params_params.get('high')
var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM)
var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM, var_form_params['name']).init_params(params)
return cls(num_qubits, var_form, params, low, high)
def build(self, qc, q, q_ancillas=None):
circuit_var_form = self._var_form.construct_circuit(self.params, q)
qc.extend(circuit_var_form)
def set_probabilities(self, quantum_instance):
"""
Set Probabilities
Args:
quantum_instance: QuantumInstance
Returns:
"""
qc_ = self._var_form.construct_circuit(self.params)
# q_ = QuantumRegister(self._num_qubits)
# qc_ = QuantumCircuit(q_)
# self.build(qc_, None)
if quantum_instance.is_statevector:
pass
else:
c_ = ClassicalRegister(self._num_qubits, name='c')
qc_.add_register(c_)
qc_.measure(qc_.qregs[0], c_)
result = quantum_instance.execute(qc_)
if quantum_instance.is_statevector:
result = result.get_statevector(qc_)
values = np.multiply(result, np.conj(result))
values = list(values.real)
else:
result = result.get_counts(qc_)
keys = list(result)
values = list(result.values())
values = [float(v) / np.sum(values) for v in values]
values = [x for _, x in sorted(zip(keys, values))]
probabilities = values
self._probabilities = np.array(probabilities)
return
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua.components.variational_forms import VariationalForm
class RY(VariationalForm):
"""Layers of Y rotations followed by entangling gates."""
CONFIGURATION = {
'name': 'RY',
'description': 'RY Variational Form',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'ry_schema',
'type': 'object',
'properties': {
'depth': {
'type': 'integer',
'default': 3,
'minimum': 0
},
'entanglement': {
'type': 'string',
'default': 'full',
'oneOf': [
{'enum': ['full', 'linear']}
]
},
'entangler_map': {
'type': ['array', 'null'],
'default': None
},
'entanglement_gate': {
'type': 'string',
'default': 'cz',
'oneOf': [
{'enum': ['cz', 'cx']}
]
},
'skip_unentangled_qubits': {
'type': 'boolean',
'default': False
}
},
'additionalProperties': False
},
'depends': [
{
'pluggable_type': 'initial_state',
'default': {
'name': 'ZERO',
}
},
],
}
def __init__(self, num_qubits, depth=3, entangler_map=None,
entanglement='full', initial_state=None,
entanglement_gate='cz', skip_unentangled_qubits=False):
"""Constructor.
Args:
num_qubits (int) : number of qubits
depth (int) : number of rotation layers
entangler_map (list[list]): describe the connectivity of qubits, each list describes
[source, target], or None for full entanglement.
Note that the order is the list is the order of
applying the two-qubit gate.
entanglement (str): 'full' or 'linear'
initial_state (InitialState): an initial state object
entanglement_gate (str): cz or cx
skip_unentangled_qubits (bool): skip the qubits not in the entangler_map
"""
self.validate(locals())
super().__init__()
self._num_qubits = num_qubits
self._depth = depth
if entangler_map is None:
self._entangler_map = VariationalForm.get_entangler_map(entanglement, num_qubits)
else:
self._entangler_map = VariationalForm.validate_entangler_map(entangler_map, num_qubits)
# determine the entangled qubits
all_qubits = []
for src, targ in self._entangler_map:
all_qubits.extend([src, targ])
self._entangled_qubits = sorted(list(set(all_qubits)))
self._initial_state = initial_state
self._entanglement_gate = entanglement_gate
self._skip_unentangled_qubits = skip_unentangled_qubits
# for the first layer
self._num_parameters = len(self._entangled_qubits) if self._skip_unentangled_qubits \
else self._num_qubits
# for repeated block
self._num_parameters += len(self._entangled_qubits) * depth
self._bounds = [(-np.pi, np.pi)] * self._num_parameters
def construct_circuit(self, parameters, q=None):
"""
Construct the variational form, given its parameters.
Args:
parameters (numpy.ndarray): circuit parameters.
q (QuantumRegister): Quantum Register for the circuit.
Returns:
QuantumCircuit: a quantum circuit with given `parameters`
Raises:
ValueError: the number of parameters is incorrect.
"""
if len(parameters) != self._num_parameters:
raise ValueError('The number of parameters has to be {}'.format(self._num_parameters))
if q is None:
q = QuantumRegister(self._num_qubits, name='q')
if self._initial_state is not None:
circuit = self._initial_state.construct_circuit('circuit', q)
else:
circuit = QuantumCircuit(q)
param_idx = 0
for qubit in range(self._num_qubits):
if not self._skip_unentangled_qubits or qubit in self._entangled_qubits:
circuit.u3(parameters[param_idx], 0.0, 0.0, q[qubit]) # ry
param_idx += 1
for block in range(self._depth):
circuit.barrier(q)
for src, targ in self._entangler_map:
if self._entanglement_gate == 'cz':
circuit.u2(0.0, np.pi, q[targ]) # h
circuit.cx(q[src], q[targ])
circuit.u2(0.0, np.pi, q[targ]) # h
else:
circuit.cx(q[src], q[targ])
circuit.barrier(q)
for qubit in self._entangled_qubits:
circuit.u3(parameters[param_idx], 0.0, 0.0, q[qubit]) # ry
param_idx += 1
circuit.barrier(q)
return circuit
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua.components.variational_forms import VariationalForm
class RYRZ(VariationalForm):
"""Layers of Y+Z rotations followed by entangling gates."""
CONFIGURATION = {
'name': 'RYRZ',
'description': 'RYRZ Variational Form',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'ryrz_schema',
'type': 'object',
'properties': {
'depth': {
'type': 'integer',
'default': 3,
'minimum': 1
},
'entanglement': {
'type': 'string',
'default': 'full',
'oneOf': [
{'enum': ['full', 'linear']}
]
},
'entangler_map': {
'type': ['array', 'null'],
'default': None
},
'entanglement_gate': {
'type': 'string',
'default': 'cz',
'oneOf': [
{'enum': ['cz', 'cx']}
]
},
'skip_unentangled_qubits': {
'type': 'boolean',
'default': False
}
},
'additionalProperties': False
},
'depends': [
{
'pluggable_type': 'initial_state',
'default': {
'name': 'ZERO',
}
},
],
}
def __init__(self, num_qubits, depth=3, entangler_map=None,
entanglement='full', initial_state=None,
entanglement_gate='cz', skip_unentangled_qubits=False):
"""Constructor.
Args:
num_qubits (int) : number of qubits
depth (int) : number of rotation layers
entangler_map (list[list]): describe the connectivity of qubits, each list describes
[source, target], or None for full entanglement.
Note that the order is the list is the order of
applying the two-qubit gate.
entanglement (str): 'full' or 'linear'
initial_state (InitialState): an initial state object
entanglement_gate (str): cz or cx
skip_unentangled_qubits (bool): skip the qubits not in the entangler_map
"""
self.validate(locals())
super().__init__()
self._num_qubits = num_qubits
self._depth = depth
if entangler_map is None:
self._entangler_map = VariationalForm.get_entangler_map(entanglement, num_qubits)
else:
self._entangler_map = VariationalForm.validate_entangler_map(entangler_map, num_qubits)
# determine the entangled qubits
all_qubits = []
for src, targ in self._entangler_map:
all_qubits.extend([src, targ])
self._entangled_qubits = sorted(list(set(all_qubits)))
self._initial_state = initial_state
self._entanglement_gate = entanglement_gate
self._skip_unentangled_qubits = skip_unentangled_qubits
# for the first layer
self._num_parameters = len(self._entangled_qubits) * 2 if self._skip_unentangled_qubits \
else self._num_qubits * 2
# for repeated block
self._num_parameters += len(self._entangled_qubits) * depth * 2
self._bounds = [(-np.pi, np.pi)] * self._num_parameters
def construct_circuit(self, parameters, q=None):
"""
Construct the variational form, given its parameters.
Args:
parameters (numpy.ndarray): circuit parameters
q (QuantumRegister): Quantum Register for the circuit.
Returns:
QuantumCircuit: a quantum circuit with given `parameters`
Raises:
ValueError: the number of parameters is incorrect.
"""
if len(parameters) != self._num_parameters:
raise ValueError('The number of parameters has to be {}'.format(self._num_parameters))
if q is None:
q = QuantumRegister(self._num_qubits, name='q')
if self._initial_state is not None:
circuit = self._initial_state.construct_circuit('circuit', q)
else:
circuit = QuantumCircuit(q)
param_idx = 0
for qubit in range(self._num_qubits):
if not self._skip_unentangled_qubits or qubit in self._entangled_qubits:
circuit.u3(parameters[param_idx], 0.0, 0.0, q[qubit]) # ry
circuit.u1(parameters[param_idx + 1], q[qubit]) # rz
param_idx += 2
for block in range(self._depth):
circuit.barrier(q)
for src, targ in self._entangler_map:
if self._entanglement_gate == 'cz':
circuit.u2(0.0, np.pi, q[targ]) # h
circuit.cx(q[src], q[targ])
circuit.u2(0.0, np.pi, q[targ]) # h
else:
circuit.cx(q[src], q[targ])
circuit.barrier(q)
for qubit in self._entangled_qubits:
circuit.u3(parameters[param_idx], 0.0, 0.0, q[qubit]) # ry
circuit.u1(parameters[param_idx + 1], q[qubit]) # rz
param_idx += 2
circuit.barrier(q)
return circuit
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua.components.variational_forms import VariationalForm
class SwapRZ(VariationalForm):
"""Layers of Swap+Z rotations followed by entangling gates."""
CONFIGURATION = {
'name': 'SWAPRZ',
'description': 'SWAPRZ Variational Form',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'swaprz_schema',
'type': 'object',
'properties': {
'depth': {
'type': 'integer',
'default': 3,
'minimum': 1
},
'entanglement': {
'type': 'string',
'default': 'full',
'oneOf': [
{'enum': ['full', 'linear']}
]
},
'entangler_map': {
'type': ['array', 'null'],
'default': None
},
'skip_unentangled_qubits': {
'type': 'boolean',
'default': False
}
},
'additionalProperties': False
},
'depends': [
{
'pluggable_type': 'initial_state',
'default': {
'name': 'ZERO',
}
},
],
}
def __init__(self, num_qubits, depth=3, entangler_map=None,
entanglement='full', initial_state=None, skip_unentangled_qubits=False):
"""Constructor.
Args:
num_qubits (int) : number of qubits
depth (int) : number of rotation layers
entangler_map (list[list]): describe the connectivity of qubits, each list describes
[source, target], or None for full entanglement.
Note that the order is the list is the order of
applying the two-qubit gate.
entanglement (str): 'full' or 'linear'
initial_state (InitialState): an initial state object
skip_unentangled_qubits (bool): skip the qubits not in the entangler_map
"""
self.validate(locals())
super().__init__()
self._num_qubits = num_qubits
self._depth = depth
if entangler_map is None:
self._entangler_map = VariationalForm.get_entangler_map(entanglement, num_qubits)
else:
self._entangler_map = VariationalForm.validate_entangler_map(entangler_map, num_qubits)
# determine the entangled qubits
all_qubits = []
for src, targ in self._entangler_map:
all_qubits.extend([src, targ])
self._entangled_qubits = sorted(list(set(all_qubits)))
self._initial_state = initial_state
self._skip_unentangled_qubits = skip_unentangled_qubits
# for the first layer
self._num_parameters = len(self._entangled_qubits) if self._skip_unentangled_qubits \
else self._num_qubits
# for repeated block
self._num_parameters += (len(self._entangled_qubits) + len(self._entangler_map)) * depth
self._bounds = [(-np.pi, np.pi)] * self._num_parameters
def construct_circuit(self, parameters, q=None):
"""
Construct the variational form, given its parameters.
Args:
parameters (numpy.ndarray): circuit parameters
q (QuantumRegister): Quantum Register for the circuit.
Returns:
QuantumCircuit: a quantum circuit with given `parameters`
Raises:
ValueError: the number of parameters is incorrect.
"""
if len(parameters) != self._num_parameters:
raise ValueError('The number of parameters has to be {}'.format(self._num_parameters))
if q is None:
q = QuantumRegister(self._num_qubits, name='q')
if self._initial_state is not None:
circuit = self._initial_state.construct_circuit('circuit', q)
else:
circuit = QuantumCircuit(q)
param_idx = 0
for qubit in range(self._num_qubits):
if not self._skip_unentangled_qubits or qubit in self._entangled_qubits:
circuit.u1(parameters[param_idx], q[qubit]) # rz
param_idx += 1
for block in range(self._depth):
circuit.barrier(q)
for src, targ in self._entangler_map:
# XX
circuit.u2(0, np.pi, q[src])
circuit.u2(0, np.pi, q[targ])
circuit.cx(q[src], q[targ])
circuit.u1(parameters[param_idx], q[targ])
circuit.cx(q[src], q[targ])
circuit.u2(0, np.pi, q[src])
circuit.u2(0, np.pi, q[targ])
# YY
circuit.u3(np.pi / 2, -np.pi / 2, np.pi / 2, q[src])
circuit.u3(np.pi / 2, -np.pi / 2, np.pi / 2, q[targ])
circuit.cx(q[src], q[targ])
circuit.u1(parameters[param_idx], q[targ])
circuit.cx(q[src], q[targ])
circuit.u3(-np.pi / 2, -np.pi / 2, np.pi / 2, q[src])
circuit.u3(-np.pi / 2, -np.pi / 2, np.pi / 2, q[targ])
param_idx += 1
circuit.barrier(q)
for qubit in self._entangled_qubits:
circuit.u1(parameters[param_idx], q[qubit]) # rz
param_idx += 1
circuit.barrier(q)
return circuit
|
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.
from collections import OrderedDict
import importlib
import logging
from qiskit.providers import BaseBackend
from qiskit.providers.basicaer import BasicAerProvider
from qiskit.aqua import Preferences
logger = logging.getLogger(__name__)
try:
from qiskit.providers.ibmq import IBMQProvider
HAS_IBMQ = True
except Exception as e:
HAS_IBMQ = False
logger.debug("IBMQProvider not loaded: '{}'".format(str(e)))
try:
from qiskit.providers.aer import AerProvider
HAS_AER = True
except Exception as e:
HAS_AER = False
logger.debug("AerProvider not loaded: '{}'".format(str(e)))
_UNSUPPORTED_BACKENDS = ['unitary_simulator', 'clifford_simulator']
def has_ibmq():
return HAS_IBMQ
def has_aer():
return HAS_AER
def is_aer_provider(backend):
"""Detect whether or not backend is from Aer provider.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is AerProvider
"""
if has_aer():
return isinstance(backend.provider(), AerProvider)
else:
return False
def is_basicaer_provider(backend):
"""Detect whether or not backend is from BasicAer provider.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is BasicAer
"""
return isinstance(backend.provider(), BasicAerProvider)
def is_ibmq_provider(backend):
"""Detect whether or not backend is from IBMQ provider.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is IBMQ
"""
if has_ibmq():
return isinstance(backend.provider(), IBMQProvider)
else:
return False
def is_aer_statevector_backend(backend):
"""
Return True if backend object is statevector and from Aer provider.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is statevector
"""
return is_statevector_backend(backend) and is_aer_provider(backend)
def is_statevector_backend(backend):
"""
Return True if backend object is statevector.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is statevector
"""
return backend.name().startswith('statevector') if backend is not None else False
def is_simulator_backend(backend):
"""
Return True if backend is a simulator.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is a simulator
"""
return backend.configuration().simulator
def is_local_backend(backend):
"""
Return True if backend is a local backend.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is a local backend
"""
return backend.configuration().local
def get_aer_backend(backend_name):
providers = ['qiskit.Aer', 'qiskit.BasicAer']
for provider in providers:
try:
return get_backend_from_provider(provider, backend_name)
except:
pass
raise ImportError("Backend '{}' not found in providers {}".format(backend_name, providers))
def get_backends_from_provider(provider_name):
"""
Backends access method.
Args:
provider_name (str): Fullname of provider instance global property or class
Returns:
list: backend names
Raises:
ImportError: Invalid provider name or failed to find provider
"""
provider_object = _load_provider(provider_name)
if has_ibmq() and isinstance(provider_object, IBMQProvider):
preferences = Preferences()
url = preferences.get_url()
token = preferences.get_token()
kwargs = {}
if url is not None and url != '':
kwargs['url'] = url
if token is not None and token != '':
kwargs['token'] = token
return [x.name() for x in provider_object.backends(**kwargs) if x.name() not in _UNSUPPORTED_BACKENDS]
try:
# try as variable containing provider instance
return [x.name() for x in provider_object.backends() if x.name() not in _UNSUPPORTED_BACKENDS]
except:
# try as provider class then
try:
provider_instance = provider_object()
return [x.name() for x in provider_instance.backends() if x.name() not in _UNSUPPORTED_BACKENDS]
except:
pass
raise ImportError("'Backends not found for provider '{}'".format(provider_object))
def get_backend_from_provider(provider_name, backend_name):
"""
Backend access method.
Args:
provider_name (str): Fullname of provider instance global property or class
backend_name (str): name of backend for this provider
Returns:
BaseBackend: backend object
Raises:
ImportError: Invalid provider name or failed to find provider
"""
backend = None
provider_object = _load_provider(provider_name)
if has_ibmq() and isinstance(provider_object, IBMQProvider):
preferences = Preferences()
url = preferences.get_url()
token = preferences.get_token()
kwargs = {}
if url is not None and url != '':
kwargs['url'] = url
if token is not None and token != '':
kwargs['token'] = token
backend = provider_object.get_backend(backend_name, **kwargs)
else:
try:
# try as variable containing provider instance
backend = provider_object.get_backend(backend_name)
except:
# try as provider class then
try:
provider_instance = provider_object()
backend = provider_instance.get_backend(backend_name)
except:
pass
if backend is None:
raise ImportError("'{} not found in provider '{}'".format(backend_name, provider_object))
return backend
def get_local_providers():
providers = OrderedDict()
for provider in ['qiskit.Aer', 'qiskit.BasicAer']:
try:
providers[provider] = get_backends_from_provider(provider)
except Exception as e:
logger.debug("'{}' not loaded: '{}'.".format(provider, str(e)))
return providers
def register_ibmq_and_get_known_providers():
"""Gets known local providers and registers IBMQ."""
providers = get_local_providers()
if has_ibmq():
providers.update(_get_ibmq_provider())
return providers
def get_provider_from_backend(backend):
"""
Attempts to find a known provider that provides this backend.
Args:
backend (BaseBackend or str): backend object or backend name
Returns:
str: provider name
Raises:
ImportError: Failed to find provider
"""
known_providers = {
'BasicAerProvider': 'qiskit.BasicAer',
'AerProvider': 'qiskit.Aer',
'IBMQProvider': 'qiskit.IBMQ',
}
if isinstance(backend, BaseBackend):
provider = backend.provider()
if provider is None:
raise ImportError("Backend object '{}' has no provider".format(backend.name()))
return known_providers.get(provider.__class__.__name__, provider.__class__.__qualname__)
elif not isinstance(backend, str):
raise ImportError("Invalid Backend '{}'".format(backend))
for provider in known_providers.values():
try:
if get_backend_from_provider(provider, backend) is not None:
return provider
except:
pass
raise ImportError("Backend '{}' not found in providers {}".format(backend, list(known_providers.values())))
def _load_provider(provider_name):
index = provider_name.rfind(".")
if index < 1:
raise ImportError("Invalid provider name '{}'".format(provider_name))
modulename = provider_name[0:index]
objectname = provider_name[index + 1:len(provider_name)]
module = importlib.import_module(modulename)
if module is None:
raise ImportError("Failed to import provider '{}'".format(provider_name))
provider_object = getattr(module, objectname)
if provider_object is None:
raise ImportError("Failed to import provider '{}'".format(provider_name))
if has_ibmq() and isinstance(provider_object, IBMQProvider):
# enable IBMQ account
preferences = Preferences()
enable_ibmq_account(preferences.get_url(), preferences.get_token(), preferences.get_proxies({}))
return provider_object
def enable_ibmq_account(url, token, proxies):
"""
Enable IBMQ account, if not alreay enabled.
"""
if not has_ibmq():
return
try:
url = url or ''
token = token or ''
proxies = proxies or {}
if url != '' and token != '':
from qiskit import IBMQ
from qiskit.providers.ibmq.credentials import Credentials
credentials = Credentials(token, url, proxies=proxies)
unique_id = credentials.unique_id()
if unique_id in IBMQ._accounts:
# disable first any existent previous account with same unique_id and different properties
enabled_credentials = IBMQ._accounts[unique_id].credentials
if enabled_credentials.url != url or enabled_credentials.token != token or enabled_credentials.proxies != proxies:
del IBMQ._accounts[unique_id]
if unique_id not in IBMQ._accounts:
IBMQ.enable_account(token, url=url, proxies=proxies)
logger.info("Enabled IBMQ account. Url:'{}' Token:'{}' "
"Proxies:'{}'".format(url, token, proxies))
except Exception as e:
logger.warning("Failed to enable IBMQ account. Url:'{}' Token:'{}' "
"Proxies:'{}' :{}".format(url, token, proxies, str(e)))
def disable_ibmq_account(url, token, proxies):
"""Disable IBMQ account."""
if not has_ibmq():
return
try:
url = url or ''
token = token or ''
proxies = proxies or {}
if url != '' and token != '':
from qiskit import IBMQ
from qiskit.providers.ibmq.credentials import Credentials
credentials = Credentials(token, url, proxies=proxies)
unique_id = credentials.unique_id()
if unique_id in IBMQ._accounts:
del IBMQ._accounts[unique_id]
logger.info("Disabled IBMQ account. Url:'{}' "
"Token:'{}' Proxies:'{}'".format(url, token, proxies))
else:
logger.info("IBMQ account is not active. Not disabled. "
"Url:'{}' Token:'{}' Proxies:'{}'".format(url, token, proxies))
except Exception as e:
logger.warning("Failed to disable IBMQ account. Url:'{}' "
"Token:'{}' Proxies:'{}' :{}".format(url, token, proxies, str(e)))
def _get_ibmq_provider():
"""Registers IBMQ and return it."""
providers = OrderedDict()
try:
providers['qiskit.IBMQ'] = get_backends_from_provider('qiskit.IBMQ')
except Exception as e:
logger.warning("Failed to access IBMQ: {}".format(str(e)))
return providers
|
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.
""" A utility for caching and reparameterizing circuits, rather than compiling from scratch
with each iteration. Note that if the circuit is transpiled aggressively such that rotation parameters
cannot be easily mapped from the uncompiled to compiled circuit, caching will fail gracefully to
standard compilation. This will be noted by multiple cache misses in the DEBUG log. It is generally safer to
skip the transpiler (aqua_dict['backend']['skip_transpiler'] = True) when using caching.
Caching is controlled via the aqua_dict['problem']['circuit_caching'] parameter. Setting skip_qobj_deepcopy = True
reuses the same qobj object over and over to avoid deepcopying. It is controlled via the aqua_dict['problem'][
'skip_qobj_deepcopy'] parameter.
You may also specify a filename into which to store the cache as a pickle file, for circuits which
are expensive to compile even the first time. The filename is set in aqua_dict['problem']['circuit_cache_file'].
If a filename is present, the system will attempt to load from the file.
In the event of an error, the system will fail gracefully, compile from scratch, and cache the new
compiled qobj and mapping in the file location in pickled form. It will fail over 5 times before deciding
that caching should be disabled."""
import numpy as np
import copy
import pickle
import logging
from qiskit import QuantumRegister
from qiskit.circuit import CompositeGate
from qiskit.assembler.run_config import RunConfig
from qiskit.qobj import Qobj, QasmQobjConfig
from qiskit.aqua.aqua_error import AquaError
logger = logging.getLogger(__name__)
class CircuitCache:
def __init__(self,
skip_qobj_deepcopy=False,
cache_file=None,
allowed_misses=3):
self.skip_qobj_deepcopy = skip_qobj_deepcopy
self.cache_file = cache_file
self.misses = 0
self.qobjs = []
self.mappings = []
self.cache_transpiled_circuits = False
self.try_reusing_qobjs = True
self.allowed_misses = allowed_misses
try:
self.try_loading_cache_from_file()
except(EOFError, FileNotFoundError) as e:
logger.warning("Error loading cache from file {0}: {1}".format(self.cache_file, repr(e)))
def cache_circuit(self, qobj, circuits, chunk):
"""
A method for caching compiled qobjs by storing the compiled qobj
and constructing a mapping array from the uncompiled operations in the circuit
to the instructions in the qobj. Note that the "qobjs" list in the cache dict is a
list of the cached chunks, each element of which contains a single qobj with as
many experiments as is allowed by the execution backend. E.g. if the backend allows
300 experiments per job and the user wants to run 500 circuits,
len(circuit_cache['qobjs']) == 2,
len(circuit_cache['qobjs'][0].experiments) == 300, and
len(circuit_cache['qobjs'][1].experiments) == 200.
This feature is only applied if 'circuit_caching' is True in the 'problem' Aqua
dictionary section.
Args:
qobj (Qobj): A compiled qobj to be saved
circuits (list): The original uncompiled QuantumCircuits
chunk (int): If a larger list of circuits was broken into chunks by run_algorithm for separate runs,
which chunk number `circuits` represents
"""
self.qobjs.insert(chunk, copy.deepcopy(qobj))
self.mappings.insert(chunk, [{} for i in range(len(circuits))])
for circ_num, input_circuit in enumerate(circuits):
qreg_sizes = [reg.size for reg in input_circuit.qregs if isinstance(reg, QuantumRegister)]
qreg_indeces = {reg.name: sum(qreg_sizes[0:i]) for i, reg in enumerate(input_circuit.qregs)}
op_graph = {}
# Unroll circuit in case of composite gates
raw_gates = []
for gate in input_circuit.data:
if isinstance(gate, CompositeGate): raw_gates += gate.instruction_list()
else: raw_gates += [gate]
for i, (uncompiled_gate, regs, _) in enumerate(raw_gates):
if not hasattr(uncompiled_gate, 'params') or len(uncompiled_gate.params) < 1: continue
if uncompiled_gate.name == 'snapshot': continue
qubits = [qubit+qreg_indeces[reg.name] for reg, qubit in regs if isinstance(reg, QuantumRegister)]
gate_type = uncompiled_gate.name
type_and_qubits = gate_type + qubits.__str__()
op_graph[type_and_qubits] = \
op_graph.get(type_and_qubits, []) + [i]
mapping = {}
for compiled_gate_index, compiled_gate in enumerate(qobj.experiments[circ_num].instructions):
if not hasattr(compiled_gate, 'params') or len(compiled_gate.params) < 1: continue
if compiled_gate.name == 'snapshot': continue
type_and_qubits = compiled_gate.name + compiled_gate.qubits.__str__()
if len(op_graph[type_and_qubits]) > 0:
uncompiled_gate_index = op_graph[type_and_qubits].pop(0)
(uncompiled_gate, regs, _) = raw_gates[uncompiled_gate_index]
qubits = [qubit + qreg_indeces[reg.name] for reg, qubit in regs if isinstance(reg, QuantumRegister)]
if (compiled_gate.name == uncompiled_gate.name) and (compiled_gate.qubits.__str__() ==
qubits.__str__()):
mapping[compiled_gate_index] = uncompiled_gate_index
else: raise AquaError("Circuit shape does not match qobj, found extra {} instruction in qobj".format(
type_and_qubits))
self.mappings[chunk][circ_num] = mapping
for type_and_qubits, ops in op_graph.items():
if len(ops) > 0:
raise AquaError("Circuit shape does not match qobj, found extra {} in circuit".format(type_and_qubits))
if self.cache_file is not None and len(self.cache_file) > 0:
with open(self.cache_file, 'wb') as cache_handler:
qobj_dicts = [qob.to_dict() for qob in self.qobjs]
pickle.dump({'qobjs': qobj_dicts,
'mappings': self.mappings,
'transpile': self.cache_transpiled_circuits},
cache_handler,
protocol=pickle.HIGHEST_PROTOCOL)
logger.debug("Circuit cache saved to file: {}".format(self.cache_file))
def try_loading_cache_from_file(self):
if len(self.qobjs) == 0 and self.cache_file is not None and len(self.cache_file) > 0:
with open(self.cache_file, "rb") as cache_handler:
try:
cache = pickle.load(cache_handler, encoding="ASCII")
except (EOFError) as e:
logger.debug("No cache found in file: {}".format(self.cache_file))
return
self.qobjs = [Qobj.from_dict(qob) for qob in cache['qobjs']]
self.mappings = cache['mappings']
self.cache_transpiled_circuits = cache['transpile']
logger.debug("Circuit cache loaded from file: {}".format(self.cache_file))
# Note that this function overwrites the previous cached qobj for speed
def load_qobj_from_cache(self, circuits, chunk, run_config=None):
self.try_loading_cache_from_file()
if self.try_reusing_qobjs and self.qobjs is not None and len(self.qobjs) > 0 and len(self.qobjs) <= chunk:
self.mappings.insert(chunk, self.mappings[0])
self.qobjs.insert(chunk, copy.deepcopy(self.qobjs[0]))
for circ_num, input_circuit in enumerate(circuits):
# If there are too few experiments in the cache, try reusing the first experiment.
# Only do this for the first chunk. Subsequent chunks should rely on these copies
# through the deepcopy above.
if self.try_reusing_qobjs and chunk == 0 and circ_num > 0 and len(self.qobjs[chunk].experiments) <= \
circ_num:
self.qobjs[0].experiments.insert(circ_num, copy.deepcopy(self.qobjs[0].experiments[0]))
self.mappings[0].insert(circ_num, self.mappings[0][0])
# Unroll circuit in case of composite gates
raw_gates = []
for gate in input_circuit.data:
if isinstance(gate, CompositeGate): raw_gates += gate.instruction_list()
else: raw_gates += [gate]
self.qobjs[chunk].experiments[circ_num].header.name = input_circuit.name
for gate_num, compiled_gate in enumerate(self.qobjs[chunk].experiments[circ_num].instructions):
if not hasattr(compiled_gate, 'params') or len(compiled_gate.params) < 1: continue
if compiled_gate.name == 'snapshot': continue
cache_index = self.mappings[chunk][circ_num][gate_num]
(uncompiled_gate, regs, _) = raw_gates[cache_index]
# Need the 'getattr' wrapper because measure has no 'params' field and breaks this.
if not len(getattr(compiled_gate, 'params', [])) == len(getattr(uncompiled_gate, 'params', [])) or \
not compiled_gate.name == uncompiled_gate.name:
raise AquaError('Gate mismatch at gate {0} ({1}, {2} params) of circuit against gate {3} ({4}, '
'{5} params) of cached qobj'.format(cache_index,
uncompiled_gate.name,
len(uncompiled_gate.params),
gate_num,
compiled_gate.name,
len(compiled_gate.params)))
compiled_gate.params = np.array(uncompiled_gate.params, dtype=float).tolist()
exec_qobj = copy.copy(self.qobjs[chunk])
if self.skip_qobj_deepcopy: exec_qobj.experiments = self.qobjs[chunk].experiments[0:len(circuits)]
else: exec_qobj.experiments = copy.deepcopy(self.qobjs[chunk].experiments[0:len(circuits)])
if run_config is None:
run_config = RunConfig(shots=1024, max_credits=10, memory=False)
exec_qobj.config = QasmQobjConfig(**run_config.to_dict())
exec_qobj.config.memory_slots = max(experiment.config.memory_slots for experiment in exec_qobj.experiments)
exec_qobj.config.n_qubits = max(experiment.config.n_qubits for experiment in exec_qobj.experiments)
return exec_qobj
def clear_cache(self):
self.qobjs = []
self.mappings = []
self.try_reusing_qobjs = True
|
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.
"""
Abstract CircuitFactory to build a circuit, along with inverse, controlled
and power combinations of the circuit.
"""
from abc import ABC, abstractmethod
from qiskit import QuantumCircuit
from qiskit.aqua.utils.controlled_circuit import get_controlled_circuit
class CircuitFactory(ABC):
""" Base class for CircuitFactories """
def __init__(self, num_target_qubits):
self._num_target_qubits = num_target_qubits
pass
@property
def num_target_qubits(self):
""" Returns the number of target qubits """
return self._num_target_qubits
def required_ancillas(self):
return 0
def required_ancillas_controlled(self):
return self.required_ancillas()
def get_num_qubits(self):
return self._num_target_qubits + self.required_ancillas()
def get_num_qubits_controlled(self):
return self._num_target_qubits + self.required_ancillas_controlled()
@abstractmethod
def build(self, qc, q, q_ancillas=None):
""" Adds corresponding sub-circuit to given circuit
Args:
qc : quantum circuit
q : list of qubits (has to be same length as self._num_qubits)
q_ancillas : list of ancilla qubits (or None if none needed)
params : parameters for circuit
"""
raise NotImplementedError()
def build_inverse(self, qc, q, q_ancillas=None):
""" Adds inverse of corresponding sub-circuit to given circuit
Args:
qc : quantum circuit
q : list of qubits (has to be same length as self._num_qubits)
q_ancillas : list of ancilla qubits (or None if none needed)
params : parameters for circuit
"""
qc_ = QuantumCircuit(*qc.qregs)
self.build(qc_, q, q_ancillas)
qc.extend(qc_.inverse())
def build_controlled(self, qc, q, q_control, q_ancillas=None, use_basis_gates=True):
""" Adds corresponding controlled sub-circuit to given circuit
Args:
qc : quantum circuit
q : list of qubits (has to be same length as self._num_qubits)
q_control : control qubit
q_ancillas : list of ancilla qubits (or None if none needed)
use_basis_gates: use basis gates for expansion of controlled circuit
"""
uncontrolled_circuit = QuantumCircuit(*qc.qregs)
self.build(uncontrolled_circuit, q, q_ancillas)
controlled_circuit = get_controlled_circuit(uncontrolled_circuit, q_control, use_basis_gates=use_basis_gates)
qc.extend(controlled_circuit)
def build_controlled_inverse(self, qc, q, q_control, q_ancillas=None, use_basis_gates=True):
""" Adds controlled inverse of corresponding sub-circuit to given circuit
Args:
qc : quantum circuit
q : list of qubits (has to be same length as self._num_qubits)
q_control : control qubit
q_ancillas : list of ancilla qubits (or None if none needed)
use_basis_gates: use basis gates for expansion of controlled circuit
"""
qc_ = QuantumCircuit(*qc.qregs)
self.build_controlled(qc_, q, q_control, q_ancillas, use_basis_gates)
qc.extend(qc_.inverse())
def build_power(self, qc, q, power, q_ancillas=None):
""" Adds power of corresponding circuit.
May be overridden if a more efficient implementation is possible """
for _ in range(power):
self.build(qc, q, q_ancillas)
def build_inverse_power(self, qc, q, power, q_ancillas=None):
""" Adds inverse power of corresponding circuit.
May be overridden if a more efficient implementation is possible """
for _ in range(power):
self.build_inverse(qc, q, q_ancillas)
def build_controlled_power(self, qc, q, q_control, power, q_ancillas=None, use_basis_gates=True):
""" Adds controlled power of corresponding circuit.
May be overridden if a more efficient implementation is possible """
for _ in range(power):
self.build_controlled(qc, q, q_control, q_ancillas, use_basis_gates)
def build_controlled_inverse_power(self, qc, q, q_control, power, q_ancillas=None, use_basis_gates=True):
""" Adds controlled, inverse, power of corresponding circuit.
May be overridden if a more efficient implementation is possible """
for _ in range(power):
self.build_controlled_inverse(qc, q, q_control, q_ancillas, use_basis_gates)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import compiler, BasicAer, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
def convert_to_basis_gates(circuit):
# unroll the circuit using the basis u1, u2, u3, cx, and id gates
unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id'])
pm = PassManager(passes=[unroller])
qc = compiler.transpile(circuit, BasicAer.get_backend('qasm_simulator'), pass_manager=pm)
return qc
def is_qubit(qb):
# check if the input is a qubit, which is in the form (QuantumRegister, int)
return isinstance(qb, tuple) and isinstance(qb[0], QuantumRegister) and isinstance(qb[1], int)
def is_qubit_list(qbs):
# check if the input is a list of qubits
for qb in qbs:
if not is_qubit(qb):
return False
return True
def summarize_circuits(circuits):
"""Summarize circuits based on QuantumCircuit, and four metrics are summarized.
Number of qubits and classical bits, and number of operations and depth of circuits.
The average statistic is provided if multiple circuits are inputed.
Args:
circuits (QuantumCircuit or [QuantumCircuit]): the to-be-summarized circuits
"""
if not isinstance(circuits, list):
circuits = [circuits]
ret = ""
ret += "Submitting {} circuits.\n".format(len(circuits))
ret += "============================================================================\n"
stats = np.zeros(4)
for i, circuit in enumerate(circuits):
dag = circuit_to_dag(circuit)
depth = dag.depth()
width = dag.width()
size = dag.size()
classical_bits = dag.num_cbits()
op_counts = dag.count_ops()
stats[0] += width
stats[1] += classical_bits
stats[2] += size
stats[3] += depth
ret = ''.join([ret, "{}-th circuit: {} qubits, {} classical bits and {} operations with depth {}\n op_counts: {}\n".format(
i, width, classical_bits, size, depth, op_counts)])
if len(circuits) > 1:
stats /= len(circuits)
ret = ''.join([ret, "Average: {:.2f} qubits, {:.2f} classical bits and {:.2f} operations with depth {:.2f}\n".format(
stats[0], stats[1], stats[2], stats[3])])
ret += "============================================================================\n"
return ret
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import QuantumCircuit, compiler
from qiskit.transpiler.passes import Unroller
from qiskit.transpiler import PassManager
from qiskit import BasicAer
def apply_cu1(circuit, lam, c, t, use_basis_gates=True):
if use_basis_gates:
circuit.u1(lam / 2, c)
circuit.cx(c, t)
circuit.u1(-lam / 2, t)
circuit.cx(c, t)
circuit.u1(lam / 2, t)
else:
circuit.cu1(lam, c, t)
def apply_cu3(circuit, theta, phi, lam, c, t, use_basis_gates=True):
if use_basis_gates:
circuit.u1((lam - phi) / 2, t)
circuit.cx(c, t)
circuit.u3(-theta / 2, 0, -(phi + lam) / 2, t)
circuit.cx(c, t)
circuit.u3(theta / 2, phi, 0, t)
else:
circuit.cu3(theta, phi, lam, c, t)
# the u3 gate below is added to account for qiskit terra's cu3
# TODO: here or only in if=True clause?
if not np.isclose(float(phi + lam), 0.0):
circuit.u3(0, 0, (phi + lam) / 2, c)
def apply_ccx(circuit, a, b, c, use_basis_gates=True):
if use_basis_gates:
circuit.u2(0, np.pi, c)
circuit.cx(b, c)
circuit.u1(-np.pi / 4, c)
circuit.cx(a, c)
circuit.u1(np.pi / 4, c)
circuit.cx(b, c)
circuit.u1(-np.pi / 4, c)
circuit.cx(a, c)
circuit.u1(np.pi / 4, b)
circuit.u1(np.pi / 4, c)
circuit.u2(0, np.pi, c)
circuit.cx(a, b)
circuit.u1(np.pi / 4, a)
circuit.u1(-np.pi / 4, b)
circuit.cx(a, b)
else:
circuit.ccx(a, b, c)
def get_controlled_circuit(circuit, ctl_qubit, tgt_circuit=None, use_basis_gates=True):
"""
Construct the controlled version of a given circuit.
Args:
circuit (QuantumCircuit) : the base circuit
ctl_qubit (indexed QuantumRegister) : the control qubit to use
tgt_circuit (QuantumCircuit) : the target controlled circuit to be modified in-place
use_basis_gates (bool) : boolean flag to indicate whether or not only basis gates should be used
Return:
a QuantumCircuit object with the base circuit being controlled by ctl_qubit
"""
if tgt_circuit is not None:
qc = tgt_circuit
else:
qc = QuantumCircuit()
# get all the qubits and clbits
qregs = circuit.qregs
qubits = []
for qreg in qregs:
if not qc.has_register(qreg):
qc.add_register(qreg)
qubits.extend(qreg)
cregs = circuit.cregs
clbits = []
for creg in cregs:
if not qc.has_register(creg):
qc.add_register(creg)
clbits.extend(creg)
# get all operations from compiled circuit
unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id'])
pm = PassManager(passes=[unroller])
ops = compiler.transpile(
circuit,
BasicAer.get_backend('qasm_simulator'),
pass_manager=pm
).data
# process all basis gates to add control
if not qc.has_register(ctl_qubit[0]):
qc.add(ctl_qubit[0])
for op in ops:
if op[0].name == 'id':
apply_cu3(qc, 0, 0, 0, ctl_qubit, op[1][0], use_basis_gates=use_basis_gates)
elif op[0].name == 'u1':
apply_cu1(qc, *op[0].params, ctl_qubit, op[1][0], use_basis_gates=use_basis_gates)
elif op[0].name == 'u2':
apply_cu3(qc, np.pi / 2, *op[0].params, ctl_qubit, op[1][0], use_basis_gates=use_basis_gates)
elif op[0].name == 'u3':
apply_cu3(qc, *op[0].params, ctl_qubit, op[1][0], use_basis_gates=use_basis_gates)
elif op[0].name == 'cx':
apply_ccx(qc, ctl_qubit, *op[1], use_basis_gates=use_basis_gates)
elif op[0].name == 'measure':
qc.measure(op[1], op[2])
else:
raise RuntimeError('Unexpected operation {}.'.format(op['name']))
return qc
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import sys
import logging
import time
import copy
import os
import uuid
import numpy as np
from qiskit import compiler
from qiskit.assembler import assemble_circuits
from qiskit.providers import BaseBackend, JobStatus, JobError
from qiskit.providers.basicaer import BasicAerJob
from qiskit.qobj import QobjHeader
from qiskit.aqua.aqua_error import AquaError
from qiskit.aqua.utils import summarize_circuits
from qiskit.aqua.utils.backend_utils import (is_aer_provider,
is_basicaer_provider,
is_ibmq_provider,
is_simulator_backend,
is_local_backend)
MAX_CIRCUITS_PER_JOB = os.environ.get('QISKIT_AQUA_MAX_CIRCUITS_PER_JOB', None)
logger = logging.getLogger(__name__)
def find_regs_by_name(circuit, name, qreg=True):
"""Find the registers in the circuits.
Args:
circuit (QuantumCircuit): the quantum circuit.
name (str): name of register
qreg (bool): quantum or classical register
Returns:
QuantumRegister or ClassicalRegister or None: if not found, return None.
"""
found_reg = None
regs = circuit.qregs if qreg else circuit.cregs
for reg in regs:
if reg.name == name:
found_reg = reg
break
return found_reg
def _avoid_empty_circuits(circuits):
new_circuits = []
for qc in circuits:
if len(qc) == 0:
tmp_q = None
for q in qc.qregs:
tmp_q = q
break
if tmp_q is None:
raise NameError("A QASM without any quantum register is invalid.")
qc.iden(tmp_q[0])
new_circuits.append(qc)
return new_circuits
def _combine_result_objects(results):
"""Tempoary helper function.
TODO:
This function would be removed after Terra supports job with infinite circuits.
"""
if len(results) == 1:
return results[0]
new_result = copy.deepcopy(results[0])
for idx in range(1, len(results)):
new_result.results.extend(results[idx].results)
return new_result
def _maybe_add_aer_expectation_instruction(qobj, options):
if 'expectation' in options:
from qiskit.providers.aer.utils.qobj_utils import snapshot_instr, append_instr, get_instr_pos
# add others, how to derive the correct used number of qubits?
# the compiled qobj could be wrong if coupling map is used.
params = options['expectation']['params']
num_qubits = options['expectation']['num_qubits']
for idx in range(len(qobj.experiments)):
# if mulitple params are provided, we assume that each circuit is corresponding one param
# otherwise, params are used for all circuits.
param_idx = idx if len(params) > 1 else 0
snapshot_pos = get_instr_pos(qobj, idx, 'snapshot')
if len(snapshot_pos) == 0: # does not append the instruction yet.
new_ins = snapshot_instr('expectation_value_pauli', 'test',
list(range(num_qubits)), params=params[param_idx])
qobj = append_instr(qobj, idx, new_ins)
else:
for i in snapshot_pos: # update all expectation_value_snapshot
if qobj.experiments[idx].instructions[i].type == 'expectation_value_pauli':
qobj.experiments[idx].instructions[i].params = params[param_idx]
return qobj
def _compile_wrapper(circuits, backend, backend_config, compile_config, run_config):
transpiled_circuits = compiler.transpile(circuits, backend, **backend_config, **compile_config)
if not isinstance(transpiled_circuits, list):
transpiled_circuits = [transpiled_circuits]
qobj = assemble_circuits(transpiled_circuits, qobj_id=str(uuid.uuid4()), qobj_header=QobjHeader(),
run_config=run_config)
return qobj, transpiled_circuits
def compile_circuits(circuits, backend, backend_config=None, compile_config=None, run_config=None,
show_circuit_summary=False, circuit_cache=None, **kwargs):
"""
An execution wrapper with Qiskit-Terra, with job auto recover capability.
The autorecovery feature is only applied for non-simulator backend.
This wraper will try to get the result no matter how long it costs.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute
backend (BaseBackend): backend instance
backend_config (dict, optional): configuration for backend
compile_config (dict, optional): configuration for compilation
run_config (RunConfig, optional): configuration for running a circuit
show_circuit_summary (bool, optional): showing the summary of submitted circuits.
circuit_cache (CircuitCache, optional): A CircuitCache to use when calling compile_and_run_circuits
Returns:
QasmObj: compiled qobj.
Raises:
AquaError: Any error except for JobError raised by Qiskit Terra
"""
backend_config = backend_config or {}
compile_config = compile_config or {}
run_config = run_config or {}
if backend is None or not isinstance(backend, BaseBackend):
raise ValueError('Backend is missing or not an instance of BaseBackend')
if not isinstance(circuits, list):
circuits = [circuits]
if is_simulator_backend(backend):
circuits = _avoid_empty_circuits(circuits)
if MAX_CIRCUITS_PER_JOB is not None:
max_circuits_per_job = int(MAX_CIRCUITS_PER_JOB)
else:
if is_local_backend(backend):
max_circuits_per_job = sys.maxsize
else:
max_circuits_per_job = backend.configuration().max_experiments
if circuit_cache is not None and circuit_cache.try_reusing_qobjs:
# Check if all circuits are the same length.
# If not, don't try to use the same qobj.experiment for all of them.
if len(set([len(circ.data) for circ in circuits])) > 1:
circuit_cache.try_reusing_qobjs = False
else: # Try setting up the reusable qobj
# Compile and cache first circuit if cache is empty. The load method will try to reuse it
if circuit_cache.qobjs is None:
qobj, transpiled_circuits = _compile_wrapper([circuits[0]], backend, backend_config,
compile_config, run_config)
if is_aer_provider(backend):
qobj = _maybe_add_aer_expectation_instruction(qobj, kwargs)
circuit_cache.cache_circuit(qobj, [circuits[0]], 0)
qobjs = []
transpiled_circuits = []
chunks = int(np.ceil(len(circuits) / max_circuits_per_job))
for i in range(chunks):
sub_circuits = circuits[i * max_circuits_per_job:(i + 1) * max_circuits_per_job]
if circuit_cache is not None and circuit_cache.misses < circuit_cache.allowed_misses:
try:
if circuit_cache.cache_transpiled_circuits:
transpiled_sub_circuits = compiler.transpile(sub_circuits, backend, **backend_config,
**compile_config)
qobj = circuit_cache.load_qobj_from_cache(transpiled_sub_circuits, i, run_config=run_config)
else:
qobj = circuit_cache.load_qobj_from_cache(sub_circuits, i, run_config=run_config)
if is_aer_provider(backend):
qobj = _maybe_add_aer_expectation_instruction(qobj, kwargs)
# cache miss, fail gracefully
except (TypeError, IndexError, FileNotFoundError, EOFError, AquaError, AttributeError) as e:
circuit_cache.try_reusing_qobjs = False # Reusing Qobj didn't work
if len(circuit_cache.qobjs) > 0:
logger.info('Circuit cache miss, recompiling. Cache miss reason: ' + repr(e))
circuit_cache.misses += 1
else:
logger.info('Circuit cache is empty, compiling from scratch.')
circuit_cache.clear_cache()
qobj, transpiled_sub_circuits = _compile_wrapper(sub_circuits, backend, backend_config,
compile_config, run_config)
transpiled_circuits.extend(transpiled_sub_circuits)
if is_aer_provider(backend):
qobj = _maybe_add_aer_expectation_instruction(qobj, kwargs)
try:
circuit_cache.cache_circuit(qobj, sub_circuits, i)
except (TypeError, IndexError, AquaError, AttributeError, KeyError) as e:
try:
circuit_cache.cache_transpiled_circuits = True
circuit_cache.cache_circuit(qobj, transpiled_sub_circuits, i)
except (TypeError, IndexError, AquaError, AttributeError, KeyError) as e:
logger.info('Circuit could not be cached for reason: ' + repr(e))
logger.info('Transpilation may be too aggressive. Try skipping transpiler.')
else:
qobj, transpiled_sub_circuits = _compile_wrapper(sub_circuits, backend, backend_config, compile_config,
run_config)
transpiled_circuits.extend(transpiled_sub_circuits)
if is_aer_provider(backend):
qobj = _maybe_add_aer_expectation_instruction(qobj, kwargs)
qobjs.append(qobj)
if logger.isEnabledFor(logging.DEBUG) and show_circuit_summary:
logger.debug("==== Before transpiler ====")
logger.debug(summarize_circuits(circuits))
logger.debug("==== After transpiler ====")
logger.debug(summarize_circuits(transpiled_circuits))
return qobjs
def _safe_submit_qobj(qobj, backend, backend_options, noise_config, skip_qobj_validation):
# assure get job ids
while True:
job = run_on_backend(backend, qobj, backend_options=backend_options, noise_config=noise_config,
skip_qobj_validation=skip_qobj_validation)
try:
job_id = job.job_id()
break
except JobError as e:
logger.warning("FAILURE: Can not get job id, Resubmit the qobj to get job id."
"Terra job error: {} ".format(e))
except Exception as e:
logger.warning("FAILURE: Can not get job id, Resubmit the qobj to get job id."
"Error: {} ".format(e))
return job, job_id
def run_qobjs(qobjs, backend, qjob_config=None, backend_options=None,
noise_config=None, skip_qobj_validation=False):
"""
An execution wrapper with Qiskit-Terra, with job auto recover capability.
The autorecovery feature is only applied for non-simulator backend.
This wraper will try to get the result no matter how long it costs.
Args:
qobjs (list[QasmObj]): qobjs to execute
backend (BaseBackend): backend instance
qjob_config (dict, optional): configuration for quantum job object
backend_options (dict, optional): configuration for simulator
noise_config (dict, optional): configuration for noise model
skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease submission time
Returns:
Result: Result object
Raises:
AquaError: Any error except for JobError raised by Qiskit Terra
"""
qjob_config = qjob_config or {}
backend_options = backend_options or {}
noise_config = noise_config or {}
if backend is None or not isinstance(backend, BaseBackend):
raise ValueError('Backend is missing or not an instance of BaseBackend')
with_autorecover = False if is_simulator_backend(backend) else True
jobs = []
job_ids = []
for qobj in qobjs:
job, job_id = _safe_submit_qobj(qobj, backend, backend_options, noise_config, skip_qobj_validation)
job_ids.append(job_id)
jobs.append(job)
results = []
if with_autorecover:
logger.info("Backend status: {}".format(backend.status()))
logger.info("There are {} jobs are submitted.".format(len(jobs)))
logger.info("All job ids:\n{}".format(job_ids))
for idx in range(len(jobs)):
job = jobs[idx]
job_id = job_ids[idx]
while True:
logger.info("Running {}-th qobj, job id: {}".format(idx, job_id))
# try to get result if possible
try:
result = job.result(**qjob_config)
if result.success:
results.append(result)
logger.info("COMPLETED the {}-th qobj, "
"job id: {}".format(idx, job_id))
break
else:
logger.warning("FAILURE: the {}-th qobj, "
"job id: {}".format(idx, job_id))
except JobError as e:
# if terra raise any error, which means something wrong, re-run it
logger.warning("FAILURE: the {}-th qobj, job id: {} "
"Terra job error: {} ".format(idx, job_id, e))
except Exception as e:
raise AquaError("FAILURE: the {}-th qobj, job id: {} "
"Unknown error: {} ".format(idx, job_id, e)) from e
# something wrong here if reach here, querying the status to check how to handle it.
# keep qeurying it until getting the status.
while True:
try:
job_status = job.status()
break
except JobError as e:
logger.warning("FAILURE: job id: {}, "
"status: 'FAIL_TO_GET_STATUS' "
"Terra job error: {}".format(job_id, e))
time.sleep(5)
except Exception as e:
raise AquaError("FAILURE: job id: {}, "
"status: 'FAIL_TO_GET_STATUS' "
"Unknown error: ({})".format(job_id, e)) from e
logger.info("Job status: {}".format(job_status))
# handle the failure job based on job status
if job_status == JobStatus.DONE:
logger.info("Job ({}) is completed anyway, retrieve result "
"from backend.".format(job_id))
job = backend.retrieve_job(job_id)
elif job_status == JobStatus.RUNNING or job_status == JobStatus.QUEUED:
logger.info("Job ({}) is {}, but encounter an exception, "
"recover it from backend.".format(job_id, job_status))
job = backend.retrieve_job(job_id)
else:
logger.info("Fail to run Job ({}), resubmit it.".format(job_id))
qobj = qobjs[idx]
# assure job get its id
job, job_id = _safe_submit_qobj(qobj, backend, backend_options, noise_config, skip_qobj_validation)
jobs[idx] = job
job_ids[idx] = job_id
else:
results = []
for job in jobs:
results.append(job.result(**qjob_config))
result = _combine_result_objects(results) if len(results) != 0 else None
return result
def compile_and_run_circuits(circuits, backend, backend_config=None,
compile_config=None, run_config=None,
qjob_config=None, backend_options=None,
noise_config=None, show_circuit_summary=False,
circuit_cache=None, skip_qobj_validation=False, **kwargs):
"""
An execution wrapper with Qiskit-Terra, with job auto recover capability.
The autorecovery feature is only applied for non-simulator backend.
This wraper will try to get the result no matter how long it costs.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute
backend (BaseBackend): backend instance
backend_config (dict, optional): configuration for backend
compile_config (dict, optional): configuration for compilation
run_config (RunConfig, optional): configuration for running a circuit
qjob_config (dict, optional): configuration for quantum job object
backend_options (dict, optional): configuration for simulator
noise_config (dict, optional): configuration for noise model
show_circuit_summary (bool, optional): showing the summary of submitted circuits.
circuit_cache (CircuitCache, optional): A CircuitCache to use when calling compile_and_run_circuits
skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease submission time
Returns:
Result: Result object
Raises:
AquaError: Any error except for JobError raised by Qiskit Terra
"""
qobjs = compile_circuits(circuits, backend, backend_config, compile_config, run_config,
show_circuit_summary, circuit_cache, **kwargs)
result = run_qobjs(qobjs, backend, qjob_config, backend_options, noise_config, skip_qobj_validation)
return result
# skip_qobj_validation = True does what backend.run and aerjob.submit do, but without qobj validation.
def run_on_backend(backend, qobj, backend_options=None, noise_config=None, skip_qobj_validation=False):
if skip_qobj_validation:
job_id = str(uuid.uuid4())
if is_aer_provider(backend):
from qiskit.providers.aer.aerjob import AerJob
temp_backend_options = backend_options['backend_options'] if backend_options != {} else None
temp_noise_config = noise_config['noise_model'] if noise_config != {} else None
job = AerJob(backend, job_id, backend._run_job, qobj, temp_backend_options, temp_noise_config, False)
job._future = job._executor.submit(job._fn, job._job_id, job._qobj, *job._args)
elif is_basicaer_provider(backend):
backend._set_options(qobj_config=qobj.config, **backend_options)
job = BasicAerJob(backend, job_id, backend._run_job, qobj)
job._future = job._executor.submit(job._fn, job._job_id, job._qobj)
elif is_ibmq_provider(backend):
# TODO: IBMQJob performs validation during the constructor. the following lines does not
# skip validation but run as is.
from qiskit.providers.ibmq.ibmqjob import IBMQJob
job = IBMQJob(backend, None, backend._api, qobj=qobj)
job._future = job._executor.submit(job._submit_callback)
else:
logger.info("Can't skip qobj validation for the third-party provider.")
job = backend.run(qobj, **backend_options, **noise_config)
return job
else:
job = backend.run(qobj, **backend_options, **noise_config)
return job
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua.components.initial_states import InitialState
logger = logging.getLogger(__name__)
class HartreeFock(InitialState):
"""A Hartree-Fock initial state."""
CONFIGURATION = {
'name': 'HartreeFock',
'description': 'Hartree-Fock initial state',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'hf_state_schema',
'type': 'object',
'properties': {
'num_orbitals': {
'type': 'integer',
'default': 4,
'minimum': 1
},
'num_particles': {
'type': 'integer',
'default': 2,
'minimum': 1
},
'qubit_mapping': {
'type': 'string',
'default': 'parity',
'oneOf': [
{'enum': ['jordan_wigner', 'parity', 'bravyi_kitaev']}
]
},
'two_qubit_reduction': {
'type': 'boolean',
'default': True
}
},
'additionalProperties': False
}
}
def __init__(self, num_qubits, num_orbitals, num_particles,
qubit_mapping='parity', two_qubit_reduction=True, sq_list=None):
"""Constructor.
Args:
num_qubits (int): number of qubits
num_orbitals (int): number of spin orbitals
qubit_mapping (str): mapping type for qubit operator
two_qubit_reduction (bool): flag indicating whether or not two qubit is reduced
num_particles (int): number of particles
sq_list ([int]): position of the single-qubit operators that anticommute
with the cliffords
Raises:
ValueError: wrong setting in num_particles and num_orbitals.
ValueError: wrong setting for computed num_qubits and supplied num_qubits.
"""
self.validate(locals())
super().__init__()
self._sq_list = sq_list
self._qubit_tapering = False if self._sq_list is None else True
self._qubit_mapping = qubit_mapping.lower()
self._two_qubit_reduction = two_qubit_reduction
if self._qubit_mapping != 'parity':
if self._two_qubit_reduction:
logger.warning("two_qubit_reduction only works with parity qubit mapping "
"but you have {}. We switch two_qubit_reduction "
"to False.".format(self._qubit_mapping))
self._two_qubit_reduction = False
self._num_orbitals = num_orbitals
self._num_particles = num_particles
if self._num_particles > self._num_orbitals:
raise ValueError("# of particles must be less than or equal to # of orbitals.")
self._num_qubits = num_orbitals - 2 if self._two_qubit_reduction else self._num_orbitals
self._num_qubits = self._num_qubits \
if not self._qubit_tapering else self._num_qubits - len(sq_list)
if self._num_qubits != num_qubits:
raise ValueError("Computed num qubits {} does not match "
"actual {}".format(self._num_qubits, num_qubits))
self._bitstr = None
def _build_bitstr(self):
half_orbitals = self._num_orbitals // 2
bitstr = np.zeros(self._num_orbitals, np.bool)
bitstr[-int(np.ceil(self._num_particles / 2)):] = True
bitstr[-(half_orbitals + int(np.floor(self._num_particles / 2))):-half_orbitals] = True
if self._qubit_mapping == 'parity':
new_bitstr = bitstr.copy()
t = np.triu(np.ones((self._num_orbitals, self._num_orbitals)))
new_bitstr = t.dot(new_bitstr.astype(np.int)) % 2
bitstr = np.append(new_bitstr[1:half_orbitals], new_bitstr[half_orbitals + 1:]) \
if self._two_qubit_reduction else new_bitstr
elif self._qubit_mapping == 'bravyi_kitaev':
binary_superset_size = int(np.ceil(np.log2(self._num_orbitals)))
beta = 1
basis = np.asarray([[1, 0], [0, 1]])
for i in range(binary_superset_size):
beta = np.kron(basis, beta)
beta[0, :] = 1
beta = beta[:self._num_orbitals, :self._num_orbitals]
new_bitstr = beta.dot(bitstr.astype(int)) % 2
bitstr = new_bitstr.astype(np.bool)
if self._qubit_tapering:
sq_list = (len(bitstr) - 1) - np.asarray(self._sq_list)
bitstr = np.delete(bitstr, sq_list)
self._bitstr = bitstr.astype(np.bool)
def construct_circuit(self, mode, register=None):
"""
Construct the statevector of desired initial state.
Args:
mode (string): `vector` or `circuit`. The `vector` mode produces the vector.
While the `circuit` constructs the quantum circuit corresponding that
vector.
register (QuantumRegister): register for circuit construction.
Returns:
QuantumCircuit or numpy.ndarray: statevector.
Raises:
ValueError: when mode is not 'vector' or 'circuit'.
"""
if self._bitstr is None:
self._build_bitstr()
if mode == 'vector':
state = 1.0
one = np.asarray([0.0, 1.0])
zero = np.asarray([1.0, 0.0])
for k in self._bitstr[::-1]:
state = np.kron(one if k else zero, state)
return state
elif mode == 'circuit':
if register is None:
register = QuantumRegister(self._num_qubits, name='q')
quantum_circuit = QuantumCircuit(register)
for qubit_idx, bit in enumerate(self._bitstr[::-1]):
if bit:
quantum_circuit.u3(np.pi, 0.0, np.pi, register[qubit_idx])
return quantum_circuit
else:
raise ValueError('Mode should be either "vector" or "circuit"')
@property
def bitstr(self):
"""Getter of the bit string represented the statevector."""
if self._bitstr is None:
self._build_bitstr()
return self._bitstr
|
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.
"""
This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations
variational form.
For more information, see https://arxiv.org/abs/1805.04340
"""
import logging
import sys
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.tools import parallel_map
from qiskit.tools.events import TextProgressBar
from qiskit.aqua import Operator, aqua_globals
from qiskit.aqua.components.variational_forms import VariationalForm
from qiskit.chemistry.fermionic_operator import FermionicOperator
from qiskit.chemistry import MP2Info
from qiskit.chemistry import QMolecule as qm
logger = logging.getLogger(__name__)
class UCCSD(VariationalForm):
"""
This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations
variational form.
For more information, see https://arxiv.org/abs/1805.04340
"""
CONFIGURATION = {
'name': 'UCCSD',
'description': 'UCCSD Variational Form',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'uccsd_schema',
'type': 'object',
'properties': {
'depth': {
'type': 'integer',
'default': 1,
'minimum': 1
},
'num_orbitals': {
'type': 'integer',
'default': 4,
'minimum': 1
},
'num_particles': {
'type': 'integer',
'default': 2,
'minimum': 1
},
'active_occupied': {
'type': ['array', 'null'],
'default': None
},
'active_unoccupied': {
'type': ['array', 'null'],
'default': None
},
'qubit_mapping': {
'type': 'string',
'default': 'parity',
'oneOf': [
{'enum': ['jordan_wigner', 'parity', 'bravyi_kitaev']}
]
},
'two_qubit_reduction': {
'type': 'boolean',
'default': False
},
'mp2_reduction': {
'type': 'boolean',
'default': False
},
'num_time_slices': {
'type': 'integer',
'default': 1,
'minimum': 1
},
},
'additionalProperties': False
},
'depends': [
{
'pluggable_type': 'initial_state',
'default': {
'name': 'HartreeFock',
}
},
],
}
def __init__(self, num_qubits, depth, num_orbitals, num_particles,
active_occupied=None, active_unoccupied=None, initial_state=None,
qubit_mapping='parity', two_qubit_reduction=False, mp2_reduction=False, num_time_slices=1,
cliffords=None, sq_list=None, tapering_values=None, symmetries=None,
shallow_circuit_concat=True):
"""Constructor.
Args:
num_orbitals (int): number of spin orbitals
depth (int): number of replica of basic module
num_particles (int): number of particles
active_occupied (list): list of occupied orbitals to consider as active space
active_unoccupied (list): list of unoccupied orbitals to consider as active space
initial_state (InitialState): An initial state object.
qubit_mapping (str): qubit mapping type.
two_qubit_reduction (bool): two qubit reduction is applied or not.
num_time_slices (int): parameters for dynamics.
cliffords ([Operator]): list of unitary Clifford transformation
sq_list ([int]): position of the single-qubit operators that anticommute
with the cliffords
tapering_values ([int]): array of +/- 1 used to select the subspace. Length
has to be equal to the length of cliffords and sq_list
symmetries ([Pauli]): represent the Z2 symmetries
shallow_circuit_concat (bool): indicate whether to use shallow (cheap) mode for circuit concatenation
"""
self.validate(locals())
super().__init__()
self._cliffords = cliffords
self._sq_list = sq_list
self._tapering_values = tapering_values
self._symmetries = symmetries
if self._cliffords is not None and self._sq_list is not None and \
self._tapering_values is not None and self._symmetries is not None:
self._qubit_tapering = True
else:
self._qubit_tapering = False
self._num_qubits = num_orbitals if not two_qubit_reduction else num_orbitals - 2
self._num_qubits = self._num_qubits if not self._qubit_tapering else self._num_qubits - len(sq_list)
if self._num_qubits != num_qubits:
raise ValueError('Computed num qubits {} does not match actual {}'
.format(self._num_qubits, num_qubits))
self._depth = depth
self._num_orbitals = num_orbitals
self._num_particles = num_particles
if self._num_particles > self._num_orbitals:
raise ValueError('# of particles must be less than or equal to # of orbitals.')
self._initial_state = initial_state
self._qubit_mapping = qubit_mapping
self._two_qubit_reduction = two_qubit_reduction
self._num_time_slices = num_time_slices
self._shallow_circuit_concat = shallow_circuit_concat
self._single_excitations, self._double_excitations = \
UCCSD.compute_excitation_lists(num_particles, num_orbitals,
active_occupied, active_unoccupied)
self._single_excitations = []
print('{} are the old doubles'.format(self._double_excitations))
print(mp2_reduction)
if mp2_reduction:
print('Getting new doubles')
self._double_excitations = get_mp2_doubles(self._single_excitations,self._double_excitations)
print('{} are the new doubles'.format(self._double_excitations))
self._hopping_ops, self._num_parameters = self._build_hopping_operators()
self._bounds = [(-np.pi, np.pi) for _ in range(self._num_parameters)]
self._logging_construct_circuit = True
def _build_hopping_operators(self):
from .uccsd import UCCSD
hopping_ops = []
if logger.isEnabledFor(logging.DEBUG):
TextProgressBar(sys.stderr)
results = parallel_map(UCCSD._build_hopping_operator, self._single_excitations + self._double_excitations,
task_args=(self._num_orbitals, self._num_particles,
self._qubit_mapping, self._two_qubit_reduction, self._qubit_tapering,
self._symmetries, self._cliffords, self._sq_list, self._tapering_values),
num_processes=aqua_globals.num_processes)
hopping_ops = [qubit_op for qubit_op in results if qubit_op is not None]
num_parameters = len(hopping_ops) * self._depth
return hopping_ops, num_parameters
@staticmethod
def _build_hopping_operator(index, num_orbitals, num_particles, qubit_mapping,
two_qubit_reduction, qubit_tapering, symmetries,
cliffords, sq_list, tapering_values):
def check_commutativity(op_1, op_2):
com = op_1 * op_2 - op_2 * op_1
com.zeros_coeff_elimination()
return True if com.is_empty() else False
h1 = np.zeros((num_orbitals, num_orbitals))
h2 = np.zeros((num_orbitals, num_orbitals, num_orbitals, num_orbitals))
if len(index) == 2:
i, j = index
h1[i, j] = 1.0
h1[j, i] = -1.0
elif len(index) == 4:
i, j, k, m = index
h2[i, j, k, m] = 1.0
h2[m, k, j, i] = -1.0
dummpy_fer_op = FermionicOperator(h1=h1, h2=h2)
qubit_op = dummpy_fer_op.mapping(qubit_mapping)
qubit_op = qubit_op.two_qubit_reduced_operator(num_particles) \
if two_qubit_reduction else qubit_op
if qubit_tapering:
for symmetry in symmetries:
symmetry_op = Operator(paulis=[[1.0, symmetry]])
symm_commuting = check_commutativity(symmetry_op, qubit_op)
if not symm_commuting:
break
if qubit_tapering:
if symm_commuting:
qubit_op = Operator.qubit_tapering(qubit_op, cliffords,
sq_list, tapering_values)
else:
qubit_op = None
if qubit_op is None:
logger.debug('Excitation ({}) is skipped since it is not commuted '
'with symmetries'.format(','.join([str(x) for x in index])))
return qubit_op
def construct_circuit(self, parameters, q=None):
"""
Construct the variational form, given its parameters.
Args:
parameters (numpy.ndarray): circuit parameters
q (QuantumRegister): Quantum Register for the circuit.
Returns:
QuantumCircuit: a quantum circuit with given `parameters`
Raises:
ValueError: the number of parameters is incorrect.
"""
from .uccsd import UCCSD
if len(parameters) != self._num_parameters:
raise ValueError('The number of parameters has to be {}'.format(self._num_parameters))
if q is None:
q = QuantumRegister(self._num_qubits, name='q')
if self._initial_state is not None:
circuit = self._initial_state.construct_circuit('circuit', q)
else:
circuit = QuantumCircuit(q)
if logger.isEnabledFor(logging.DEBUG) and self._logging_construct_circuit:
logger.debug("Evolving hopping operators:")
TextProgressBar(sys.stderr)
self._logging_construct_circuit = False
num_excitations = len(self._hopping_ops)
results = parallel_map(UCCSD._construct_circuit_for_one_excited_operator,
[(self._hopping_ops[index % num_excitations], parameters[index])
for index in range(self._depth * num_excitations)],
task_args=(q, self._num_time_slices),
num_processes=aqua_globals.num_processes)
for qc in results:
if self._shallow_circuit_concat:
circuit.data += qc.data
else:
circuit += qc
return circuit
@staticmethod
def _construct_circuit_for_one_excited_operator(qubit_op_and_param, qr, num_time_slices):
qubit_op, param = qubit_op_and_param
qc = qubit_op.evolve(None, param * -1j, 'circuit', num_time_slices, qr)
return qc
@property
def preferred_init_points(self):
"""Getter of preferred initial points based on the given initial state."""
if self._initial_state is None:
return None
else:
bitstr = self._initial_state.bitstr
if bitstr is not None:
return np.zeros(self._num_parameters, dtype=np.float)
else:
return None
@staticmethod
def compute_excitation_lists(num_particles, num_orbitals, active_occ_list=None,
active_unocc_list=None, same_spin_doubles=True):
"""
Computes single and double excitation lists
Args:
num_particles: Total number of particles
num_orbitals: Total number of spin orbitals
active_occ_list: List of occupied orbitals to include, indices are
0 to n where n is num particles // 2
active_unocc_list: List of unoccupied orbitals to include, indices are
0 to m where m is (num_orbitals - num particles) // 2
same_spin_doubles: True to include alpha,alpha and beta,beta double excitations
as well as alpha,beta pairings. False includes only alpha,beta
Returns:
Single and double excitation lists
"""
if num_particles < 2 or num_particles % 2 != 0:
raise ValueError('Invalid number of particles {}'.format(num_particles))
if num_orbitals < 4 or num_orbitals % 2 != 0:
raise ValueError('Invalid number of orbitals {}'.format(num_orbitals))
if num_orbitals <= num_particles:
raise ValueError('No unoccupied orbitals')
if active_occ_list is not None:
active_occ_list = [i if i >= 0 else i + num_particles // 2 for i in active_occ_list]
for i in active_occ_list:
if i >= num_particles // 2:
raise ValueError('Invalid index {} in active active_occ_list {}'
.format(i, active_occ_list))
if active_unocc_list is not None:
active_unocc_list = [i + num_particles // 2 if i >=
0 else i + num_orbitals // 2 for i in active_unocc_list]
for i in active_unocc_list:
if i < 0 or i >= num_orbitals // 2:
raise ValueError('Invalid index {} in active active_unocc_list {}'
.format(i, active_unocc_list))
if active_occ_list is None or len(active_occ_list) <= 0:
active_occ_list = [i for i in range(0, num_particles // 2)]
if active_unocc_list is None or len(active_unocc_list) <= 0:
active_unocc_list = [i for i in range(num_particles // 2, num_orbitals // 2)]
single_excitations = []
double_excitations = []
logger.debug('active_occ_list {}'.format(active_occ_list))
logger.debug('active_unocc_list {}'.format(active_unocc_list))
beta_idx = num_orbitals // 2
for occ_alpha in active_occ_list:
for unocc_alpha in active_unocc_list:
single_excitations.append([occ_alpha, unocc_alpha])
for occ_beta in [i + beta_idx for i in active_occ_list]:
for unocc_beta in [i + beta_idx for i in active_unocc_list]:
single_excitations.append([occ_beta, unocc_beta])
for occ_alpha in active_occ_list:
for unocc_alpha in active_unocc_list:
for occ_beta in [i + beta_idx for i in active_occ_list]:
for unocc_beta in [i + beta_idx for i in active_unocc_list]:
double_excitations.append([occ_alpha, unocc_alpha, occ_beta, unocc_beta])
if same_spin_doubles and len(active_occ_list) > 1 and len(active_unocc_list) > 1:
for i, occ_alpha in enumerate(active_occ_list[:-1]):
for j, unocc_alpha in enumerate(active_unocc_list[:-1]):
for occ_alpha_1 in active_occ_list[i + 1:]:
for unocc_alpha_1 in active_unocc_list[j + 1:]:
double_excitations.append([occ_alpha, unocc_alpha,
occ_alpha_1, unocc_alpha_1])
up_active_occ_list = [i + beta_idx for i in active_occ_list]
up_active_unocc_list = [i + beta_idx for i in active_unocc_list]
for i, occ_beta in enumerate(up_active_occ_list[:-1]):
for j, unocc_beta in enumerate(up_active_unocc_list[:-1]):
for occ_beta_1 in up_active_occ_list[i + 1:]:
for unocc_beta_1 in up_active_unocc_list[j + 1:]:
double_excitations.append([occ_beta, unocc_beta,
occ_beta_1, unocc_beta_1])
logger.debug('single_excitations ({}) {}'.format(len(single_excitations), single_excitations))
logger.debug('double_excitations ({}) {}'.format(len(double_excitations), double_excitations))
return single_excitations, double_excitations
def get_mp2_doubles(single_excitations, double_excitations):
print('Is the class still populated with the correct info: ', qm.nuclear_repulsion_energy)
mp2 = MP2Info(qm, single_excitations, double_excitations, threshold=1e-3)
mp2_doubles = mp2._mp2_doubles
return mp2_doubles
|
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/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Functions used for the analysis of randomized benchmarking results.
"""
from scipy.optimize import curve_fit
import numpy as np
from qiskit import QiskitError
from ..tomography import marginal_counts
from ...characterization.fitters import build_counts_dict_from_list
try:
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
class RBFitter:
"""
Class for fitters for randomized benchmarking
"""
def __init__(self, backend_result, cliff_lengths,
rb_pattern=None):
"""
Args:
backend_result: list of results (qiskit.Result).
cliff_lengths: the Clifford lengths, 2D list i x j where i is the
number of patterns, j is the number of cliffords lengths
rb_pattern: the pattern for the rb sequences.
"""
if rb_pattern is None:
rb_pattern = [[0]]
self._cliff_lengths = cliff_lengths
self._rb_pattern = rb_pattern
self._raw_data = []
self._ydata = []
self._fit = []
self._nseeds = 0
self._result_list = []
self.add_data(backend_result)
@property
def raw_data(self):
"""Return raw data."""
return self._raw_data
@property
def cliff_lengths(self):
"""Return clifford lengths."""
return self.cliff_lengths
@property
def ydata(self):
"""Return ydata (means and std devs)."""
return self._ydata
@property
def fit(self):
"""Return fit."""
return self._fit
@property
def seeds(self):
"""Return the number of loaded seeds."""
return self._nseeds
@property
def results(self):
"""Return all the results."""
return self._result_list
def add_data(self, new_backend_result, rerun_fit=True):
"""
Add a new result. Re calculate the raw data, means and
fit.
Args:
new_backend_result: list of rb results
rerun_fit: re caculate the means and fit the result
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
if new_backend_result is None:
return
if not isinstance(new_backend_result, list):
new_backend_result = [new_backend_result]
for result in new_backend_result:
self._result_list.append(result)
# update the number of seeds *if* new ones
# added. Note, no checking if we've done all the
# cliffords
for rbcirc in result.results:
nseeds_circ = int(rbcirc.header.name.split('_')[-1])
if (nseeds_circ+1) > self._nseeds:
self._nseeds = nseeds_circ+1
for result in self._result_list:
if not len(result.results) == len(self._cliff_lengths[0]):
raise ValueError(
"The number of clifford lengths must match the number of "
"results")
if rerun_fit:
self.calc_data()
self.calc_statistics()
self.fit_data()
@staticmethod
def _rb_fit_fun(x, a, alpha, b):
"""Function used to fit rb."""
# pylint: disable=invalid-name
return a * alpha ** x + b
def calc_data(self):
"""
Retrieve probabilities of success from execution results. Outputs
results into an internal variable _raw_data which is a 3-dimensional
list, where item (i,j,k) is the probability to measure the ground state
for the set of qubits in pattern "i" for seed no. j and vector length
self._cliff_lengths[i][k].
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
circ_counts = {}
circ_shots = {}
for seedidx in range(self._nseeds):
for circ, _ in enumerate(self._cliff_lengths[0]):
circ_name = 'rb_length_%d_seed_%d' % (circ, seedidx)
count_list = []
for result in self._result_list:
try:
count_list.append(result.get_counts(circ_name))
except (QiskitError, KeyError):
pass
circ_counts[circ_name] = \
build_counts_dict_from_list(count_list)
circ_shots[circ_name] = sum(circ_counts[circ_name].values())
self._raw_data = []
startind = 0
for patt_ind in range(len(self._rb_pattern)):
string_of_0s = ''
string_of_0s = string_of_0s.zfill(len(self._rb_pattern[patt_ind]))
self._raw_data.append([])
endind = startind+len(self._rb_pattern[patt_ind])
for i in range(self._nseeds):
self._raw_data[-1].append([])
for k, _ in enumerate(self._cliff_lengths[patt_ind]):
circ_name = 'rb_length_%d_seed_%d' % (k, i)
counts_subspace = marginal_counts(
circ_counts[circ_name],
np.arange(startind, endind))
self._raw_data[-1][i].append(
counts_subspace.get(string_of_0s, 0)
/ circ_shots[circ_name])
startind += (endind)
def calc_statistics(self):
"""
Extract averages and std dev from the raw data (self._raw_data).
Assumes that self._calc_data has been run. Output into internal
_ydata variable:
ydata is a list of dictionaries (length number of patterns).
Dictionary ydata[i]:
ydata[i]['mean'] is a numpy_array of length n;
entry j of this array contains the mean probability of
success over seeds, for vector length
self._cliff_lengths[i][j].
And ydata[i]['std'] is a numpy_array of length n;
entry j of this array contains the std
of the probability of success over seeds,
for vector length self._cliff_lengths[i][j].
"""
self._ydata = []
for patt_ind in range(len(self._rb_pattern)):
self._ydata.append({})
self._ydata[-1]['mean'] = np.mean(self._raw_data[patt_ind], 0)
if len(self._raw_data[patt_ind]) == 1: # 1 seed
self._ydata[-1]['std'] = None
else:
self._ydata[-1]['std'] = np.std(self._raw_data[patt_ind], 0)
def fit_data(self):
"""
Fit the RB results to an exponential curve.
Fit each of the patterns
Puts the results into a list of fit dictionaries:
where each dictionary corresponds to a pattern and has fields:
'params' - three parameters of rb_fit_fun. The middle one is the
exponent.
'err' - the error limits of the parameters.
'epc' - error per Clifford
"""
self._fit = []
for patt_ind, (lens, qubits) in enumerate(zip(self._cliff_lengths,
self._rb_pattern)):
# if at least one of the std values is zero, then sigma is replaced
# by None
if not self._ydata[patt_ind]['std'] is None:
sigma = self._ydata[patt_ind]['std'].copy()
if len(sigma) - np.count_nonzero(sigma) > 0:
sigma = None
else:
sigma = None
params, pcov = curve_fit(self._rb_fit_fun, lens,
self._ydata[patt_ind]['mean'],
sigma=sigma,
p0=(1.0, 0.95, 0.0),
bounds=([-2, 0, -2], [2, 1, 2]))
alpha = params[1] # exponent
params_err = np.sqrt(np.diag(pcov))
alpha_err = params_err[1]
nrb = 2 ** len(qubits)
epc = (nrb-1)/nrb*(1-alpha)
epc_err = epc*alpha_err/alpha
self._fit.append({'params': params, 'params_err': params_err,
'epc': epc, 'epc_err': epc_err})
def plot_rb_data(self, pattern_index=0, ax=None,
add_label=True, show_plt=True):
"""
Plot randomized benchmarking data of a single pattern.
Args:
pattern_index: which RB pattern to plot
ax (Axes or None): plot axis (if passed in).
add_label (bool): Add an EPC label
show_plt (bool): display the plot.
Raises:
ImportError: If matplotlib is not installed.
"""
fit_function = self._rb_fit_fun
if not HAS_MATPLOTLIB:
raise ImportError('The function plot_rb_data needs matplotlib. '
'Run "pip install matplotlib" before.')
if ax is None:
plt.figure()
ax = plt.gca()
xdata = self._cliff_lengths[pattern_index]
# Plot the result for each sequence
for one_seed_data in self._raw_data[pattern_index]:
ax.plot(xdata, one_seed_data, color='gray', linestyle='none',
marker='x')
# Plot the mean with error bars
ax.errorbar(xdata, self._ydata[pattern_index]['mean'],
yerr=self._ydata[pattern_index]['std'],
color='r', linestyle='--', linewidth=3)
# Plot the fit
ax.plot(xdata,
fit_function(xdata, *self._fit[pattern_index]['params']),
color='blue', linestyle='-', linewidth=2)
ax.tick_params(labelsize=14)
ax.set_xlabel('Clifford Length', fontsize=16)
ax.set_ylabel('Ground State Population', fontsize=16)
ax.grid(True)
if add_label:
bbox_props = dict(boxstyle="round,pad=0.3",
fc="white", ec="black", lw=2)
ax.text(0.6, 0.9,
"alpha: %.3f(%.1e) EPC: %.3e(%.1e)" %
(self._fit[pattern_index]['params'][1],
self._fit[pattern_index]['params_err'][1],
self._fit[pattern_index]['epc'],
self._fit[pattern_index]['epc_err']),
ha="center", va="center", size=14,
bbox=bbox_props, transform=ax.transAxes)
if show_plt:
plt.show()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=cell-var-from-loop
"""
Measurement correction filters.
"""
from copy import deepcopy
from scipy.optimize import minimize
import scipy.linalg as la
import numpy as np
import qiskit
from qiskit.validation.base import Obj
from qiskit import QiskitError
from ...verification.tomography import count_keys
class MeasurementFilter():
"""
Measurement error mitigation filter
Produced from a measurement calibration fitter and can be applied
to data
"""
def __init__(self, cal_matrix, state_labels):
"""
Initialize a measurement error mitigation filter using the cal_matrix
from a measurement calibration fitter
Args:
cal_matrix: the calibration matrix for applying the correction
state_labels: the states for the ordering of the cal matrix
"""
self._cal_matrix = cal_matrix
self._state_labels = state_labels
@property
def cal_matrix(self):
"""Return cal_matrix."""
return self._cal_matrix
@property
def state_labels(self):
"""return the state label ordering of the cal matrix"""
return self._state_labels
@state_labels.setter
def state_labels(self, new_state_labels):
"""set the state label ordering of the cal matrix"""
self._state_labels = new_state_labels
@cal_matrix.setter
def cal_matrix(self, new_cal_matrix):
"""Set cal_matrix."""
self._cal_matrix = new_cal_matrix
def apply(self, raw_data, method='least_squares'):
"""
Apply the calibration matrix to results
Args:
raw_data: The data to be corrected. Can be in a number of forms.
Form1: a counts dictionary from results.get_counts
Form2: a list of counts of length==len(state_labels)
Form3: a list of counts of length==M*len(state_labels) where M
is an integer (e.g. for use with the tomography data)
Form4: a qiskit Result
method (str): fitting method. If None, then least_squares is used.
'pseudo_inverse': direct inversion of the A matrix
'least_squares': constrained to have physical probabilities
Returns:
The corrected data in the same form as raw_data
Additional Information:
e.g.
calcircuits, state_labels = complete_measurement_calibration(
qiskit.QuantumRegister(5))
job = qiskit.execute(calcircuits)
meas_fitter = CompleteMeasFitter(job.results(),
state_labels)
meas_filter = MeasurementFilter(meas_fitter.cal_matrix)
job2 = qiskit.execute(my_circuits)
result2 = job2.results()
error_mitigated_counts = meas_filter.apply(
result2.get_counts('circ1'))
"""
# check forms of raw_data
if isinstance(raw_data, dict):
# counts dictionary
data_format = 0
# convert to form2
raw_data2 = [np.zeros(len(self._state_labels), dtype=float)]
for stateidx, state in enumerate(self._state_labels):
raw_data2[0][stateidx] = raw_data.get(state, 0)
elif isinstance(raw_data, list):
size_ratio = len(raw_data)/len(self._state_labels)
if len(raw_data) == len(self._state_labels):
data_format = 1
raw_data2 = [raw_data]
elif int(size_ratio) == size_ratio:
data_format = 2
size_ratio = int(size_ratio)
# make the list into chunks the size of state_labels for easier
# processing
raw_data2 = np.zeros([size_ratio, len(self._state_labels)])
for i in range(size_ratio):
raw_data2[i][:] = raw_data[
i * len(self._state_labels):(i + 1)*len(
self._state_labels)]
else:
raise QiskitError("Data list is not an integer multiple "
"of the number of calibrated states")
elif isinstance(raw_data, qiskit.result.result.Result):
# extract out all the counts, re-call the function with the
# counts and push back into the new result
new_result = deepcopy(raw_data)
for resultidx, _ in enumerate(raw_data.results):
new_counts = self.apply(
raw_data.get_counts(resultidx), method=method)
new_result.results[resultidx].data.counts = \
new_result.results[resultidx]. \
data.counts.from_dict(new_counts)
return new_result
else:
raise QiskitError("Unrecognized type for raw_data.")
if method == 'pseudo_inverse':
pinv_cal_mat = la.pinv(self._cal_matrix)
# Apply the correction
for data_idx, _ in enumerate(raw_data2):
if method == 'pseudo_inverse':
raw_data2[data_idx] = np.dot(
pinv_cal_mat, raw_data2[data_idx])
elif method == 'least_squares':
nshots = sum(raw_data2[data_idx])
def fun(x):
return sum(
(raw_data2[data_idx] - np.dot(self._cal_matrix, x))**2)
x0 = np.random.rand(len(self._state_labels))
x0 = x0 / sum(x0)
cons = ({'type': 'eq', 'fun': lambda x: nshots - sum(x)})
bnds = tuple((0, nshots) for x in x0)
res = minimize(fun, x0, method='SLSQP',
constraints=cons, bounds=bnds, tol=1e-6)
raw_data2[data_idx] = res.x
else:
raise QiskitError("Unrecognized method.")
if data_format == 2:
# flatten back out the list
raw_data2 = raw_data2.flatten()
elif data_format == 0:
# convert back into a counts dictionary
new_count_dict = {}
for stateidx, state in enumerate(self._state_labels):
if raw_data2[0][stateidx] != 0:
new_count_dict[state] = raw_data2[0][stateidx]
raw_data2 = new_count_dict
else:
# TODO: should probably change to:
# raw_data2 = raw_data2[0].tolist()
raw_data2 = raw_data2[0]
return raw_data2
class TensoredFilter():
"""
Tensored measurement error mitigation filter
Produced from a tensored measurement calibration fitter and can be applied
to data
"""
def __init__(self, cal_matrices, substate_labels_list):
"""
Initialize a tensored measurement error mitigation filter using
the cal_matrices from a tensored measurement calibration fitter
Args:
cal_matrices: the calibration matrices for applying the correction
qubit_list_sizes: the lengths of the lists in mit_pattern
(see tensored_meas_cal in circuits.py for mit_pattern)
substate_labels_list (list of lists): for each calibration matrix
a list of the states (as strings, states in the subspace)
"""
self._cal_matrices = cal_matrices
self._qubit_list_sizes = []
self._indices_list = []
self._substate_labels_list = []
self.substate_labels_list = substate_labels_list
@property
def cal_matrices(self):
"""Return cal_matrices."""
return self._cal_matrices
@cal_matrices.setter
def cal_matrices(self, new_cal_matrices):
"""Set cal_matrices."""
self._cal_matrices = deepcopy(new_cal_matrices)
@property
def substate_labels_list(self):
"""Return _substate_labels_list"""
return self._substate_labels_list
@substate_labels_list.setter
def substate_labels_list(self, new_substate_labels_list):
"""Return _substate_labels_list"""
self._substate_labels_list = new_substate_labels_list
# get the number of qubits in each subspace
self._qubit_list_sizes = []
for _, substate_label_list in enumerate(self._substate_labels_list):
self._qubit_list_sizes.append(
int(np.log2(len(substate_label_list))))
# get the indices in the calibration matrix
self._indices_list = []
for _, sub_labels in enumerate(self._substate_labels_list):
self._indices_list.append(
{lab: ind for ind, lab in enumerate(sub_labels)})
@property
def qubit_list_sizes(self):
"""Return _qubit_list_sizes"""
return self._qubit_list_sizes
@property
def nqubits(self):
"""Return the number of qubits"""
return sum(self._qubit_list_sizes)
def apply(self, raw_data, method='least_squares'):
"""
Apply the calibration matrices to results
Args:
raw_data: The data to be corrected. Can be in a number of forms.
a counts dictionary from results.get_countsphy data);
or a qiskit Result
method (str): fitting method. If None, then least_squares is used.
'pseudo_inverse': direct inversion of the cal matrices
'least_squares': constrained to have physical probabilities
Returns:
The corrected data in the same form as raw_data
"""
all_states = count_keys(self.nqubits)
num_of_states = 2**self.nqubits
# check forms of raw_data
if isinstance(raw_data, dict):
# counts dictionary
# convert to list
raw_data2 = [np.zeros(num_of_states, dtype=float)]
for state, count in raw_data.items():
stateidx = int(state, 2)
raw_data2[0][stateidx] = count
elif isinstance(raw_data, qiskit.result.result.Result):
# extract out all the counts, re-call the function with the
# counts and push back into the new result
new_result = deepcopy(raw_data)
for resultidx, _ in enumerate(raw_data.results):
new_counts = self.apply(
raw_data.get_counts(resultidx), method=method)
new_result.results[resultidx].data.counts = \
Obj(**new_counts)
return new_result
else:
raise QiskitError("Unrecognized type for raw_data.")
if method == 'pseudo_inverse':
pinv_cal_matrices = []
for cal_mat in self._cal_matrices:
pinv_cal_matrices.append(la.pinv(cal_mat))
# Apply the correction
for data_idx, _ in enumerate(raw_data2):
if method == 'pseudo_inverse':
inv_mat_dot_raw = np.zeros([num_of_states], dtype=float)
for state1_idx, state1 in enumerate(all_states):
for state2_idx, state2 in enumerate(all_states):
if raw_data2[data_idx][state2_idx] == 0:
continue
product = 1.
end_index = self.nqubits
for p_ind, pinv_mat in enumerate(pinv_cal_matrices):
start_index = end_index - \
self._qubit_list_sizes[p_ind]
state1_as_int = \
self._indices_list[p_ind][
state1[start_index:end_index]]
state2_as_int = \
self._indices_list[p_ind][
state2[start_index:end_index]]
end_index = start_index
product *= \
pinv_mat[state1_as_int][state2_as_int]
if product == 0:
break
inv_mat_dot_raw[state1_idx] += \
(product * raw_data2[data_idx][state2_idx])
raw_data2[data_idx] = inv_mat_dot_raw
elif method == 'least_squares':
def fun(x):
mat_dot_x = np.zeros([num_of_states], dtype=float)
for state1_idx, state1 in enumerate(all_states):
mat_dot_x[state1_idx] = 0.
for state2_idx, state2 in enumerate(all_states):
if x[state2_idx] != 0:
product = 1.
end_index = self.nqubits
for c_ind, cal_mat in \
enumerate(self._cal_matrices):
start_index = end_index - \
self._qubit_list_sizes[c_ind]
state1_as_int = \
self._indices_list[c_ind][
state1[start_index:end_index]]
state2_as_int = \
self._indices_list[c_ind][
state2[start_index:end_index]]
end_index = start_index
product *= \
cal_mat[state1_as_int][state2_as_int]
if product == 0:
break
mat_dot_x[state1_idx] += \
(product * x[state2_idx])
return sum(
(raw_data2[data_idx] - mat_dot_x)**2)
x0 = np.random.rand(num_of_states)
x0 = x0 / sum(x0)
nshots = sum(raw_data2[data_idx])
cons = ({'type': 'eq', 'fun': lambda x: nshots - sum(x)})
bnds = tuple((0, nshots) for x in x0)
res = minimize(fun, x0, method='SLSQP',
constraints=cons, bounds=bnds, tol=1e-6)
raw_data2[data_idx] = res.x
else:
raise QiskitError("Unrecognized method.")
# convert back into a counts dictionary
new_count_dict = {}
for state_idx, state in enumerate(all_states):
if raw_data2[0][state_idx] != 0:
new_count_dict[state] = raw_data2[0][state_idx]
return new_count_dict
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Functions used for the analysis of randomized benchmarking results.
"""
from scipy.optimize import curve_fit
import numpy as np
from qiskit import QiskitError
from ..tomography import marginal_counts
from ...characterization.fitters import build_counts_dict_from_list
try:
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
class RBFitter:
"""
Class for fitters for randomized benchmarking
"""
def __init__(self, backend_result, cliff_lengths,
rb_pattern=None):
"""
Args:
backend_result: list of results (qiskit.Result).
cliff_lengths: the Clifford lengths, 2D list i x j where i is the
number of patterns, j is the number of cliffords lengths
rb_pattern: the pattern for the rb sequences.
"""
if rb_pattern is None:
rb_pattern = [[0]]
self._cliff_lengths = cliff_lengths
self._rb_pattern = rb_pattern
self._raw_data = []
self._ydata = []
self._fit = []
self._nseeds = 0
self._result_list = []
self.add_data(backend_result)
@property
def raw_data(self):
"""Return raw data."""
return self._raw_data
@property
def cliff_lengths(self):
"""Return clifford lengths."""
return self.cliff_lengths
@property
def ydata(self):
"""Return ydata (means and std devs)."""
return self._ydata
@property
def fit(self):
"""Return fit."""
return self._fit
@property
def seeds(self):
"""Return the number of loaded seeds."""
return self._nseeds
@property
def results(self):
"""Return all the results."""
return self._result_list
def add_data(self, new_backend_result, rerun_fit=True):
"""
Add a new result. Re calculate the raw data, means and
fit.
Args:
new_backend_result: list of rb results
rerun_fit: re caculate the means and fit the result
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
if new_backend_result is None:
return
if not isinstance(new_backend_result, list):
new_backend_result = [new_backend_result]
for result in new_backend_result:
self._result_list.append(result)
# update the number of seeds *if* new ones
# added. Note, no checking if we've done all the
# cliffords
for rbcirc in result.results:
nseeds_circ = int(rbcirc.header.name.split('_')[-1])
if (nseeds_circ+1) > self._nseeds:
self._nseeds = nseeds_circ+1
for result in self._result_list:
if not len(result.results) == len(self._cliff_lengths[0]):
raise ValueError(
"The number of clifford lengths must match the number of "
"results")
if rerun_fit:
self.calc_data()
self.calc_statistics()
self.fit_data()
@staticmethod
def _rb_fit_fun(x, a, alpha, b):
"""Function used to fit rb."""
# pylint: disable=invalid-name
return a * alpha ** x + b
def calc_data(self):
"""
Retrieve probabilities of success from execution results. Outputs
results into an internal variable _raw_data which is a 3-dimensional
list, where item (i,j,k) is the probability to measure the ground state
for the set of qubits in pattern "i" for seed no. j and vector length
self._cliff_lengths[i][k].
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
circ_counts = {}
circ_shots = {}
for seedidx in range(self._nseeds):
for circ, _ in enumerate(self._cliff_lengths[0]):
circ_name = 'rb_length_%d_seed_%d' % (circ, seedidx)
count_list = []
for result in self._result_list:
try:
count_list.append(result.get_counts(circ_name))
except (QiskitError, KeyError):
pass
circ_counts[circ_name] = \
build_counts_dict_from_list(count_list)
circ_shots[circ_name] = sum(circ_counts[circ_name].values())
self._raw_data = []
startind = 0
for patt_ind in range(len(self._rb_pattern)):
string_of_0s = ''
string_of_0s = string_of_0s.zfill(len(self._rb_pattern[patt_ind]))
self._raw_data.append([])
endind = startind+len(self._rb_pattern[patt_ind])
for i in range(self._nseeds):
self._raw_data[-1].append([])
for k, _ in enumerate(self._cliff_lengths[patt_ind]):
circ_name = 'rb_length_%d_seed_%d' % (k, i)
counts_subspace = marginal_counts(
circ_counts[circ_name],
np.arange(startind, endind))
self._raw_data[-1][i].append(
counts_subspace.get(string_of_0s, 0)
/ circ_shots[circ_name])
startind += (endind)
def calc_statistics(self):
"""
Extract averages and std dev from the raw data (self._raw_data).
Assumes that self._calc_data has been run. Output into internal
_ydata variable:
ydata is a list of dictionaries (length number of patterns).
Dictionary ydata[i]:
ydata[i]['mean'] is a numpy_array of length n;
entry j of this array contains the mean probability of
success over seeds, for vector length
self._cliff_lengths[i][j].
And ydata[i]['std'] is a numpy_array of length n;
entry j of this array contains the std
of the probability of success over seeds,
for vector length self._cliff_lengths[i][j].
"""
self._ydata = []
for patt_ind in range(len(self._rb_pattern)):
self._ydata.append({})
self._ydata[-1]['mean'] = np.mean(self._raw_data[patt_ind], 0)
if len(self._raw_data[patt_ind]) == 1: # 1 seed
self._ydata[-1]['std'] = None
else:
self._ydata[-1]['std'] = np.std(self._raw_data[patt_ind], 0)
def fit_data(self):
"""
Fit the RB results to an exponential curve.
Fit each of the patterns
Puts the results into a list of fit dictionaries:
where each dictionary corresponds to a pattern and has fields:
'params' - three parameters of rb_fit_fun. The middle one is the
exponent.
'err' - the error limits of the parameters.
'epc' - error per Clifford
"""
self._fit = []
for patt_ind, (lens, qubits) in enumerate(zip(self._cliff_lengths,
self._rb_pattern)):
# if at least one of the std values is zero, then sigma is replaced
# by None
if not self._ydata[patt_ind]['std'] is None:
sigma = self._ydata[patt_ind]['std'].copy()
if len(sigma) - np.count_nonzero(sigma) > 0:
sigma = None
else:
sigma = None
params, pcov = curve_fit(self._rb_fit_fun, lens,
self._ydata[patt_ind]['mean'],
sigma=sigma,
p0=(1.0, 0.95, 0.0),
bounds=([-2, 0, -2], [2, 1, 2]))
alpha = params[1] # exponent
params_err = np.sqrt(np.diag(pcov))
alpha_err = params_err[1]
nrb = 2 ** len(qubits)
epc = (nrb-1)/nrb*(1-alpha)
epc_err = epc*alpha_err/alpha
self._fit.append({'params': params, 'params_err': params_err,
'epc': epc, 'epc_err': epc_err})
def plot_rb_data(self, pattern_index=0, ax=None,
add_label=True, show_plt=True):
"""
Plot randomized benchmarking data of a single pattern.
Args:
pattern_index: which RB pattern to plot
ax (Axes or None): plot axis (if passed in).
add_label (bool): Add an EPC label
show_plt (bool): display the plot.
Raises:
ImportError: If matplotlib is not installed.
"""
fit_function = self._rb_fit_fun
if not HAS_MATPLOTLIB:
raise ImportError('The function plot_rb_data needs matplotlib. '
'Run "pip install matplotlib" before.')
if ax is None:
plt.figure()
ax = plt.gca()
xdata = self._cliff_lengths[pattern_index]
# Plot the result for each sequence
for one_seed_data in self._raw_data[pattern_index]:
ax.plot(xdata, one_seed_data, color='gray', linestyle='none',
marker='x')
# Plot the mean with error bars
ax.errorbar(xdata, self._ydata[pattern_index]['mean'],
yerr=self._ydata[pattern_index]['std'],
color='r', linestyle='--', linewidth=3)
# Plot the fit
ax.plot(xdata,
fit_function(xdata, *self._fit[pattern_index]['params']),
color='blue', linestyle='-', linewidth=2)
ax.tick_params(labelsize=14)
ax.set_xlabel('Clifford Length', fontsize=16)
ax.set_ylabel('Ground State Population', fontsize=16)
ax.grid(True)
if add_label:
bbox_props = dict(boxstyle="round,pad=0.3",
fc="white", ec="black", lw=2)
ax.text(0.6, 0.9,
"alpha: %.3f(%.1e) EPC: %.3e(%.1e)" %
(self._fit[pattern_index]['params'][1],
self._fit[pattern_index]['params_err'][1],
self._fit[pattern_index]['epc'],
self._fit[pattern_index]['epc_err']),
ha="center", va="center", size=14,
bbox=bbox_props, transform=ax.transAxes)
if show_plt:
plt.show()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Functions used for the analysis of randomized benchmarking results.
"""
from scipy.optimize import curve_fit
import numpy as np
from qiskit import QiskitError
from ..tomography import marginal_counts
from ...characterization.fitters import build_counts_dict_from_list
try:
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
class RBFitter:
"""
Class for fitters for randomized benchmarking
"""
def __init__(self, backend_result, cliff_lengths,
rb_pattern=None):
"""
Args:
backend_result: list of results (qiskit.Result).
cliff_lengths: the Clifford lengths, 2D list i x j where i is the
number of patterns, j is the number of cliffords lengths
rb_pattern: the pattern for the rb sequences.
"""
if rb_pattern is None:
rb_pattern = [[0]]
self._cliff_lengths = cliff_lengths
self._rb_pattern = rb_pattern
self._raw_data = []
self._ydata = []
self._fit = []
self._nseeds = 0
self._result_list = []
self.add_data(backend_result)
@property
def raw_data(self):
"""Return raw data."""
return self._raw_data
@property
def cliff_lengths(self):
"""Return clifford lengths."""
return self.cliff_lengths
@property
def ydata(self):
"""Return ydata (means and std devs)."""
return self._ydata
@property
def fit(self):
"""Return fit."""
return self._fit
@property
def seeds(self):
"""Return the number of loaded seeds."""
return self._nseeds
@property
def results(self):
"""Return all the results."""
return self._result_list
def add_data(self, new_backend_result, rerun_fit=True):
"""
Add a new result. Re calculate the raw data, means and
fit.
Args:
new_backend_result: list of rb results
rerun_fit: re caculate the means and fit the result
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
if new_backend_result is None:
return
if not isinstance(new_backend_result, list):
new_backend_result = [new_backend_result]
for result in new_backend_result:
self._result_list.append(result)
# update the number of seeds *if* new ones
# added. Note, no checking if we've done all the
# cliffords
for rbcirc in result.results:
nseeds_circ = int(rbcirc.header.name.split('_')[-1])
if (nseeds_circ+1) > self._nseeds:
self._nseeds = nseeds_circ+1
for result in self._result_list:
if not len(result.results) == len(self._cliff_lengths[0]):
raise ValueError(
"The number of clifford lengths must match the number of "
"results")
if rerun_fit:
self.calc_data()
self.calc_statistics()
self.fit_data()
@staticmethod
def _rb_fit_fun(x, a, alpha, b):
"""Function used to fit rb."""
# pylint: disable=invalid-name
return a * alpha ** x + b
def calc_data(self):
"""
Retrieve probabilities of success from execution results. Outputs
results into an internal variable _raw_data which is a 3-dimensional
list, where item (i,j,k) is the probability to measure the ground state
for the set of qubits in pattern "i" for seed no. j and vector length
self._cliff_lengths[i][k].
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
circ_counts = {}
circ_shots = {}
for seedidx in range(self._nseeds):
for circ, _ in enumerate(self._cliff_lengths[0]):
circ_name = 'rb_length_%d_seed_%d' % (circ, seedidx)
count_list = []
for result in self._result_list:
try:
count_list.append(result.get_counts(circ_name))
except (QiskitError, KeyError):
pass
circ_counts[circ_name] = \
build_counts_dict_from_list(count_list)
circ_shots[circ_name] = sum(circ_counts[circ_name].values())
self._raw_data = []
startind = 0
for patt_ind in range(len(self._rb_pattern)):
string_of_0s = ''
string_of_0s = string_of_0s.zfill(len(self._rb_pattern[patt_ind]))
self._raw_data.append([])
endind = startind+len(self._rb_pattern[patt_ind])
for i in range(self._nseeds):
self._raw_data[-1].append([])
for k, _ in enumerate(self._cliff_lengths[patt_ind]):
circ_name = 'rb_length_%d_seed_%d' % (k, i)
counts_subspace = marginal_counts(
circ_counts[circ_name],
np.arange(startind, endind))
self._raw_data[-1][i].append(
counts_subspace.get(string_of_0s, 0)
/ circ_shots[circ_name])
startind += (endind)
def calc_statistics(self):
"""
Extract averages and std dev from the raw data (self._raw_data).
Assumes that self._calc_data has been run. Output into internal
_ydata variable:
ydata is a list of dictionaries (length number of patterns).
Dictionary ydata[i]:
ydata[i]['mean'] is a numpy_array of length n;
entry j of this array contains the mean probability of
success over seeds, for vector length
self._cliff_lengths[i][j].
And ydata[i]['std'] is a numpy_array of length n;
entry j of this array contains the std
of the probability of success over seeds,
for vector length self._cliff_lengths[i][j].
"""
self._ydata = []
for patt_ind in range(len(self._rb_pattern)):
self._ydata.append({})
self._ydata[-1]['mean'] = np.mean(self._raw_data[patt_ind], 0)
if len(self._raw_data[patt_ind]) == 1: # 1 seed
self._ydata[-1]['std'] = None
else:
self._ydata[-1]['std'] = np.std(self._raw_data[patt_ind], 0)
def fit_data(self):
"""
Fit the RB results to an exponential curve.
Fit each of the patterns
Puts the results into a list of fit dictionaries:
where each dictionary corresponds to a pattern and has fields:
'params' - three parameters of rb_fit_fun. The middle one is the
exponent.
'err' - the error limits of the parameters.
'epc' - error per Clifford
"""
self._fit = []
for patt_ind, (lens, qubits) in enumerate(zip(self._cliff_lengths,
self._rb_pattern)):
# if at least one of the std values is zero, then sigma is replaced
# by None
if not self._ydata[patt_ind]['std'] is None:
sigma = self._ydata[patt_ind]['std'].copy()
if len(sigma) - np.count_nonzero(sigma) > 0:
sigma = None
else:
sigma = None
params, pcov = curve_fit(self._rb_fit_fun, lens,
self._ydata[patt_ind]['mean'],
sigma=sigma,
p0=(1.0, 0.95, 0.0),
bounds=([-2, 0, -2], [2, 1, 2]))
alpha = params[1] # exponent
params_err = np.sqrt(np.diag(pcov))
alpha_err = params_err[1]
nrb = 2 ** len(qubits)
epc = (nrb-1)/nrb*(1-alpha)
epc_err = epc*alpha_err/alpha
self._fit.append({'params': params, 'params_err': params_err,
'epc': epc, 'epc_err': epc_err})
def plot_rb_data(self, pattern_index=0, ax=None,
add_label=True, show_plt=True):
"""
Plot randomized benchmarking data of a single pattern.
Args:
pattern_index: which RB pattern to plot
ax (Axes or None): plot axis (if passed in).
add_label (bool): Add an EPC label
show_plt (bool): display the plot.
Raises:
ImportError: If matplotlib is not installed.
"""
fit_function = self._rb_fit_fun
if not HAS_MATPLOTLIB:
raise ImportError('The function plot_rb_data needs matplotlib. '
'Run "pip install matplotlib" before.')
if ax is None:
plt.figure()
ax = plt.gca()
xdata = self._cliff_lengths[pattern_index]
# Plot the result for each sequence
for one_seed_data in self._raw_data[pattern_index]:
ax.plot(xdata, one_seed_data, color='gray', linestyle='none',
marker='x')
# Plot the mean with error bars
ax.errorbar(xdata, self._ydata[pattern_index]['mean'],
yerr=self._ydata[pattern_index]['std'],
color='r', linestyle='--', linewidth=3)
# Plot the fit
ax.plot(xdata,
fit_function(xdata, *self._fit[pattern_index]['params']),
color='blue', linestyle='-', linewidth=2)
ax.tick_params(labelsize=14)
ax.set_xlabel('Clifford Length', fontsize=16)
ax.set_ylabel('Ground State Population', fontsize=16)
ax.grid(True)
if add_label:
bbox_props = dict(boxstyle="round,pad=0.3",
fc="white", ec="black", lw=2)
ax.text(0.6, 0.9,
"alpha: %.3f(%.1e) EPC: %.3e(%.1e)" %
(self._fit[pattern_index]['params'][1],
self._fit[pattern_index]['params_err'][1],
self._fit[pattern_index]['epc'],
self._fit[pattern_index]['epc_err']),
ha="center", va="center", size=14,
bbox=bbox_props, transform=ax.transAxes)
if show_plt:
plt.show()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Advanced Clifford operations needed for randomized benchmarking
"""
import numpy as np
import qiskit
from . import Clifford
try:
import cPickle as pickle
except ImportError:
import pickle
# ----------------------------------------------------------------------------------------
# Functions that convert to/from a Clifford object
# ----------------------------------------------------------------------------------------
def compose_gates(cliff, gatelist):
"""
Add gates to a Clifford object from a list of gates.
Args:
cliff: A Clifford class object.
gatelist: a list of gates.
Returns:
A Clifford class object.
"""
for op in gatelist:
split = op.split()
q1 = int(split[1])
if split[0] == 'v':
cliff.v(q1)
elif split[0] == 'w':
cliff.w(q1)
elif split[0] == 'x':
cliff.x(q1)
elif split[0] == 'y':
cliff.y(q1)
elif split[0] == 'z':
cliff.z(q1)
elif split[0] == 'cx':
cliff.cx(q1, int(split[2]))
elif split[0] == 'h':
cliff.h(q1)
elif split[0] == 's':
cliff.s(q1)
elif split[0] == 'sdg':
cliff.sdg(q1)
else:
raise ValueError("Unknown gate type: ", op)
return cliff
def clifford_from_gates(num_qubits, gatelist):
"""
Generates a Clifford object from a list of gates.
Args:
num_qubits: the number of qubits for the Clifford.
gatelist: a list of gates.
Returns:
A num-qubit Clifford class object.
"""
cliff = Clifford(num_qubits)
new_cliff = compose_gates(cliff, gatelist)
return new_cliff
# --------------------------------------------------------
# Add gates to Cliffords
# --------------------------------------------------------
def pauli_gates(gatelist, q, pauli):
"""adds a pauli gate on qubit q"""
if pauli == 2:
gatelist.append('x ' + str(q))
elif pauli == 3:
gatelist.append('y ' + str(q))
elif pauli == 1:
gatelist.append('z ' + str(q))
def h_gates(gatelist, q, h):
"""adds a hadamard gate or not on qubit q"""
if h == 1:
gatelist.append('h ' + str(q))
def v_gates(gatelist, q, v):
"""adds an axis-swap-gates on qubit q"""
# rotation is V=HSHS = [[0,1],[1,1]] tableau
# takes Z->X->Y->Z
# V is of order 3, and two V-gates is W-gate, so: W=VV and WV=I
if v == 1:
gatelist.append('v ' + str(q))
elif v == 2:
gatelist.append('w ' + str(q))
def cx_gates(gatelist, ctrl, tgt):
"""adds a controlled=x gates"""
gatelist.append('cx ' + str(ctrl) + ' ' + str(tgt))
# --------------------------------------------------------
# Create a 1 or 2 Qubit Clifford based on a unique index
# --------------------------------------------------------
def clifford1_gates(idx: int):
"""
Make a single qubit Clifford gate.
Args:
idx: the index (mod 24) of a single qubit Clifford.
Returns:
A single qubit Clifford gate.
"""
gatelist = []
# Cannonical Ordering of Cliffords 0,...,23
cannonicalorder = idx % 24
pauli = np.mod(cannonicalorder, 4)
rotation = np.mod(cannonicalorder // 4, 3)
h_or_not = np.mod(cannonicalorder // 12, 2)
h_gates(gatelist, 0, h_or_not)
v_gates(gatelist, 0, rotation) # do the R-gates
pauli_gates(gatelist, 0, pauli)
return gatelist
def clifford2_gates(idx: int):
"""
Make a 2-qubit Clifford gate.
Args:
idx: the index (mod 11520) of a two-qubit Clifford.
Returns:
A 2-qubit Clifford gate.
"""
gatelist = []
cannon = idx % 11520
pauli = np.mod(cannon, 16)
symp = cannon // 16
if symp < 36: # 1-qubit Cliffords Class
r0 = np.mod(symp, 3)
r1 = np.mod(symp // 3, 3)
h0 = np.mod(symp // 9, 2)
h1 = np.mod(symp // 18, 2)
h_gates(gatelist, 0, h0)
h_gates(gatelist, 1, h1)
v_gates(gatelist, 0, r0)
v_gates(gatelist, 1, r1)
elif symp < 360: # CNOT-like Class
symp = symp - 36
r0 = np.mod(symp, 3)
r1 = np.mod(symp // 3, 3)
r2 = np.mod(symp // 9, 3)
r3 = np.mod(symp // 27, 3)
h0 = np.mod(symp // 81, 2)
h1 = np.mod(symp // 162, 2)
h_gates(gatelist, 0, h0)
h_gates(gatelist, 1, h1)
v_gates(gatelist, 0, r0)
v_gates(gatelist, 1, r1)
cx_gates(gatelist, 0, 1)
v_gates(gatelist, 0, r2)
v_gates(gatelist, 1, r3)
elif symp < 684: # iSWAP-like Class
symp = symp - 360
r0 = np.mod(symp, 3)
r1 = np.mod(symp // 3, 3)
r2 = np.mod(symp // 9, 3)
r3 = np.mod(symp // 27, 3)
h0 = np.mod(symp // 81, 2)
h1 = np.mod(symp // 162, 2)
h_gates(gatelist, 0, h0)
h_gates(gatelist, 1, h1)
v_gates(gatelist, 0, r0)
v_gates(gatelist, 1, r1)
cx_gates(gatelist, 0, 1)
cx_gates(gatelist, 1, 0)
v_gates(gatelist, 0, r2)
v_gates(gatelist, 1, r3)
else: # SWAP Class
symp = symp - 684
r0 = np.mod(symp, 3)
r1 = np.mod(symp // 3, 3)
h0 = np.mod(symp // 9, 2)
h1 = np.mod(symp // 18, 2)
h_gates(gatelist, 0, h0)
h_gates(gatelist, 1, h1)
v_gates(gatelist, 0, r0)
v_gates(gatelist, 1, r1)
cx_gates(gatelist, 0, 1)
cx_gates(gatelist, 1, 0)
cx_gates(gatelist, 0, 1)
pauli_gates(gatelist, 0, np.mod(pauli, 4))
pauli_gates(gatelist, 1, pauli // 4)
return gatelist
# --------------------------------------------------------
# Create a 1 or 2 Qubit Clifford tables
# --------------------------------------------------------
def clifford2_gates_table():
"""
Generate a table of all 2-qubit Clifford gates.
Args:
None.
Returns:
A table of all 2-qubit Clifford gates.
"""
cliffords2 = {}
for i in range(11520):
circ = clifford2_gates(i)
key = clifford_from_gates(2, circ).index()
cliffords2[key] = circ
return cliffords2
def clifford1_gates_table():
"""
Generate a table of all 1-qubit Clifford gates.
Args:
None.
Returns:
A table of all 1-qubit Clifford gates.
"""
cliffords1 = {}
for i in range(24):
circ = clifford1_gates(i)
key = clifford_from_gates(1, circ).index()
cliffords1[key] = circ
return cliffords1
def pickle_clifford_table(picklefile='cliffords2.pickle', num_qubits=2):
"""
Create pickled versions of the 1 and 2 qubit Clifford tables.
Args:
picklefile - pickle file name.
num_qubits - number of qubits.
Returns:
A pickle file with the 1 and 2 qubit Clifford tables.
"""
cliffords = {}
if num_qubits == 1:
cliffords = clifford1_gates_table()
elif num_qubits == 2:
cliffords = clifford2_gates_table()
else:
raise ValueError(
"number of qubits bigger than is not supported for pickle")
with open(picklefile, "wb") as pf:
pickle.dump(cliffords, pf)
def load_clifford_table(picklefile='cliffords2.pickle'):
"""
Load pickled files of the tables of 1 and 2 qubit Clifford tables.
Args:
picklefile - pickle file name.
Returns:
A table of 1 and 2 qubit Clifford gates.
"""
with open(picklefile, "rb") as pf:
return pickle.load(pf)
# --------------------------------------------------------
# Main function that generates a random clifford gate
# --------------------------------------------------------
def random_clifford_gates(num_qubits):
"""
Pick a random Clifford gate.
Args:
num_qubits: dimension of the Clifford.
Returns:
A 1 or 2 qubit Clifford gate.
"""
if num_qubits == 1:
return clifford1_gates(np.random.randint(0, 24))
if num_qubits == 2:
return clifford2_gates(np.random.randint(0, 11520))
raise ValueError("The number of qubits should be only 1 or 2")
# --------------------------------------------------------
# Main function that calculates an inverse of a clifford gate
# --------------------------------------------------------
def find_inverse_clifford_gates(num_qubits, gatelist):
"""
Find the inverse of a Clifford gate.
Args:
num_qubits: the dimension of the Clifford.
gatelist: a Clifford gate.
Returns:
An inverse Clifford gate.
"""
if num_qubits in (1, 2):
inv_gatelist = gatelist.copy()
inv_gatelist.reverse()
# replace v by w and w by v
for i, _ in enumerate(inv_gatelist):
split = inv_gatelist[i].split()
if split[0] == 'v':
inv_gatelist[i] = 'w ' + split[1]
elif split[0] == 'w':
inv_gatelist[i] = 'v ' + split[1]
return inv_gatelist
raise ValueError("The number of qubits should be only 1 or 2")
# --------------------------------------------------------
# Returns the Clifford circuit in the form of a QuantumCircuit object
# --------------------------------------------------------
def get_quantum_circuit(gatelist, num_qubits):
"""
Returns the Clifford circuit in the form of a QuantumCircuit object.
Args:
num_qubits: the dimension of the Clifford.
gatelist: a Clifford gate.
Returns:
A QuantumCircuit object.
"""
qr = qiskit.QuantumRegister(num_qubits)
qc = qiskit.QuantumCircuit(qr)
for op in gatelist:
split = op.split()
op_names = [split[0]]
# temporary correcting the ops name since QuantumCircuit has no
# attributes 'v' or 'w' yet:
if op_names == ['v']:
op_names = ['sdg', 'h']
elif op_names == ['w']:
op_names = ['h', 's']
qubits = [qr[int(x)] for x in split[1:]]
for sub_op in op_names:
operation = eval('qiskit.QuantumCircuit.' + sub_op)
operation(qc, *qubits)
return qc
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Functions used for the analysis of randomized benchmarking results.
"""
from scipy.optimize import curve_fit
import numpy as np
from qiskit import QiskitError
from ..tomography import marginal_counts
from ...characterization.fitters import build_counts_dict_from_list
try:
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
class RBFitter:
"""
Class for fitters for randomized benchmarking
"""
def __init__(self, backend_result, cliff_lengths,
rb_pattern=None):
"""
Args:
backend_result: list of results (qiskit.Result).
cliff_lengths: the Clifford lengths, 2D list i x j where i is the
number of patterns, j is the number of cliffords lengths
rb_pattern: the pattern for the rb sequences.
"""
if rb_pattern is None:
rb_pattern = [[0]]
self._cliff_lengths = cliff_lengths
self._rb_pattern = rb_pattern
self._raw_data = []
self._ydata = []
self._fit = []
self._nseeds = 0
self._result_list = []
self.add_data(backend_result)
@property
def raw_data(self):
"""Return raw data."""
return self._raw_data
@property
def cliff_lengths(self):
"""Return clifford lengths."""
return self.cliff_lengths
@property
def ydata(self):
"""Return ydata (means and std devs)."""
return self._ydata
@property
def fit(self):
"""Return fit."""
return self._fit
@property
def seeds(self):
"""Return the number of loaded seeds."""
return self._nseeds
@property
def results(self):
"""Return all the results."""
return self._result_list
def add_data(self, new_backend_result, rerun_fit=True):
"""
Add a new result. Re calculate the raw data, means and
fit.
Args:
new_backend_result: list of rb results
rerun_fit: re caculate the means and fit the result
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
if new_backend_result is None:
return
if not isinstance(new_backend_result, list):
new_backend_result = [new_backend_result]
for result in new_backend_result:
self._result_list.append(result)
# update the number of seeds *if* new ones
# added. Note, no checking if we've done all the
# cliffords
for rbcirc in result.results:
nseeds_circ = int(rbcirc.header.name.split('_')[-1])
if (nseeds_circ+1) > self._nseeds:
self._nseeds = nseeds_circ+1
for result in self._result_list:
if not len(result.results) == len(self._cliff_lengths[0]):
raise ValueError(
"The number of clifford lengths must match the number of "
"results")
if rerun_fit:
self.calc_data()
self.calc_statistics()
self.fit_data()
@staticmethod
def _rb_fit_fun(x, a, alpha, b):
"""Function used to fit rb."""
# pylint: disable=invalid-name
return a * alpha ** x + b
def calc_data(self):
"""
Retrieve probabilities of success from execution results. Outputs
results into an internal variable _raw_data which is a 3-dimensional
list, where item (i,j,k) is the probability to measure the ground state
for the set of qubits in pattern "i" for seed no. j and vector length
self._cliff_lengths[i][k].
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
circ_counts = {}
circ_shots = {}
for seedidx in range(self._nseeds):
for circ, _ in enumerate(self._cliff_lengths[0]):
circ_name = 'rb_length_%d_seed_%d' % (circ, seedidx)
count_list = []
for result in self._result_list:
try:
count_list.append(result.get_counts(circ_name))
except (QiskitError, KeyError):
pass
circ_counts[circ_name] = \
build_counts_dict_from_list(count_list)
circ_shots[circ_name] = sum(circ_counts[circ_name].values())
self._raw_data = []
startind = 0
for patt_ind in range(len(self._rb_pattern)):
string_of_0s = ''
string_of_0s = string_of_0s.zfill(len(self._rb_pattern[patt_ind]))
self._raw_data.append([])
endind = startind+len(self._rb_pattern[patt_ind])
for i in range(self._nseeds):
self._raw_data[-1].append([])
for k, _ in enumerate(self._cliff_lengths[patt_ind]):
circ_name = 'rb_length_%d_seed_%d' % (k, i)
counts_subspace = marginal_counts(
circ_counts[circ_name],
np.arange(startind, endind))
self._raw_data[-1][i].append(
counts_subspace.get(string_of_0s, 0)
/ circ_shots[circ_name])
startind += (endind)
def calc_statistics(self):
"""
Extract averages and std dev from the raw data (self._raw_data).
Assumes that self._calc_data has been run. Output into internal
_ydata variable:
ydata is a list of dictionaries (length number of patterns).
Dictionary ydata[i]:
ydata[i]['mean'] is a numpy_array of length n;
entry j of this array contains the mean probability of
success over seeds, for vector length
self._cliff_lengths[i][j].
And ydata[i]['std'] is a numpy_array of length n;
entry j of this array contains the std
of the probability of success over seeds,
for vector length self._cliff_lengths[i][j].
"""
self._ydata = []
for patt_ind in range(len(self._rb_pattern)):
self._ydata.append({})
self._ydata[-1]['mean'] = np.mean(self._raw_data[patt_ind], 0)
if len(self._raw_data[patt_ind]) == 1: # 1 seed
self._ydata[-1]['std'] = None
else:
self._ydata[-1]['std'] = np.std(self._raw_data[patt_ind], 0)
def fit_data(self):
"""
Fit the RB results to an exponential curve.
Fit each of the patterns
Puts the results into a list of fit dictionaries:
where each dictionary corresponds to a pattern and has fields:
'params' - three parameters of rb_fit_fun. The middle one is the
exponent.
'err' - the error limits of the parameters.
'epc' - error per Clifford
"""
self._fit = []
for patt_ind, (lens, qubits) in enumerate(zip(self._cliff_lengths,
self._rb_pattern)):
# if at least one of the std values is zero, then sigma is replaced
# by None
if not self._ydata[patt_ind]['std'] is None:
sigma = self._ydata[patt_ind]['std'].copy()
if len(sigma) - np.count_nonzero(sigma) > 0:
sigma = None
else:
sigma = None
params, pcov = curve_fit(self._rb_fit_fun, lens,
self._ydata[patt_ind]['mean'],
sigma=sigma,
p0=(1.0, 0.95, 0.0),
bounds=([-2, 0, -2], [2, 1, 2]))
alpha = params[1] # exponent
params_err = np.sqrt(np.diag(pcov))
alpha_err = params_err[1]
nrb = 2 ** len(qubits)
epc = (nrb-1)/nrb*(1-alpha)
epc_err = epc*alpha_err/alpha
self._fit.append({'params': params, 'params_err': params_err,
'epc': epc, 'epc_err': epc_err})
def plot_rb_data(self, pattern_index=0, ax=None,
add_label=True, show_plt=True):
"""
Plot randomized benchmarking data of a single pattern.
Args:
pattern_index: which RB pattern to plot
ax (Axes or None): plot axis (if passed in).
add_label (bool): Add an EPC label
show_plt (bool): display the plot.
Raises:
ImportError: If matplotlib is not installed.
"""
fit_function = self._rb_fit_fun
if not HAS_MATPLOTLIB:
raise ImportError('The function plot_rb_data needs matplotlib. '
'Run "pip install matplotlib" before.')
if ax is None:
plt.figure()
ax = plt.gca()
xdata = self._cliff_lengths[pattern_index]
# Plot the result for each sequence
for one_seed_data in self._raw_data[pattern_index]:
ax.plot(xdata, one_seed_data, color='gray', linestyle='none',
marker='x')
# Plot the mean with error bars
ax.errorbar(xdata, self._ydata[pattern_index]['mean'],
yerr=self._ydata[pattern_index]['std'],
color='r', linestyle='--', linewidth=3)
# Plot the fit
ax.plot(xdata,
fit_function(xdata, *self._fit[pattern_index]['params']),
color='blue', linestyle='-', linewidth=2)
ax.tick_params(labelsize=14)
ax.set_xlabel('Clifford Length', fontsize=16)
ax.set_ylabel('Ground State Population', fontsize=16)
ax.grid(True)
if add_label:
bbox_props = dict(boxstyle="round,pad=0.3",
fc="white", ec="black", lw=2)
ax.text(0.6, 0.9,
"alpha: %.3f(%.1e) EPC: %.3e(%.1e)" %
(self._fit[pattern_index]['params'][1],
self._fit[pattern_index]['params_err'][1],
self._fit[pattern_index]['epc'],
self._fit[pattern_index]['epc_err']),
ha="center", va="center", size=14,
bbox=bbox_props, transform=ax.transAxes)
if show_plt:
plt.show()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Pauli tomography preparation and measurement basis
"""
# Needed for functions
import numpy as np
# Import QISKit classes
from qiskit import QuantumCircuit
from .tomographybasis import TomographyBasis
###########################################################################
# Built-in circuit functions
###########################################################################
def pauli_measurement_circuit(op, qubit, clbit):
"""
Return a qubit Pauli operator measurement circuit.
Params:
op (str): Pauli operator 'X', 'Y', 'Z'.
qubit (QuantumRegister tuple): qubit to be measured.
clbit (ClassicalRegister tuple): clbit for measurement outcome.
Returns:
A QuantumCircuit object.
"""
circ = QuantumCircuit(qubit[0], clbit[0])
if op == 'X':
circ.h(qubit)
circ.measure(qubit, clbit)
if op == 'Y':
circ.sdg(qubit)
circ.h(qubit)
circ.measure(qubit, clbit)
if op == 'Z':
circ.measure(qubit, clbit)
return circ
def pauli_preparation_circuit(op, qubit):
"""
Return a qubit Pauli eigenstate preparation circuit.
This circuit assumes the qubit is initialized in the Zp eigenstate [1, 0].
Params:
op (str): Pauli eigenstate 'Zp', 'Zm', 'Xp', 'Xm', 'Yp', or 'Ym'.
qubit (QuantumRegister tuple): qubit to be prepared.
Returns:
A QuantumCircuit object.
"""
circ = QuantumCircuit(qubit[0])
if op == 'Xp':
circ.h(qubit)
if op == 'Xm':
circ.x(qubit)
circ.h(qubit)
if op == 'Yp':
circ.h(qubit)
circ.s(qubit)
if op == 'Ym':
circ.x(qubit)
circ.h(qubit)
circ.s(qubit)
if op == 'Zm':
circ.x(qubit)
return circ
###########################################################################
# Matrix functions for built-in bases
###########################################################################
def pauli_preparation_matrix(label):
"""
Return the matrix corresonding to a Pauli eigenstate preparation.
Args:
label (str): single-qubit Pauli eigenstate operator label.
Returns:
numpy.array: A Numpy array for the Pauli eigenstate. Allowed inputs
and corresponding returned matrices are:
'Xp' : [[1, 1], [1, 1]] / sqrt(2)
'Xm' : [[1, -1], [1, -1]] / sqrt(2)
'Yp' : [[1, -1j], [1j, 1]] / sqrt(2)
'Ym' : [[1, 1j], [-1j, 1]] / sqrt(2)
'Zp' : [[1, 0], [0, 0]]
'Zm' : [[0, 0], [0, 1]]
"""
res = np.array([])
# Return matrix for allowed label
if label == 'Xp':
res = np.array([[0.5, 0.5], [0.5, 0.5]], dtype=complex)
if label == 'Xm':
res = np.array([[0.5, -0.5], [-0.5, 0.5]], dtype=complex)
if label == 'Yp':
res = np.array([[0.5, -0.5j], [0.5j, 0.5]], dtype=complex)
if label == 'Ym':
res = np.array([[0.5, 0.5j], [-0.5j, 0.5]], dtype=complex)
if label == 'Zp':
res = np.array([[1, 0], [0, 0]], dtype=complex)
if label == 'Zm':
res = np.array([[0, 0], [0, 1]], dtype=complex)
return res
def pauli_measurement_matrix(label, outcome):
"""
Return the matrix corresonding to a Pauli measurement outcome.
Args:
label (str): single-qubit Pauli measurement operator label.
outcome (int): measurement outcome.
Returns:
numpy.array: A Numpy array for measurement outcome operator.
Allowed inputs and corresponding returned matrices are:
'X', 0 : [[1, 1], [1, 1]] / sqrt(2)
'X', 1 : [[1, -1], [1, -1]] / sqrt(2)
'Y', 0 : [[1, -1j], [1j, 1]] / sqrt(2)
'Y', 1 : [[1, 1j], [-1j, 1]] / sqrt(2)
'Z', 0 : [[1, 0], [0, 0]]
'Z', 1 : [[0, 0], [0, 1]]
"""
res = np.array([])
# Return matrix
if label == 'X':
if outcome in ['0', 0]:
res = pauli_preparation_matrix('Xp')
if outcome in ['1', 1]:
res = pauli_preparation_matrix('Xm')
if label == 'Y':
if outcome in ['0', 0]:
res = pauli_preparation_matrix('Yp')
if outcome in ['1', 1]:
res = pauli_preparation_matrix('Ym')
if label == 'Z':
if outcome in ['0', 0]:
res = pauli_preparation_matrix('Zp')
if outcome in ['1', 1]:
res = pauli_preparation_matrix('Zm')
return res
###########################################################################
# PauliBasis Object
###########################################################################
PauliBasis = TomographyBasis('Pauli',
measurement=(('X', 'Y', 'Z'),
pauli_measurement_circuit,
pauli_measurement_matrix),
preparation=(('Xp', 'Xm', 'Yp', 'Ym', 'Zp', 'Zm'),
pauli_preparation_circuit,
pauli_preparation_matrix))
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Symmetric informationally complete (SIC)-POVM tomography preparation basis.
"""
# Needed for functions
import numpy as np
# Import QISKit classes
from qiskit import QuantumCircuit
from .tomographybasis import TomographyBasis
###########################################################################
# Built-in circuit functions
###########################################################################
def sicpovm_preparation_circuit(op, qubit):
"""
Return a SIC-POVM projector preparation circuit.
This circuit assumes the qubit is initialized in the Zp eigenstate [1, 0].
Params:
op (str): SIC-POVM element label 'S0', 'S1', 'S2' or 'S3'.
qubit (QuantumRegister tuple): qubit to be prepared.
Returns:
A QuantumCircuit object.
"""
circ = QuantumCircuit(qubit[0])
theta = -2 * np.arctan(np.sqrt(2))
if op == 'S1':
circ.u3(theta, np.pi, 0.0, qubit)
if op == 'S2':
circ.u3(theta, np.pi / 3, 0.0, qubit)
if op == 'S3':
circ.u3(theta, -np.pi / 3, 0.0, qubit)
return circ
###########################################################################
# Matrix functions for built-in bases
###########################################################################
def sicpovm_preparation_matrix(label):
"""
Return the matrix corresonding to a SIC-POVM preparation.
Args:
label (str): single-qubit SIC-POVM element label.
Returns:
A Numpy array for the SIC-POVM element.
Allowed inputs and corresponding returned matrices are:
'S0' : [[1, 0], [0, 0]]
'S1' : [[1, np.sqrt(2)], [np.sqrt(2), 2]]/ 3
'S2' : [[1, exp(pi * 2j / 3) * sqrt(2)],
[exp(-pi * 2j / 3) * sqrt(2), 2]] / 3
'S3' : [[1, exp(-pi * 2j / 3) * sqrt(2)],
[exp(pi * 2j / 3) * sqrt(2), 2]] / 3
"""
res = np.array([])
# Return matrix for allowed label
if label == 'S0':
res = np.array([[1, 0], [0, 0]], dtype=complex)
if label == 'S1':
res = np.array([[1, np.sqrt(2)], [np.sqrt(2), 2]], dtype=complex) / 3
if label == 'S2':
res = np.array([[1, np.exp(np.pi * 2j / 3) * np.sqrt(2)],
[np.exp(-np.pi * 2j / 3) * np.sqrt(2), 2]]) / 3
if label == 'S3':
res = np.array([[1, np.exp(-np.pi * 2j / 3) * np.sqrt(2)],
[np.exp(np.pi * 2j / 3) * np.sqrt(2), 2]]) / 3
return res
###########################################################################
# PauliBasis Object
###########################################################################
SICBasis = TomographyBasis('SIC', measurement=None,
preparation=(('S0', 'S1', 'S2', 'S3'),
sicpovm_preparation_circuit,
sicpovm_preparation_matrix))
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
TomographyBasis class
"""
from qiskit import QuantumRegister
from qiskit import ClassicalRegister
from qiskit import QiskitError
class TomographyBasis:
"""
Tomography basis class.
"""
def __init__(self, name, measurement=None, preparation=None):
# TODO: check that measurement and preparation are both tuples
# (labels, circuit_fn, matrix_fn)
# Also check functions have correct signature and are return valid
# outputs for all specified labels
self._name = name
self._measurement = False
self._preparation = False
if measurement is not None and len(measurement) == 3:
self._measurement = True
self._measurement_labels = measurement[0]
self._measurement_circuit = measurement[1]
self._measurement_matrix = measurement[2]
if preparation is not None and len(preparation) == 3:
self._preparation = True
self._preparation_labels = preparation[0]
self._preparation_circuit = preparation[1]
self._preparation_matrix = preparation[2]
@property
def name(self):
"""The name of the tomography basis."""
return self._name
@property
def measurement(self):
"""The measurement of the tomography basis."""
return self._measurement
@property
def preparation(self):
"""The preparation of the tomography basis."""
return self._preparation
@property
def measurement_labels(self):
"""The measurement labels of the tomography basis."""
if self.measurement is True:
return self._measurement_labels
return None
@property
def preparation_labels(self):
"""The preparation labels of the tomography basis."""
if self.preparation is True:
return self._preparation_labels
return None
def measurement_circuit(self, op, qubit, clbit):
"""Return the measurement circuits."""
# Error Checking
if self.measurement is False:
raise QiskitError(
"{} is not a measurement basis".format(self._name))
if not (isinstance(qubit, tuple) and isinstance(qubit[0],
QuantumRegister)):
raise QiskitError('Input must be a qubit in a QuantumRegister')
if not (isinstance(clbit, tuple) and isinstance(clbit[0],
ClassicalRegister)):
raise QiskitError('Input must be a bit in a ClassicalRegister')
if op not in self._measurement_labels:
msg = "Invalid {0} measurement operator label".format(self._name)
error = "'{0}' != {1}".format(op, self._measurement_labels)
raise ValueError("{0}: {1}".format(msg, error))
# Return QuantumCircuit function output
return self._measurement_circuit(op, qubit, clbit)
def preparation_circuit(self, op, qubit):
"""Return the preparation circuits."""
# Error Checking
if self.preparation is False:
raise QiskitError("{} is not a preparation basis".format(
self._name))
if not (isinstance(qubit, tuple) and isinstance(qubit[0],
QuantumRegister)):
raise QiskitError('Input must be a qubit in a QuantumRegister')
if op not in self._preparation_labels:
msg = "Invalid {0} preparation operator label".format(self._name)
error = "'{}' not in {}".format(op, self._preparation_labels)
raise ValueError("{0}: {1}".format(msg, error))
return self._preparation_circuit(op, qubit)
def measurement_matrix(self, label, outcome):
"""Return the measurement matrix."""
if self.measurement is False:
raise QiskitError("{} is not a measurement basis".format(
self._name))
# Check input is valid for this basis
if label not in self._measurement_labels:
msg = "Invalid {0} measurement operator label".format(self._name)
error = "'{}' not in {}".format(label, self._measurement_labels)
raise ValueError("{0}: {1}".format(msg, error))
# Check outcome is valid for this measurement
allowed_outcomes = [0, 1, '0', '1']
if outcome not in allowed_outcomes:
error = "'{}' not in {}".format(outcome, allowed_outcomes)
raise ValueError('Invalid measurement outcome: {}'.format(error))
return self._measurement_matrix(label, outcome)
def preparation_matrix(self, label):
"""Return the preparation matrix."""
if self.preparation is False:
raise QiskitError("{} is not a preparation basis".format(
self._name))
# Check input is valid for this basis
if label not in self._preparation_labels:
msg = "Invalid {0} preparation operator label".format(self._name)
error = "'{}' not in {}".format(label, self._preparation_labels)
raise ValueError("{0}: {1}".format(msg, error))
return self._preparation_matrix(label)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Maximum-Likelihood estimation quantum tomography fitter
"""
import logging
import itertools as it
from ast import literal_eval
import numpy as np
from qiskit import QiskitError
from qiskit import QuantumCircuit
from ..basis import TomographyBasis, default_basis
from ..data import marginal_counts, combine_counts, count_keys
from .cvx_fit import cvxpy, cvx_fit
from .lstsq_fit import lstsq_fit
# Create logger
logger = logging.getLogger(__name__)
class TomographyFitter:
"""Basse maximum-likelihood estimate tomography fitter class"""
def __init__(self,
result,
circuits,
meas_basis='Pauli',
prep_basis='Pauli'):
"""Initialize tomography fitter with experimental data.
Args:
result (Result): a Qiskit Result object obtained from executing
tomography circuits.
circuits (list): a list of circuits or circuit names to extract
count information from the result object.
meas_basis (TomographyBasis, str): A function to return
measurement operators corresponding to measurement
outcomes. See Additional Information
(default: 'Pauli')
prep_basis (TomographyBasis, str): A function to return
preparation operators. See Additional
Information (default: 'Pauli')
"""
# Set the measure and prep basis
self._meas_basis = None
self._prep_basis = None
self.set_measure_basis(meas_basis)
self.set_preparation_basis(prep_basis)
# Add initial data
self._data = {}
self.add_data(result, circuits)
def set_measure_basis(self, basis):
"""Set the measurement basis
Args:
basis (TomographyBasis or str): measurement basis
"""
self._meas_basis = default_basis(basis)
if isinstance(self._meas_basis, TomographyBasis):
if self._meas_basis.measurement is not True:
raise QiskitError("Invalid measurement basis")
def set_preparation_basis(self, basis):
"""Set the prepearation basis function
Args:
basis (TomographyBasis or str): preparation basis
"""
self._prep_basis = default_basis(basis)
if isinstance(self._prep_basis, TomographyBasis):
if self._prep_basis.preparation is not True:
raise QiskitError("Invalid preparation basis")
@property
def measure_basis(self):
"""Return the tomography measurement basis."""
return self._meas_basis
@property
def preparation_basis(self):
"""Return the tomography preperation basis."""
return self._prep_basis
def fit(self, method='auto', standard_weights=True, beta=0.5, **kwargs):
"""
Reconstruct a quantum state using CVXPY convex optimization.
Args:
method (str): The fitter method 'auto', 'cvx' or 'lstsq'.
standard_weights (bool, optional): Apply weights to
tomography data
based on count probability
(default: True)
beta (float): hedging parameter for converting counts
to probabilities
(default: 0.5)
PSD (bool, optional): Enforced the fitted matrix to be positive
semidefinite (default: True)
trace (int, optional): trace constraint for the fitted matrix
(default: None).
trace_preserving (bool, optional): Enforce the fitted matrix to be
trace preserving when fitting a Choi-matrix in quantum process
tomography. Note this method does not apply for 'lstsq' fitter
method (default: False).
**kwargs (optional): kwargs for fitter method.
Returns:
The fitted matrix rho that minimizes
||basis_matrix * vec(rho) - data||_2.
Additional Information:
Fitter method
-------------
The 'cvx' fitter method used CVXPY convex optimization package.
The 'lstsq' method uses least-squares fitting (linear inversion).
The 'auto' method will use 'cvx' if the CVXPY package is found on
the system, otherwise it will default to 'lstsq'.
Objective function
------------------
This fitter solves the constrained least-squares minimization:
minimize: ||a * x - b ||_2
subject to: x >> 0 (PSD, optional)
trace(x) = t (trace, optional)
partial_trace(x) = identity (trace_preserving,
optional)
where:
a is the matrix of measurement operators a[i] = vec(M_i).H
b is the vector of expectation value data for each projector
b[i] ~ Tr[M_i.H * x] = (a * x)[i]
x is the vectorized density matrix (or Choi-matrix)
to be fitted
PSD constraint
--------------
The PSD keyword constrains the fitted matrix to be
postive-semidefinite.
For the 'lstsq' fitter method the fitted matrix is rescaled
using the method proposed in Reference [1].
For the 'cvx' fitter method the convex constraint makes the
optimization problem a SDP. If PSD=False the fitted matrix
will still
be constrained to be Hermitian, but not PSD. In this case the
optimization problem becomes a SOCP.
Trace constraint
----------------
The trace keyword constrains the trace of the fitted matrix. If
trace=None there will be no trace constraint on the fitted matrix.
This constraint should not be used for process tomography and the
trace preserving constraint should be used instead.
Trace preserving (TP) constraint
--------------------------------
The trace_preserving keyword constrains the fitted matrix
to be TP. This should only be used for process tomography,
not state tomography.
Note that the TP constraint implicitly enforces
the trace of the fitted
matrix to be equal to the square-root of the matrix dimension.
If a trace constraint is also specified that
differs from this value the fit
will likely fail. Note that this can only be used
for the CVX method.
CVXPY Solvers:
-------
Various solvers can be called in CVXPY using the `solver` keyword
argument. Solvers included in CVXPY are:
'CVXOPT': SDP and SOCP (default solver)
'SCS' : SDP and SOCP
'ECOS' : SOCP only
See the documentation on CVXPY for more information on solvers.
References:
[1] J Smolin, JM Gambetta, G Smith, Phys. Rev. Lett. 108, 070502
(2012). Open access: arXiv:1106.5458 [quant-ph].
"""
# Get fitter data
data, basis_matrix, weights = self._fitter_data(standard_weights,
beta)
# Choose automatic method
if method == 'auto':
if cvxpy is None:
method = 'lstsq'
else:
method = 'cvx'
if method == 'lstsq':
return lstsq_fit(data, basis_matrix, weights=weights, **kwargs)
if method == 'cvx':
return cvx_fit(data, basis_matrix, weights=weights, **kwargs)
raise QiskitError('Unrecognised fit method {}'.format(method))
@property
def data(self):
"""
Return tomography data
"""
return self._data
def add_data(self, result, circuits):
"""Add tomography data from a Qiskit Result object.
Args:
result (Result): a Qiskit Result object obtained from executing
tomography circuits.
circuits (list): a list of circuits or circuit names to extract
count information from the result object.
"""
if len(circuits[0].cregs) == 1:
marginalize = False
else:
marginalize = True
# Process measurement counts into probabilities
for circ in circuits:
counts = result.get_counts(circ)
if isinstance(circ, str):
tup = literal_eval(circ)
elif isinstance(circ, QuantumCircuit):
tup = literal_eval(circ.name)
else:
tup = circ
if marginalize:
counts = marginal_counts(counts, range(len(tup[0])))
if tup in self._data:
self._data[tup] = combine_counts(self._data[tup], counts)
else:
self._data[tup] = counts
def _fitter_data(self, standard_weights, beta):
"""Generate tomography fitter data from a tomography data dictionary.
Args:
standard_weights (bool, optional): Apply weights to basis matrix
and data based on count probability
(default: True)
beta (float): hedging parameter for 0, 1
probabilities (default: 0.5)
Returns:
tuple: (data, basis_matrix, weights) where `data`
is a vector of the
probability values, and `basis_matrix`
is a matrix of the preparation
and measurement operator, and `weights`
is a vector of weights for the
given probabilities.
Additional Information
----------------------
standard_weights:
Weights are calculated from from binomial distribution standard
deviation
"""
# Get basis matrix functions
if self._meas_basis:
measurement = self._meas_basis.measurement_matrix
else:
measurement = None
if self._prep_basis:
preparation = self._prep_basis.preparation_matrix
else:
preparation = None
data = []
basis_blocks = []
if standard_weights:
weights = []
else:
weights = None
# Check if input data is state or process tomography data based
# on the label tuples
label = next(iter(self._data))
is_qpt = (isinstance(label, tuple) and len(label) == 2 and
isinstance(label[0], tuple) and isinstance(label[1], tuple))
# Generate counts keys for converting to np array
if is_qpt:
ctkeys = count_keys(len(label[1]))
else:
ctkeys = count_keys(len(label))
for label, cts in self._data.items():
# Convert counts dict to numpy array
if isinstance(cts, dict):
cts = np.array([cts.get(key, 0) for key in ctkeys])
# Get probabilities
shots = np.sum(cts)
probs = np.array(cts) / shots
data += list(probs)
# Compute binomial weights
if standard_weights is True:
wts = self._binomial_weights(cts, beta)
weights += list(wts)
# Get reconstruction basis operators
if is_qpt:
prep_label = label[0]
meas_label = label[1]
else:
prep_label = None
meas_label = label
prep_op = self._preparation_op(prep_label, preparation)
meas_ops = self._measurement_ops(meas_label, measurement)
block = self._basis_operator_matrix(
[np.kron(prep_op.T, mop) for mop in meas_ops])
basis_blocks.append(block)
return data, np.vstack(basis_blocks), weights
def _binomial_weights(self, counts, beta=0.5):
"""
Compute binomial weights for list or dictionary of counts.
Args:
counts (dict, vector): A set of measurement counts for
all outcomes of a given measurement
configuration.
beta (float >= 0): A hedging parameter used to bias probabilities
computed from input counts away from 0 or 1.
Returns:
A numpy array of binomial weights for the input counts and beta
parameter.
Additional Information:
The weights are determined by
w[i] = sqrt(shots / p[i] * (1 - p[i]))
p[i] = (counts[i] + beta) / (shots + K * beta)
where
`shots` is the sum of all counts in the input
`p` is the hedged probability computed for a count
`K` is the total number of possible measurement outcomes.
"""
# Sort counts if input is a dictionary
if isinstance(counts, dict):
mcts = marginal_counts(counts, pad_zeros=True)
ordered_keys = sorted(list(mcts))
counts = np.array([mcts[k] for k in ordered_keys])
# Assume counts are already sorted if a list
else:
counts = np.array(counts)
shots = np.sum(counts)
# If beta is 0 check if we would be dividing by zero
# If so change beta value and log warning.
if beta < 0:
raise ValueError('beta = {} must be non-negative.'.format(beta))
if beta == 0 and (shots in counts or 0 in counts):
beta = 0.5
msg = ("Counts result in probabilities of 0 or 1 "
"in binomial weights "
"calculation. Setting hedging "
"parameter beta={} to prevent "
"dividing by zero.".format(beta))
logger.warning(msg)
K = len(counts) # Number of possible outcomes.
# Compute hedged frequencies which are shifted to never be 0 or 1.
freqs_hedged = (counts + beta) / (shots + K * beta)
# Return gaussian weights for 2-outcome measurements.
return np.sqrt(shots / (freqs_hedged * (1 - freqs_hedged)))
def _basis_operator_matrix(self, basis):
"""
Return a basis measurement matrix of the input basis.
Args:
basis (list (array like)): a list of basis matrices.
Returns:
A numpy array of shape (n, col * row) where n is the number
of operators of shape (row, col) in `basis`.
"""
# Dimensions
num_ops = len(basis)
nrows, ncols = basis[0].shape
size = nrows * ncols
ret = np.zeros((num_ops, size), dtype=complex)
for j, b in enumerate(basis):
ret[j] = np.array(b).reshape((1, size), order='F').conj()
return ret
def _preparation_op(self, label, prep_matrix_fn):
"""
Return the multi-qubit matrix for a state preparation label.
Args:
label (tuple(str)): a preparation configuration label for a
tomography circuit.
prep_matrix_fn (function): a function that returns the matrix
corresponding to a single qubit preparation label.
The functions should have signature
prep_matrix_fn(str) -> np.array
Returns:
A Numpy array for the multi-qubit prepration operator specified
by label.
Additional Information:
See the Pauli and SIC-POVM preparation functions
`pauli_preparation_matrix` and `sicpovm_preparation_matrix` for
examples.
"""
# Trivial case
if label is None:
return np.eye(1, dtype=complex)
# Construct preparation matrix
op = np.eye(1, dtype=complex)
for l in label:
op = np.kron(prep_matrix_fn(l), op)
return op
def _measurement_ops(self, label, meas_matrix_fn):
"""
Return a list multi-qubit matrices for a measurement label.
Args:
label (tuple(str)): a measurement configuration label for a
tomography circuit.
meas_matrix_fn (function): a function that returns the matrix
corresponding to a single qubit measurement label
for a given outcome. The functions should have
signature meas_matrix_fn(str, int) -> np.array
Returns:
A list of Numpy array for the multi-qubit measurement operators
for all measurement outcomes for the measurement basis specified
by the label. These are ordered in increasing binary order. Eg for
2-qubits the returned matrices correspond to outcomes
[00, 01, 10, 11]
Additional Information:
See the Pauli measurement function `pauli_measurement_matrix`
for an example.
"""
num_qubits = len(label)
meas_ops = []
# Construct measurement POVM for all measurement outcomes for a given
# measurement label. This will be a list of 2 ** n operators.
for l in sorted(it.product((0, 1), repeat=num_qubits)):
op = np.eye(1, dtype=complex)
# Reverse label to correspond to QISKit bit ordering
for m, outcome in zip(reversed(label), l):
op = np.kron(op, meas_matrix_fn(m, outcome))
meas_ops.append(op)
return meas_ops
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Maximum-Likelihood estimation quantum process tomography fitter
"""
import numpy as np
from qiskit import QiskitError
from qiskit.quantum_info.operators import Choi
from .base_fitter import TomographyFitter
from .cvx_fit import cvxpy, cvx_fit
from .lstsq_fit import lstsq_fit
class ProcessTomographyFitter(TomographyFitter):
"""Maximum-Likelihood estimation process tomography fitter."""
def fit(self, method='auto', standard_weights=True, beta=0.5, **kwargs):
"""
Reconstruct a quantum channel using CVXPY convex optimization.
Args:
method (str): The fitter method 'auto', 'cvx' or 'lstsq'.
standard_weights (bool, optional): Apply weights
to tomography data
based on count probability
(default: True)
beta (float): hedging parameter for converting counts
to probabilities (default: 0.5)
**kwargs (optional): kwargs for fitter method.
Returns:
Choi: The fitted Choi-matrix J for the channel that maximizes
||basis_matrix * vec(J) - data||_2. The Numpy matrix can be
obtained from `Choi.data`.
Additional Information:
Choi matrix
-----------
The Choi matrix object is a QuantumChannel representation which
may be converted to other representations using the classes
`SuperOp`, `Kraus`, `Stinespring`, `PTM`, `Chi` from the module
`qiskit.quantum_info.operators`. The raw matrix data for the
representation may be obtained by `channel.data`.
Fitter method
-------------
The 'cvx' fitter method used CVXPY convex optimization package.
The 'lstsq' method uses least-squares fitting (linear inversion).
The 'auto' method will use 'cvx' if the CVXPY package is found on
the system, otherwise it will default to 'lstsq'.
Objective function
------------------
This fitter solves the constrained least-squares minimization:
minimize: ||a * x - b ||_2
subject to: x >> 0 (PSD)
trace(x) = dim (trace)
partial_trace(x) = identity (trace_preserving)
where:
a is the matrix of measurement operators a[i] = vec(M_i).H
b is the vector of expectation value data for each projector
b[i] ~ Tr[M_i.H * x] = (a * x)[i]
x is the vectorized Choi-matrix to be fitted
PSD constraint
--------------
The PSD keyword constrains the fitted matrix to be
postive-semidefinite.
For the 'lstsq' fitter method the fitted matrix is
rescaled using the
method proposed in Reference [1].
For the 'cvx' fitter method the convex constraint makes the
optimization problem a SDP. If PSD=False the
fitted matrix will still
be constrained to be Hermitian, but not PSD. In this case the
optimization problem becomes a SOCP.
Trace constraint
----------------
The trace keyword constrains the trace of the fitted matrix. If
trace=None there will be no trace constraint on the fitted matrix.
This constraint should not be used for process tomography and the
trace preserving constraint should be used instead.
Trace preserving (TP) constraint
--------------------------------
The trace_preserving keyword constrains the fitted
matrix to be TP.
This should only be used for process tomography,
not state tomography.
Note that the TP constraint implicitly enforces
the trace of the fitted
matrix to be equal to the square-root of the
matrix dimension. If a
trace constraint is also specified that differs f
rom this value the fit
will likely fail. Note that this can
only be used for the CVX method.
CVXPY Solvers:
-------
Various solvers can be called in CVXPY using the `solver` keyword
argument. Solvers included in CVXPY are:
'CVXOPT': SDP and SOCP (default solver)
'SCS' : SDP and SOCP
'ECOS' : SOCP only
See the documentation on CVXPY for more information on solvers.
References:
[1] J Smolin, JM Gambetta, G Smith, Phys. Rev. Lett. 108, 070502
(2012). Open access: arXiv:1106.5458 [quant-ph].
"""
# Get fitter data
data, basis_matrix, weights = self._fitter_data(standard_weights,
beta)
# Calculate trace of Choi-matrix from projector length
_, cols = np.shape(basis_matrix)
dim = int(np.sqrt(np.sqrt(cols)))
if dim ** 4 != cols:
raise ValueError("Input data does not correspond "
"to a process matrix.")
# Choose automatic method
if method == 'auto':
if cvxpy is None:
method = 'lstsq'
else:
method = 'cvx'
if method == 'lstsq':
return Choi(lstsq_fit(data, basis_matrix, weights=weights,
trace=dim, **kwargs))
if method == 'cvx':
return Choi(cvx_fit(data, basis_matrix, weights=weights, trace=dim,
trace_preserving=True, **kwargs))
raise QiskitError('Unrecognised fit method {}'.format(method))
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Exception for errors raised by Qiskit Aer simulators backends.
"""
from qiskit import QiskitError
class AerError(QiskitError):
"""Base class for errors raised by simulators."""
def __init__(self, *message):
"""Set the error message."""
super().__init__(*message)
self.message = ' '.join(message)
def __str__(self):
"""Return the message."""
return repr(self.message)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Exception for errors raised by Qiskit Aer noise module.
"""
from qiskit import QiskitError
class NoiseError(QiskitError):
"""Class for errors raised in qiskit_aer.noise package."""
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/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Decorator for using with Qiskit unit tests."""
import functools
import os
import sys
import unittest
from .utils import Path
from .http_recorder import http_recorder
from .testing_options import get_test_options
def is_aer_provider_available():
"""Check if the C++ simulator can be instantiated.
Returns:
bool: True if simulator executable is available
"""
# TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC
if sys.platform == 'darwin':
return False
try:
import qiskit.providers.aer # pylint: disable=unused-import
except ImportError:
return False
return True
def requires_aer_provider(test_item):
"""Decorator that skips test if qiskit aer provider is not available
Args:
test_item (callable): function or class to be decorated.
Returns:
callable: the decorated function.
"""
reason = 'Aer provider not found, skipping test'
return unittest.skipIf(not is_aer_provider_available(), reason)(test_item)
def slow_test(func):
"""Decorator that signals that the test takes minutes to run.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(*args, **kwargs):
skip_slow = not TEST_OPTIONS['run_slow']
if skip_slow:
raise unittest.SkipTest('Skipping slow tests')
return func(*args, **kwargs)
return _wrapper
def _get_credentials(test_object, test_options):
"""Finds the credentials for a specific test and options.
Args:
test_object (QiskitTestCase): The test object asking for credentials
test_options (dict): Options after QISKIT_TESTS was parsed by
get_test_options.
Returns:
Credentials: set of credentials
Raises:
ImportError: if the
Exception: when the credential could not be set and they are needed
for that set of options
"""
try:
from qiskit.providers.ibmq.credentials import (Credentials,
discover_credentials)
except ImportError:
raise ImportError('qiskit-ibmq-provider could not be found, and is '
'required for mocking or executing online tests.')
dummy_credentials = Credentials(
'dummyapiusersloginWithTokenid01',
'https://quantumexperience.ng.bluemix.net/api')
if test_options['mock_online']:
return dummy_credentials
if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''):
# Special case: instead of using the standard credentials mechanism,
# load them from different environment variables. This assumes they
# will always be in place, as is used by the Travis setup.
return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL'))
else:
# Attempt to read the standard credentials.
discovered_credentials = discover_credentials()
if discovered_credentials:
# Decide which credentials to use for testing.
if len(discovered_credentials) > 1:
try:
# Attempt to use QE credentials.
return discovered_credentials[dummy_credentials.unique_id()]
except KeyError:
pass
# Use the first available credentials.
return list(discovered_credentials.values())[0]
# No user credentials were found.
if test_options['rec']:
raise Exception('Could not locate valid credentials. You need them for '
'recording tests against the remote API.')
test_object.log.warning('No user credentials were detected. '
'Running with mocked data.')
test_options['mock_online'] = True
return dummy_credentials
def requires_qe_access(func):
"""Decorator that signals that the test uses the online API:
It involves:
* determines if the test should be skipped by checking environment
variables.
* if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is
set, it reads the credentials from an alternative set of environment
variables.
* if the test is not skipped, it reads `qe_token` and `qe_url` from
`Qconfig.py`, environment variables or qiskitrc.
* if the test is not skipped, it appends `qe_token` and `qe_url` as
arguments to the test function.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if TEST_OPTIONS['skip_online']:
raise unittest.SkipTest('Skipping online tests')
credentials = _get_credentials(self, TEST_OPTIONS)
self.using_ibmq_credentials = credentials.is_ibmq()
kwargs.update({'qe_token': credentials.token,
'qe_url': credentials.url})
decorated_func = func
if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']:
# For recording or for replaying existing cassettes, the test
# should be decorated with @use_cassette.
vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none'
decorated_func = http_recorder(
vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func)
return decorated_func(self, *args, **kwargs)
return _wrapper
TEST_OPTIONS = get_test_options()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# Copyright 2019, 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.
"""Helper class used to convert a pulse instruction into PulseQobjInstruction."""
import re
import math
import warnings
from sympy.parsing.sympy_parser import (parse_expr, standard_transformations,
implicit_multiplication_application,
function_exponentiation)
from sympy import Symbol
from qiskit.pulse import commands, channels, Schedule
from qiskit.pulse.schedule import ParameterizedSchedule
from qiskit.pulse.exceptions import PulseError
from qiskit.qobj import QobjMeasurementOption
from qiskit import QiskitError
class ConversionMethodBinder:
"""Conversion method registrar."""
def __init__(self):
"""Acts as method registration decorator and tracker for conversion methods."""
self._bound_instructions = {}
def __call__(self, bound):
""" Converter decorator method.
Converter is defined for object to be converted matched on hash
Args:
bound (Hashable): Hashable object to bind to the converter.
"""
# pylint: disable=missing-return-doc, missing-return-type-doc
def _apply_converter(converter):
"""Return decorated converter function."""
# Track conversion methods for class.
self._bound_instructions[bound] = converter
return converter
return _apply_converter
def get_bound_method(self, bound):
"""Get conversion method for bound object."""
try:
return self._bound_instructions[bound]
except KeyError:
raise PulseError('Bound method for %s is not found.' % bound)
class InstructionToQobjConverter:
"""Converts pulse Instructions to Qobj models.
Converter is constructed with qobj model and experimental configuration,
and returns proper qobj instruction to each backend.
Third party providers can be add their own custom pulse instructions by
providing custom converter methods.
To create a custom converter for custom instruction
```
class CustomConverter(InstructionToQobjConverter):
@bind_instruction(CustomInstruction)
def convert_custom_command(self, shift, instruction):
command_dict = {
'name': 'custom_command',
't0': shift+instruction.start_time,
'param1': instruction.param1,
'param2': instruction.param2
}
if self._run_config('option1', True):
command_dict.update({
'param3': instruction.param3
})
return self.qobj_model(**command_dict)
```
"""
# class level tracking of conversion methods
bind_instruction = ConversionMethodBinder()
def __init__(self, qobj_model, **run_config):
"""Create new converter.
Args:
qobj_model (QobjInstruction): marshmallow model to serialize to object.
run_config (dict): experimental configuration.
"""
self._qobj_model = qobj_model
self._run_config = run_config
def __call__(self, shift, instruction):
method = self.bind_instruction.get_bound_method(type(instruction))
return method(self, shift, instruction)
@bind_instruction(commands.AcquireInstruction)
def convert_acquire(self, shift, instruction):
"""Return converted `AcquireInstruction`.
Args:
shift(int): Offset time.
instruction (AcquireInstruction): acquire instruction.
Returns:
dict: Dictionary of required parameters.
"""
meas_level = self._run_config.get('meas_level', 2)
command_dict = {
'name': 'acquire',
't0': shift+instruction.start_time,
'duration': instruction.duration,
'qubits': [q.index for q in instruction.acquires],
'memory_slot': [m.index for m in instruction.mem_slots]
}
if meas_level == 2:
# setup discriminators
if instruction.command.discriminator:
command_dict.update({
'discriminators': [
QobjMeasurementOption(
name=instruction.command.discriminator.name,
params=instruction.command.discriminator.params)
]
})
# setup register_slots
if instruction.reg_slots:
command_dict.update({
'register_slot': [regs.index for regs in instruction.reg_slots]
})
if meas_level >= 1:
# setup kernels
if instruction.command.kernel:
command_dict.update({
'kernels': [
QobjMeasurementOption(
name=instruction.command.kernel.name,
params=instruction.command.kernel.params)
]
})
return self._qobj_model(**command_dict)
@bind_instruction(commands.FrameChangeInstruction)
def convert_frame_change(self, shift, instruction):
"""Return converted `FrameChangeInstruction`.
Args:
shift(int): Offset time.
instruction (FrameChangeInstruction): frame change instruction.
Returns:
dict: Dictionary of required parameters.
"""
command_dict = {
'name': 'fc',
't0': shift+instruction.start_time,
'ch': instruction.channels[0].name,
'phase': instruction.command.phase
}
return self._qobj_model(**command_dict)
@bind_instruction(commands.PersistentValueInstruction)
def convert_persistent_value(self, shift, instruction):
"""Return converted `PersistentValueInstruction`.
Args:
shift(int): Offset time.
instruction (PersistentValueInstruction): persistent value instruction.
Returns:
dict: Dictionary of required parameters.
"""
command_dict = {
'name': 'pv',
't0': shift+instruction.start_time,
'ch': instruction.channels[0].name,
'val': instruction.command.value
}
return self._qobj_model(**command_dict)
@bind_instruction(commands.PulseInstruction)
def convert_drive(self, shift, instruction):
"""Return converted `PulseInstruction`.
Args:
shift(int): Offset time.
instruction (PulseInstruction): drive instruction.
Returns:
dict: Dictionary of required parameters.
"""
command_dict = {
'name': instruction.command.name,
't0': shift+instruction.start_time,
'ch': instruction.channels[0].name
}
return self._qobj_model(**command_dict)
@bind_instruction(commands.Snapshot)
def convert_snapshot(self, shift, instruction):
"""Return converted `Snapshot`.
Args:
shift(int): Offset time.
instruction (Snapshot): snapshot instruction.
Returns:
dict: Dictionary of required parameters.
"""
command_dict = {
'name': 'snapshot',
't0': shift+instruction.start_time,
'label': instruction.name,
'type': instruction.type
}
return self._qobj_model(**command_dict)
# pylint: disable=invalid-name
# get math operations valid in python. Presumably these are valid in sympy
_math_ops = [math_op for math_op in math.__dict__ if not math_op.startswith('__')]
# only allow valid math ops
_math_ops_regex = r"(" + ")|(".join(_math_ops) + ")"
# match consecutive alphanumeric, and single consecutive math ops +-/.()
# and multiple * for exponentiation
_allowedchars = re.compile(r'(([+\/\-]?|\*{0,2})?[\(\)\s]*' # allow to start with math/bracket
r'([a-zA-Z][a-zA-Z\d]*|' # match word
r'[\d]+(\.\d*)?)[\(\)\s]*)*') # match decimal and bracket
# match any sequence of chars and numbers
_expr_regex = r'([a-zA-Z]+\d*)'
# and valid params
_param_regex = r'(P\d+)'
# only valid sequences are P# for parameters and valid math operations above
_valid_sub_expr = re.compile(_param_regex+'|'+_math_ops_regex)
# pylint: enable=invalid-name
def _is_math_expr_safe(expr):
r"""Verify mathematical expression is sanitized.
Only allow strings of form 'P\d+' and operations from `math`.
Allowed chars are [a-zA-Z]. Allowed math operators are '+*/().'
where only '*' are allowed to be consecutive.
Args:
expr (str): Expression to sanitize
Returns:
bool: Whether the string is safe to parse math from
Raise:
QiskitError: If math expression is not sanitized
"""
only_allowed_chars = _allowedchars.match(expr)
if not only_allowed_chars:
return False
elif not only_allowed_chars.group(0) == expr:
return False
sub_expressions = re.findall(_expr_regex, expr)
if not all([_valid_sub_expr.match(sub_exp) for sub_exp in sub_expressions]):
return False
return True
def _parse_string_expr(expr): # pylint: disable=missing-return-type-doc
"""Parse a mathematical string expression and extract free parameters.
Args:
expr (str): String expression to parse
Returns:
(Callable, Tuple[str]): Returns a callable function and tuple of string symbols
Raises:
QiskitError: If expression is not safe
"""
# remove these strings from expression and hope sympy knows these math expressions
# these are effectively reserved keywords
subs = [('numpy.', ''), ('np.', ''), ('math.', '')]
for match, sub in subs:
expr = expr.replace(match, sub)
if not _is_math_expr_safe(expr):
raise QiskitError('Expression: "%s" is not safe to evaluate.' % expr)
params = sorted(re.findall(_param_regex, expr))
local_dict = {param: Symbol(param) for param in params}
symbols = list(local_dict.keys())
transformations = (standard_transformations + (implicit_multiplication_application,) +
(function_exponentiation,))
parsed_expr = parse_expr(expr, local_dict=local_dict, transformations=transformations)
def parsed_fun(*args, **kwargs):
subs = {}
matched_params = []
if args:
subs.update({symbols[i]: arg for i, arg in enumerate(args)})
matched_params += list(params[i] for i in range(len(args)))
elif kwargs:
subs.update({local_dict[key]: value for key, value in kwargs.items()
if key in local_dict})
matched_params += list(key for key in kwargs if key in params)
if not set(matched_params).issuperset(set(params)):
raise PulseError('Supplied params ({args}, {kwargs}) do not match '
'{params}'.format(args=args, kwargs=kwargs, params=params))
return complex(parsed_expr.evalf(subs=subs))
return parsed_fun, params
class QobjToInstructionConverter:
"""Converts Qobj models to pulse Instructions
"""
# pylint: disable=invalid-name,missing-return-type-doc
# class level tracking of conversion methods
bind_name = ConversionMethodBinder()
chan_regex = re.compile(r'([a-zA-Z]+)(\d+)')
def __init__(self, pulse_library, buffer=0, **run_config):
"""Create new converter.
Args:
pulse_library (List[PulseLibraryItem]): Pulse library to be used in conversion
buffer (int): Channel buffer
run_config (dict): experimental configuration.
"""
self.buffer = buffer
self._run_config = run_config
# bind pulses to conversion methods
for pulse in pulse_library:
self.bind_pulse(pulse)
def __call__(self, instruction):
method = self.bind_name.get_bound_method(instruction.name)
return method(self, instruction)
def get_channel(self, channel):
"""Parse and retrieve channel from ch string.
Args:
channel (str): Channel to match
Returns:
(Channel, int): Matched channel
Raises:
PulseError: Is raised if valid channel is not matched
"""
match = self.chan_regex.match(channel)
if match:
prefix, index = match.group(1), int(match.group(2))
if prefix == channels.DriveChannel.prefix:
return channels.DriveChannel(index, buffer=self.buffer)
elif prefix == channels.MeasureChannel.prefix:
return channels.MeasureChannel(index, buffer=self.buffer)
elif prefix == channels.ControlChannel.prefix:
return channels.ControlChannel(index, buffer=self.buffer)
raise PulseError('Channel %s is not valid' % channel)
@bind_name('acquire')
def convert_acquire(self, instruction):
"""Return converted `AcquireInstruction`.
Args:
instruction (PulseQobjInstruction): acquire qobj
Returns:
Schedule: Converted and scheduled Instruction
"""
t0 = instruction.t0
duration = instruction.duration
qubits = instruction.qubits
qubit_channels = [channels.AcquireChannel(qubit, buffer=self.buffer) for qubit in qubits]
mem_slots = [channels.MemorySlot(instruction.memory_slot[i]) for i in range(len(qubits))]
if hasattr(instruction, 'register_slot'):
register_slots = [channels.RegisterSlot(instruction.register_slot[i])
for i in range(len(qubits))]
else:
register_slots = None
discriminators = (instruction.discriminators
if hasattr(instruction, 'discriminators') else None)
if not isinstance(discriminators, list):
discriminators = [discriminators]
if any(discriminators[i] != discriminators[0] for i in range(len(discriminators))):
warnings.warn("Can currently only support one discriminator per acquire. Defaulting "
"to first discriminator entry.")
discriminator = discriminators[0]
if discriminator:
discriminator = commands.Discriminator(name=discriminators[0].name,
params=discriminators[0].params)
kernels = (instruction.kernels
if hasattr(instruction, 'kernels') else None)
if not isinstance(kernels, list):
kernels = [kernels]
if any(kernels[0] != kernels[i] for i in range(len(kernels))):
warnings.warn("Can currently only support one kernel per acquire. Defaulting to first "
"kernel entry.")
kernel = kernels[0]
if kernel:
kernel = commands.Kernel(name=kernels[0].name, params=kernels[0].params)
cmd = commands.Acquire(duration, discriminator=discriminator, kernel=kernel)
schedule = Schedule()
schedule |= commands.AcquireInstruction(cmd, qubit_channels, mem_slots,
register_slots) << t0
return schedule
@bind_name('fc')
def convert_frame_change(self, instruction):
"""Return converted `FrameChangeInstruction`.
Args:
instruction (PulseQobjInstruction): frame change qobj
Returns:
Schedule: Converted and scheduled Instruction
"""
t0 = instruction.t0
channel = self.get_channel(instruction.ch)
phase = instruction.phase
# This is parameterized
if isinstance(phase, str):
phase_expr, params = _parse_string_expr(phase)
def gen_fc_sched(*args, **kwargs):
phase = abs(phase_expr(*args, **kwargs))
return commands.FrameChange(phase)(channel) << t0
return ParameterizedSchedule(gen_fc_sched, parameters=params)
return commands.FrameChange(phase)(channel) << t0
@bind_name('pv')
def convert_persistent_value(self, instruction):
"""Return converted `PersistentValueInstruction`.
Args:
instruction (PulseQobjInstruction): persistent value qobj
Returns:
Schedule: Converted and scheduled Instruction
"""
t0 = instruction.t0
channel = self.get_channel(instruction.ch)
val = instruction.val
# This is parameterized
if isinstance(val, str):
val_expr, params = _parse_string_expr(val)
def gen_fc_sched(*args, **kwargs):
val = complex(val_expr(*args, **kwargs))
return commands.PersistentValue(val)(channel) << t0
return ParameterizedSchedule(gen_fc_sched, parameters=params)
return commands.PersistentValue(val)(channel) << t0
def bind_pulse(self, pulse):
"""Bind the supplied pulse to a converter method by pulse name.
Args:
pulse (PulseLibraryItem): Pulse to bind
"""
# pylint: disable=unused-variable
pulse = commands.SamplePulse(pulse.samples, pulse.name)
@self.bind_name(pulse.name)
def convert_named_drive(self, instruction):
"""Return converted `PulseInstruction`.
Args:
instruction (PulseQobjInstruction): pulse qobj
Returns:
Schedule: Converted and scheduled pulse
"""
t0 = instruction.t0
channel = self.get_channel(instruction.ch)
return pulse(channel) << t0
@bind_name('snapshot')
def convert_snapshot(self, instruction):
"""Return converted `Snapshot`.
Args:
instruction (PulseQobjInstruction): snapshot qobj
Returns:
Schedule: Converted and scheduled Snapshot
"""
t0 = instruction.t0
return commands.Snapshot(instruction.label, instruction.type) << t0
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Decorator for using with Qiskit unit tests."""
import functools
import os
import sys
import unittest
from .utils import Path
from .http_recorder import http_recorder
from .testing_options import get_test_options
def is_aer_provider_available():
"""Check if the C++ simulator can be instantiated.
Returns:
bool: True if simulator executable is available
"""
# TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC
if sys.platform == 'darwin':
return False
try:
import qiskit.providers.aer # pylint: disable=unused-import
except ImportError:
return False
return True
def requires_aer_provider(test_item):
"""Decorator that skips test if qiskit aer provider is not available
Args:
test_item (callable): function or class to be decorated.
Returns:
callable: the decorated function.
"""
reason = 'Aer provider not found, skipping test'
return unittest.skipIf(not is_aer_provider_available(), reason)(test_item)
def slow_test(func):
"""Decorator that signals that the test takes minutes to run.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(*args, **kwargs):
skip_slow = not TEST_OPTIONS['run_slow']
if skip_slow:
raise unittest.SkipTest('Skipping slow tests')
return func(*args, **kwargs)
return _wrapper
def _get_credentials(test_object, test_options):
"""Finds the credentials for a specific test and options.
Args:
test_object (QiskitTestCase): The test object asking for credentials
test_options (dict): Options after QISKIT_TESTS was parsed by
get_test_options.
Returns:
Credentials: set of credentials
Raises:
ImportError: if the
Exception: when the credential could not be set and they are needed
for that set of options
"""
try:
from qiskit.providers.ibmq.credentials import (Credentials,
discover_credentials)
except ImportError:
raise ImportError('qiskit-ibmq-provider could not be found, and is '
'required for mocking or executing online tests.')
dummy_credentials = Credentials(
'dummyapiusersloginWithTokenid01',
'https://quantumexperience.ng.bluemix.net/api')
if test_options['mock_online']:
return dummy_credentials
if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''):
# Special case: instead of using the standard credentials mechanism,
# load them from different environment variables. This assumes they
# will always be in place, as is used by the Travis setup.
return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL'))
else:
# Attempt to read the standard credentials.
discovered_credentials = discover_credentials()
if discovered_credentials:
# Decide which credentials to use for testing.
if len(discovered_credentials) > 1:
try:
# Attempt to use QE credentials.
return discovered_credentials[dummy_credentials.unique_id()]
except KeyError:
pass
# Use the first available credentials.
return list(discovered_credentials.values())[0]
# No user credentials were found.
if test_options['rec']:
raise Exception('Could not locate valid credentials. You need them for '
'recording tests against the remote API.')
test_object.log.warning('No user credentials were detected. '
'Running with mocked data.')
test_options['mock_online'] = True
return dummy_credentials
def requires_qe_access(func):
"""Decorator that signals that the test uses the online API:
It involves:
* determines if the test should be skipped by checking environment
variables.
* if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is
set, it reads the credentials from an alternative set of environment
variables.
* if the test is not skipped, it reads `qe_token` and `qe_url` from
`Qconfig.py`, environment variables or qiskitrc.
* if the test is not skipped, it appends `qe_token` and `qe_url` as
arguments to the test function.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if TEST_OPTIONS['skip_online']:
raise unittest.SkipTest('Skipping online tests')
credentials = _get_credentials(self, TEST_OPTIONS)
self.using_ibmq_credentials = credentials.is_ibmq()
kwargs.update({'qe_token': credentials.token,
'qe_url': credentials.url})
decorated_func = func
if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']:
# For recording or for replaying existing cassettes, the test
# should be decorated with @use_cassette.
vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none'
decorated_func = http_recorder(
vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func)
return decorated_func(self, *args, **kwargs)
return _wrapper
TEST_OPTIONS = get_test_options()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utils for using with Qiskit unit tests."""
import logging
import os
import unittest
from enum import Enum
from qiskit import __path__ as qiskit_path
class Path(Enum):
"""Helper with paths commonly used during the tests."""
# Main SDK path: qiskit/
SDK = qiskit_path[0]
# test.python path: qiskit/test/python/
TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python'))
# Examples path: examples/
EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples'))
# Schemas path: qiskit/schemas
SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas'))
# VCR cassettes path: qiskit/test/cassettes/
CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes'))
# Sample QASMs path: qiskit/test/python/qasm
QASMS = os.path.normpath(os.path.join(TEST, 'qasm'))
def setup_test_logging(logger, log_level, filename):
"""Set logging to file and stdout for a logger.
Args:
logger (Logger): logger object to be updated.
log_level (str): logging level.
filename (str): name of the output file.
"""
# Set up formatter.
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(logger.name))
formatter = logging.Formatter(log_fmt)
# Set up the file handler.
file_handler = logging.FileHandler(filename)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(log_level, logging.INFO)
logger.setLevel(level)
class _AssertNoLogsContext(unittest.case._AssertLogsContext):
"""A context manager used to implement TestCase.assertNoLogs()."""
# pylint: disable=inconsistent-return-statements
def __exit__(self, exc_type, exc_value, tb):
"""
This is a modified version of TestCase._AssertLogsContext.__exit__(...)
"""
self.logger.handlers = self.old_handlers
self.logger.propagate = self.old_propagate
self.logger.setLevel(self.old_level)
if exc_type is not None:
# let unexpected exceptions pass through
return False
if self.watcher.records:
msg = 'logs of level {} or higher triggered on {}:\n'.format(
logging.getLevelName(self.level), self.logger.name)
for record in self.watcher.records:
msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname,
record.lineno,
record.getMessage())
self._raiseFailure(msg)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit import Aer, IBMQ, execute
from qiskit import transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
from qiskit.visualization import plot_histogram, plot_state_city
"""
Qiskit backends to execute the quantum circuit
"""
def simulator(qc):
"""
Run on local simulator
:param qc: quantum circuit
:return:
"""
backend = Aer.get_backend("qasm_simulator")
shots = 2048
tqc = transpile(qc, backend)
qobj = assemble(tqc, shots=shots)
job_sim = backend.run(qobj)
qc_results = job_sim.result()
return qc_results, shots
def simulator_state_vector(qc):
"""
Select the StatevectorSimulator from the Aer provider
:param qc: quantum circuit
:return:
statevector
"""
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(qc, simulator).result()
state_vector = result.get_statevector(qc)
return state_vector
def real_quantum_device(qc):
"""
Use the IBMQ essex device
:param qc: quantum circuit
:return:
"""
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_santiago')
shots = 2048
TQC = transpile(qc, backend)
qobj = assemble(TQC, shots=shots)
job_exp = backend.run(qobj)
job_monitor(job_exp)
QC_results = job_exp.result()
return QC_results, shots
def counts(qc_results):
"""
Get counts representing the wave-function amplitudes
:param qc_results:
:return: dict keys are bit_strings and their counting values
"""
return qc_results.get_counts()
def plot_results(qc_results):
"""
Visualizing wave-function amplitudes in a histogram
:param qc_results: quantum circuit
:return:
"""
plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False))
def plot_state_vector(state_vector):
"""Visualizing state vector in the density matrix representation"""
plt.show(plot_state_city(state_vector))
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A module of magic functions"""
import time
import threading
from IPython.display import display # pylint: disable=import-error
from IPython.core import magic_arguments # pylint: disable=import-error
from IPython.core.magic import cell_magic, Magics, magics_class # pylint: disable=import-error
try:
import ipywidgets as widgets # pylint: disable=import-error
except ImportError:
raise ImportError('These functions need ipywidgets. '
'Run "pip install ipywidgets" before.')
import qiskit
from qiskit.tools.events.progressbar import TextProgressBar
from .progressbar import HTMLProgressBar
def _html_checker(job_var, interval, status, header,
_interval_set=False):
"""Internal function that updates the status
of a HTML job monitor.
Args:
job_var (BaseJob): The job to keep track of.
interval (int): The status check interval
status (widget): HTML ipywidget for output ot screen
header (str): String representing HTML code for status.
_interval_set (bool): Was interval set by user?
"""
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
status.value = header % (job_status_msg)
while job_status_name not in ['DONE', 'CANCELLED']:
time.sleep(interval)
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
if job_status_name == 'ERROR':
break
else:
if job_status_name == 'QUEUED':
job_status_msg += ' (%s)' % job_var.queue_position()
if not _interval_set:
interval = max(job_var.queue_position(), 2)
else:
if not _interval_set:
interval = 2
status.value = header % (job_status_msg)
status.value = header % (job_status_msg)
@magics_class
class StatusMagic(Magics):
"""A class of status magic functions.
"""
@cell_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument(
'-i',
'--interval',
type=float,
default=None,
help='Interval for status check.'
)
def qiskit_job_status(self, line='', cell=None):
"""A Jupyter magic function to check the status of a Qiskit job instance.
"""
args = magic_arguments.parse_argstring(self.qiskit_job_status, line)
if args.interval is None:
args.interval = 2
_interval_set = False
else:
_interval_set = True
# Split cell lines to get LHS variables
cell_lines = cell.split('\n')
line_vars = []
for cline in cell_lines:
if '=' in cline and '==' not in cline:
line_vars.append(cline.replace(' ', '').split('=')[0])
elif '.append(' in cline:
line_vars.append(cline.replace(' ', '').split('(')[0])
# Execute the cell
self.shell.ex(cell)
# Look for all vars that are BaseJob instances
jobs = []
for var in line_vars:
iter_var = False
if '#' not in var:
# The line var is a list or array, but we cannot parse the index
# so just iterate over the whole array for jobs.
if '[' in var:
var = var.split('[')[0]
iter_var = True
elif '.append' in var:
var = var.split('.append')[0]
iter_var = True
if iter_var:
for item in self.shell.user_ns[var]:
if isinstance(item, qiskit.providers.basejob.BaseJob):
jobs.append(item)
else:
if isinstance(self.shell.user_ns[var],
qiskit.providers.basejob.BaseJob):
jobs.append(self.shell.user_ns[var])
# Must have one job class
if not any(jobs):
raise Exception(
"Cell must contain at least one variable of BaseJob type.")
# List index of job if checking status of multiple jobs.
multi_job = False
if len(jobs) > 1:
multi_job = True
job_checkers = []
# Loop over every BaseJob that was found.
for idx, job_var in enumerate(jobs):
style = "font-size:16px;"
if multi_job:
idx_str = '[%s]' % idx
else:
idx_str = ''
header = "<p style='{style}'>Job Status {id}: %s </p>".format(id=idx_str,
style=style)
status = widgets.HTML(
value=header % job_var.status().value)
thread = threading.Thread(target=_html_checker, args=(job_var, args.interval,
status, header,
_interval_set))
thread.start()
job_checkers.append(status)
# Group all HTML widgets into single vertical layout
box = widgets.VBox(job_checkers)
display(box)
@magics_class
class ProgressBarMagic(Magics):
"""A class of progress bar magic functions.
"""
@cell_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument(
'-t',
'--type',
type=str,
default='html',
help="Type of progress bar, 'html' or 'text'."
)
def qiskit_progress_bar(self, line='', cell=None): # pylint: disable=W0613
"""A Jupyter magic function to generate progressbar.
"""
args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line)
if args.type == 'html':
HTMLProgressBar()
elif args.type == 'text':
TextProgressBar()
else:
raise qiskit.QiskitError('Invalid progress bar type.')
self.shell.ex(cell)
|
https://github.com/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.
# pylint: disable=invalid-name
"""
Quantum Tomography Module
Description:
This module contains functions for performing quantum state and quantum
process tomography. This includes:
- Functions for generating a set of circuits to
extract tomographically complete sets of measurement data.
- Functions for generating a tomography data set from the
results after the circuits have been executed on a backend.
- Functions for reconstructing a quantum state, or quantum process
(Choi-matrix) from tomography data sets.
Reconstruction Methods:
Currently implemented reconstruction methods are
- Linear inversion by weighted least-squares fitting.
- Fast maximum likelihood reconstruction using ref [1].
References:
[1] J Smolin, JM Gambetta, G Smith, Phys. Rev. Lett. 108, 070502 (2012).
Open access: arXiv:1106.5458 [quant-ph].
Workflow:
The basic functions for performing state and tomography experiments are:
- `tomography_set`, `state_tomography_set`, and `process_tomography_set`
all generates data structures for tomography experiments.
- `create_tomography_circuits` generates the quantum circuits specified
in a `tomography_set` for performing state tomography of the output
- `tomography_data` extracts the results after executing the tomography
circuits and returns it in a data structure used by fitters for state
reconstruction.
- `fit_tomography_data` reconstructs a density matrix or Choi-matrix from
the a set of tomography data.
"""
import logging
from functools import reduce
from itertools import product
from re import match
import numpy as np
from qiskit import QuantumCircuit
from qiskit.exceptions import QiskitError
from qiskit.tools.qi.qi import vectorize, devectorize, outer
logger = logging.getLogger(__name__)
###############################################################################
# Tomography Bases
###############################################################################
class TomographyBasis(dict):
"""
Dictionary subsclass that includes methods for adding gates to circuits.
A TomographyBasis is a dictionary where the keys index a measurement
and the values are a list of projectors associated to that measurement.
It also includes two optional methods `prep_gate` and `meas_gate`:
- `prep_gate` adds gates to a circuit to prepare the corresponding
basis projector from an initial ground state.
- `meas_gate` adds gates to a circuit to transform the default
Z-measurement into a measurement in the basis.
With the exception of built in bases, these functions do nothing unless
they are specified by the user. They may be set by the data members
`prep_fun` and `meas_fun`. We illustrate this with an example.
Example:
A measurement in the Pauli-X basis has two outcomes corresponding to
the projectors:
`Xp = [[0.5, 0.5], [0.5, 0.5]]`
`Xm = [[0.5, -0.5], [-0.5, 0.5]]`
We can express this as a basis by
`BX = TomographyBasis( {'X': [Xp, Xm]} )`
To specifiy the gates to prepare and measure in this basis we :
```
def BX_prep_fun(circuit, qreg, op):
bas, proj = op
if bas == "X":
if proj == 0:
circuit.u2(0., np.pi, qreg) # apply H
else: # proj == 1
circuit.u2(np.pi, np.pi, qreg) # apply H.X
def BX_prep_fun(circuit, qreg, op):
if op == "X":
circuit.u2(0., np.pi, qreg) # apply H
```
We can then attach these functions to the basis using:
`BX.prep_fun = BX_prep_fun`
`BX.meas_fun = BX_meas_fun`.
Generating function:
A generating function `tomography_basis` exists to create bases in a
single step. Using the above example this can be done by:
```
BX = tomography_basis({'X': [Xp, Xm]},
prep_fun=BX_prep_fun,
meas_fun=BX_meas_fun)
```
"""
prep_fun = None
meas_fun = None
def prep_gate(self, circuit, qreg, op):
"""
Add state preparation gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add a preparation to.
qreg (tuple(QuantumRegister,int)): quantum register to apply
preparation to.
op (tuple(str, int)): the basis label and index for the
preparation op.
"""
if self.prep_fun is None:
pass
else:
self.prep_fun(circuit, qreg, op)
def meas_gate(self, circuit, qreg, op):
"""
Add measurement gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add measurement to.
qreg (tuple(QuantumRegister,int)): quantum register being measured.
op (str): the basis label for the measurement.
"""
if self.meas_fun is None:
pass
else:
self.meas_fun(circuit, qreg, op)
def tomography_basis(basis, prep_fun=None, meas_fun=None):
"""
Generate a TomographyBasis object.
See TomographyBasis for further details.abs
Args:
prep_fun (callable) optional: the function which adds preparation
gates to a circuit.
meas_fun (callable) optional: the function which adds measurement
gates to a circuit.
Returns:
TomographyBasis: A tomography basis.
"""
ret = TomographyBasis(basis)
ret.prep_fun = prep_fun
ret.meas_fun = meas_fun
return ret
# PAULI BASIS
# This corresponds to measurements in the X, Y, Z basis where
# Outcomes 0,1 are the +1,-1 eigenstates respectively.
# State preparation is also done in the +1 and -1 eigenstates.
def __pauli_prep_gates(circuit, qreg, op):
"""
Add state preparation gates to a circuit.
"""
bas, proj = op
if bas not in ['X', 'Y', 'Z']:
raise QiskitError("There's no X, Y or Z basis for this Pauli "
"preparation")
if bas == "X":
if proj == 1:
circuit.u2(np.pi, np.pi, qreg) # H.X
else:
circuit.u2(0., np.pi, qreg) # H
elif bas == "Y":
if proj == 1:
circuit.u2(-0.5 * np.pi, np.pi, qreg) # S.H.X
else:
circuit.u2(0.5 * np.pi, np.pi, qreg) # S.H
elif bas == "Z" and proj == 1:
circuit.u3(np.pi, 0., np.pi, qreg) # X
def __pauli_meas_gates(circuit, qreg, op):
"""
Add state measurement gates to a circuit.
"""
if op not in ['X', 'Y', 'Z']:
raise QiskitError("There's no X, Y or Z basis for this Pauli "
"measurement")
if op == "X":
circuit.u2(0., np.pi, qreg) # H
elif op == "Y":
circuit.u2(0., 0.5 * np.pi, qreg) # H.S^*
__PAULI_BASIS_OPS = {
'X':
[np.array([[0.5, 0.5], [0.5, 0.5]]),
np.array([[0.5, -0.5], [-0.5, 0.5]])],
'Y': [
np.array([[0.5, -0.5j], [0.5j, 0.5]]),
np.array([[0.5, 0.5j], [-0.5j, 0.5]])
],
'Z': [np.array([[1, 0], [0, 0]]),
np.array([[0, 0], [0, 1]])]
}
# Create the actual basis
PAULI_BASIS = tomography_basis(
__PAULI_BASIS_OPS,
prep_fun=__pauli_prep_gates,
meas_fun=__pauli_meas_gates)
# SIC-POVM BASIS
def __sic_prep_gates(circuit, qreg, op):
"""
Add state preparation gates to a circuit.
"""
bas, proj = op
if bas != 'S':
raise QiskitError('Not in SIC basis!')
theta = -2 * np.arctan(np.sqrt(2))
if proj == 1:
circuit.u3(theta, np.pi, 0.0, qreg)
elif proj == 2:
circuit.u3(theta, np.pi / 3, 0.0, qreg)
elif proj == 3:
circuit.u3(theta, -np.pi / 3, 0.0, qreg)
__SIC_BASIS_OPS = {
'S': [
np.array([[1, 0], [0, 0]]),
np.array([[1, np.sqrt(2)], [np.sqrt(2), 2]]) / 3,
np.array([[1, np.exp(np.pi * 2j / 3) * np.sqrt(2)],
[np.exp(-np.pi * 2j / 3) * np.sqrt(2), 2]]) / 3,
np.array([[1, np.exp(-np.pi * 2j / 3) * np.sqrt(2)],
[np.exp(np.pi * 2j / 3) * np.sqrt(2), 2]]) / 3
]
}
SIC_BASIS = tomography_basis(__SIC_BASIS_OPS, prep_fun=__sic_prep_gates)
###############################################################################
# Tomography Set and labels
###############################################################################
def tomography_set(meas_qubits,
meas_basis='Pauli',
prep_qubits=None,
prep_basis=None):
"""
Generate a dictionary of tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.
Quantum State Tomography:
Be default it will return a set for performing Quantum State
Tomography where individual qubits are measured in the Pauli basis.
A custom measurement basis may also be used by defining a user
`tomography_basis` and passing this in for the `meas_basis` argument.
Quantum Process Tomography:
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
meas_qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
prep_qubits (list or None): The qubits being prepared. If None then
meas_qubits will be used for process tomography experiments.
prep_basis (tomography_basis or None): The optional qubit preparation
basis. If no basis is specified state tomography will be performed
instead of process tomography. A built in basis may be specified by
'SIC' or 'Pauli' (SIC basis recommended for > 2 qubits).
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "circuits". It may also optionally
contain a field "prep_basis" for process tomography experiments.
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
# optionally for process tomography experiments:
'prep_basis': prep_basis (tomography_basis)
}
```
Raises:
QiskitError: if the Qubits argument is not a list.
"""
if not isinstance(meas_qubits, list):
raise QiskitError('Qubits argument must be a list')
num_of_qubits = len(meas_qubits)
if prep_qubits is None:
prep_qubits = meas_qubits
if not isinstance(prep_qubits, list):
raise QiskitError('prep_qubits argument must be a list')
if len(prep_qubits) != len(meas_qubits):
raise QiskitError('meas_qubits and prep_qubitsare different length')
if isinstance(meas_basis, str):
if meas_basis.lower() == 'pauli':
meas_basis = PAULI_BASIS
if isinstance(prep_basis, str):
if prep_basis.lower() == 'pauli':
prep_basis = PAULI_BASIS
elif prep_basis.lower() == 'sic':
prep_basis = SIC_BASIS
circuits = []
circuit_labels = []
# add meas basis configs
if prep_basis is None:
# State Tomography
for meas_product in product(meas_basis.keys(), repeat=num_of_qubits):
meas = dict(zip(meas_qubits, meas_product))
circuits.append({'meas': meas})
# Make label
label = '_meas_'
for qubit, op in meas.items():
label += '%s(%d)' % (op[0], qubit)
circuit_labels.append(label)
return {'qubits': meas_qubits,
'circuits': circuits,
'circuit_labels': circuit_labels,
'meas_basis': meas_basis}
# Process Tomography
num_of_s = len(list(prep_basis.values())[0])
plst_single = [(b, s)
for b in prep_basis.keys()
for s in range(num_of_s)]
for plst_product in product(plst_single, repeat=num_of_qubits):
for meas_product in product(meas_basis.keys(),
repeat=num_of_qubits):
prep = dict(zip(prep_qubits, plst_product))
meas = dict(zip(meas_qubits, meas_product))
circuits.append({'prep': prep, 'meas': meas})
# Make label
label = '_prep_'
for qubit, op in prep.items():
label += '%s%d(%d)' % (op[0], op[1], qubit)
label += '_meas_'
for qubit, op in meas.items():
label += '%s(%d)' % (op[0], qubit)
circuit_labels.append(label)
return {'qubits': meas_qubits,
'circuits': circuits,
'circuit_labels': circuit_labels,
'prep_basis': prep_basis,
'meas_basis': meas_basis}
def state_tomography_set(qubits, meas_basis='Pauli'):
"""
Generate a dictionary of state tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.
Quantum State Tomography:
Be default it will return a set for performing Quantum State
Tomography where individual qubits are measured in the Pauli basis.
A custom measurement basis may also be used by defining a user
`tomography_basis` and passing this in for the `meas_basis` argument.
Quantum Process Tomography:
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "circuits".
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
}
```
"""
return tomography_set(qubits, meas_basis=meas_basis)
def process_tomography_set(meas_qubits, meas_basis='Pauli',
prep_qubits=None, prep_basis='SIC'):
"""
Generate a dictionary of process tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
meas_qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
prep_qubits (list or None): The qubits being prepared. If None then
meas_qubits will be used for process tomography experiments.
prep_basis (tomography_basis or str): The qubit preparation basis.
The default value is 'SIC'.
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "prep_basus", circuits".
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'prep_basis': prep_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
}
```
"""
return tomography_set(meas_qubits, meas_basis=meas_basis,
prep_qubits=prep_qubits, prep_basis=prep_basis)
def tomography_circuit_names(tomo_set, name=''):
"""
Return a list of tomography circuit names.
The returned list is the same as the one returned by
`create_tomography_circuits` and can be used by a QuantumProgram
to execute tomography circuits and extract measurement results.
Args:
tomo_set (tomography_set): a tomography set generated by
`tomography_set`.
name (str): the name of the base QuantumCircuit used by the
tomography experiment.
Returns:
list: A list of circuit names.
"""
return [name + l for l in tomo_set['circuit_labels']]
###############################################################################
# Tomography circuit generation
###############################################################################
def create_tomography_circuits(circuit, qreg, creg, tomoset):
"""
Add tomography measurement circuits to a QuantumProgram.
The quantum program must contain a circuit 'name', which is treated as a
state preparation circuit for state tomography, or as teh circuit being
measured for process tomography. This function then appends the circuit
with a set of measurements specified by the input `tomography_set`,
optionally it also prepends the circuit with state preparation circuits if
they are specified in the `tomography_set`.
For n-qubit tomography with a tomographically complete set of preparations
and measurements this results in $4^n 3^n$ circuits being added to the
quantum program.
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
qreg (QuantumRegister): the quantum register containing qubits to be
measured.
creg (ClassicalRegister): the classical register containing bits to
store measurement outcomes.
tomoset (tomography_set): the dict of tomography configurations.
Returns:
list: A list of quantum tomography circuits for the input circuit.
Raises:
QiskitError: if circuit is not a valid QuantumCircuit
Example:
For a tomography set specifying state tomography of qubit-0 prepared
by a circuit 'circ' this would return:
```
['circ_meas_X(0)', 'circ_meas_Y(0)', 'circ_meas_Z(0)']
```
For process tomography of the same circuit with preparation in the
SIC-POVM basis it would return:
```
[
'circ_prep_S0(0)_meas_X(0)', 'circ_prep_S0(0)_meas_Y(0)',
'circ_prep_S0(0)_meas_Z(0)', 'circ_prep_S1(0)_meas_X(0)',
'circ_prep_S1(0)_meas_Y(0)', 'circ_prep_S1(0)_meas_Z(0)',
'circ_prep_S2(0)_meas_X(0)', 'circ_prep_S2(0)_meas_Y(0)',
'circ_prep_S2(0)_meas_Z(0)', 'circ_prep_S3(0)_meas_X(0)',
'circ_prep_S3(0)_meas_Y(0)', 'circ_prep_S3(0)_meas_Z(0)'
]
```
"""
if not isinstance(circuit, QuantumCircuit):
raise QiskitError('Input circuit must be a QuantumCircuit object')
dics = tomoset['circuits']
labels = tomography_circuit_names(tomoset, circuit.name)
tomography_circuits = []
for label, conf in zip(labels, dics):
tmp = circuit
# Add prep circuits
if 'prep' in conf:
prep = QuantumCircuit(qreg, creg, name='tmp_prep')
for qubit, op in conf['prep'].items():
tomoset['prep_basis'].prep_gate(prep, qreg[qubit], op)
prep.barrier(qreg[qubit])
tmp = prep + tmp
# Add measurement circuits
meas = QuantumCircuit(qreg, creg, name='tmp_meas')
for qubit, op in conf['meas'].items():
meas.barrier(qreg[qubit])
tomoset['meas_basis'].meas_gate(meas, qreg[qubit], op)
meas.measure(qreg[qubit], creg[qubit])
tmp = tmp + meas
# Add label to the circuit
tmp.name = label
tomography_circuits.append(tmp)
logger.info('>> created tomography circuits for "%s"', circuit.name)
return tomography_circuits
###############################################################################
# Get results data
###############################################################################
def tomography_data(results, name, tomoset):
"""
Return a results dict for a state or process tomography experiment.
Args:
results (Result): Results from execution of a process tomography
circuits on a backend.
name (string): The name of the circuit being reconstructed.
tomoset (tomography_set): the dict of tomography configurations.
Returns:
list: A list of dicts for the outcome of each process tomography
measurement circuit.
"""
labels = tomography_circuit_names(tomoset, name)
circuits = tomoset['circuits']
data = []
prep = None
for j, _ in enumerate(labels):
counts = marginal_counts(results.get_counts(labels[j]),
tomoset['qubits'])
shots = sum(counts.values())
meas = circuits[j]['meas']
prep = circuits[j].get('prep', None)
meas_qubits = sorted(meas.keys())
if prep:
prep_qubits = sorted(prep.keys())
circuit = {}
for c in counts.keys():
circuit[c] = {}
circuit[c]['meas'] = [(meas[meas_qubits[k]], int(c[-1 - k]))
for k in range(len(meas_qubits))]
if prep:
circuit[c]['prep'] = [prep[prep_qubits[k]]
for k in range(len(prep_qubits))]
data.append({'counts': counts, 'shots': shots, 'circuit': circuit})
ret = {'data': data, 'meas_basis': tomoset['meas_basis']}
if prep:
ret['prep_basis'] = tomoset['prep_basis']
return ret
def marginal_counts(counts, meas_qubits):
"""
Compute the marginal counts for a subset of measured qubits.
Args:
counts (dict): the counts returned from a backend ({str: int}).
meas_qubits (list[int]): the qubits to return the marginal
counts distribution for.
Returns:
dict: A counts dict for the meas_qubits.abs
Example: if `counts = {'00': 10, '01': 5}`
`marginal_counts(counts, [0])` returns `{'0': 15, '1': 0}`.
`marginal_counts(counts, [0])` returns `{'0': 10, '1': 5}`.
"""
# pylint: disable=cell-var-from-loop
# Extract total number of qubits from count keys
num_of_qubits = len(list(counts.keys())[0])
# keys for measured qubits only
qs = sorted(meas_qubits, reverse=True)
meas_keys = count_keys(len(qs))
# get regex match strings for summing outcomes of other qubits
rgx = [
reduce(lambda x, y: (key[qs.index(y)] if y in qs else '\\d') + x,
range(num_of_qubits), '') for key in meas_keys
]
# build the return list
meas_counts = []
for m in rgx:
c = 0
for key, val in counts.items():
if match(m, key):
c += val
meas_counts.append(c)
# return as counts dict on measured qubits only
return dict(zip(meas_keys, meas_counts))
def count_keys(n):
"""Generate outcome bitstrings for n-qubits.
Args:
n (int): the number of qubits.
Returns:
list: A list of bitstrings ordered as follows:
Example: n=2 returns ['00', '01', '10', '11'].
"""
return [bin(j)[2:].zfill(n) for j in range(2**n)]
###############################################################################
# Tomographic Reconstruction functions.
###############################################################################
def fit_tomography_data(tomo_data, method='wizard', options=None):
"""
Reconstruct a density matrix or process-matrix from tomography data.
If the input data is state_tomography_data the returned operator will
be a density matrix. If the input data is process_tomography_data the
returned operator will be a Choi-matrix in the column-vectorization
convention.
Args:
tomo_data (dict): process tomography measurement data.
method (str): the fitting method to use.
Available methods:
- 'wizard' (default)
- 'leastsq'
options (dict or None): additional options for fitting method.
Returns:
numpy.array: The fitted operator.
Available methods:
- 'wizard' (Default): The returned operator will be constrained to be
positive-semidefinite.
Options:
- 'trace': the trace of the returned operator.
The default value is 1.
- 'beta': hedging parameter for computing frequencies from
zero-count data. The default value is 0.50922.
- 'epsilon: threshold for truncating small eigenvalues to zero.
The default value is 0
- 'leastsq': Fitting without positive-semidefinite constraint.
Options:
- 'trace': Same as for 'wizard' method.
- 'beta': Same as for 'wizard' method.
Raises:
Exception: if the `method` parameter is not valid.
"""
if isinstance(method, str) and method.lower() in ['wizard', 'leastsq']:
# get options
trace = __get_option('trace', options)
beta = __get_option('beta', options)
# fit state
rho = __leastsq_fit(tomo_data, trace=trace, beta=beta)
if method == 'wizard':
# Use wizard method to constrain positivity
epsilon = __get_option('epsilon', options)
rho = __wizard(rho, epsilon=epsilon)
return rho
else:
raise Exception('Invalid reconstruction method "%s"' % method)
def __get_option(opt, options):
"""
Return an optional value or None if not found.
"""
if options is not None:
if opt in options:
return options[opt]
return None
###############################################################################
# Fit Method: Linear Inversion
###############################################################################
def __leastsq_fit(tomo_data, weights=None, trace=None, beta=None):
"""
Reconstruct a state from unconstrained least-squares fitting.
Args:
tomo_data (list[dict]): state or process tomography data.
weights (list or array or None): weights to use for least squares
fitting. The default is standard deviation from a binomial
distribution.
trace (float or None): trace of returned operator. The default is 1.
beta (float or None): hedge parameter (>=0) for computing frequencies
from zero-count data. The default value is 0.50922.
Returns:
numpy.array: A numpy array of the reconstructed operator.
"""
if trace is None:
trace = 1. # default to unit trace
data = tomo_data['data']
keys = data[0]['circuit'].keys()
# Get counts and shots
counts = []
shots = []
ops = []
for dat in data:
for key in keys:
counts.append(dat['counts'][key])
shots.append(dat['shots'])
projectors = dat['circuit'][key]
op = __projector(projectors['meas'], tomo_data['meas_basis'])
if 'prep' in projectors:
op_prep = __projector(projectors['prep'],
tomo_data['prep_basis'])
op = np.kron(op_prep.conj(), op)
ops.append(op)
# Convert counts to frequencies
counts = np.array(counts)
shots = np.array(shots)
freqs = counts / shots
# Use hedged frequencies to calculate least squares fitting weights
if weights is None:
if beta is None:
beta = 0.50922
K = len(keys)
freqs_hedged = (counts + beta) / (shots + K * beta)
weights = np.sqrt(shots / (freqs_hedged * (1 - freqs_hedged)))
return __tomo_linear_inv(freqs, ops, weights, trace=trace)
def __projector(op_list, basis):
"""Returns a projectors.
"""
ret = 1
# list is from qubit 0 to 1
for op in op_list:
label, eigenstate = op
ret = np.kron(basis[label][eigenstate], ret)
return ret
def __tomo_linear_inv(freqs, ops, weights=None, trace=None):
"""
Reconstruct a matrix through linear inversion.
Args:
freqs (list[float]): list of observed frequences.
ops (list[np.array]): list of corresponding projectors.
weights (list[float] or array_like):
weights to be used for weighted fitting.
trace (float or None): trace of returned operator.
Returns:
numpy.array: A numpy array of the reconstructed operator.
"""
# get weights matrix
if weights is not None:
W = np.array(weights)
if W.ndim == 1:
W = np.diag(W)
# Get basis S matrix
S = np.array([vectorize(m).conj()
for m in ops]).reshape(len(ops), ops[0].size)
if weights is not None:
S = np.dot(W, S) # W.S
# get frequencies vec
v = np.array(freqs) # |f>
if weights is not None:
v = np.dot(W, freqs) # W.|f>
Sdg = S.T.conj() # S^*.W^*
inv = np.linalg.pinv(np.dot(Sdg, S)) # (S^*.W^*.W.S)^-1
# linear inversion of freqs
ret = devectorize(np.dot(inv, np.dot(Sdg, v)))
# renormalize to input trace value
if trace is not None:
ret = trace * ret / np.trace(ret)
return ret
###############################################################################
# Fit Method: Wizard
###############################################################################
def __wizard(rho, epsilon=None):
"""
Returns the nearest positive semidefinite operator to an operator.
This method is based on reference [1]. It constrains positivity
by setting negative eigenvalues to zero and rescaling the positive
eigenvalues.
Args:
rho (array_like): the input operator.
epsilon(float or None): threshold (>=0) for truncating small
eigenvalues values to zero.
Returns:
numpy.array: A positive semidefinite numpy array.
"""
if epsilon is None:
epsilon = 0. # default value
dim = len(rho)
rho_wizard = np.zeros([dim, dim])
v, w = np.linalg.eigh(rho) # v eigenvecrors v[0] < v[1] <...
for j in range(dim):
if v[j] < epsilon:
tmp = v[j]
v[j] = 0.
# redistribute loop
x = 0.
for k in range(j + 1, dim):
x += tmp / (dim - (j + 1))
v[k] = v[k] + tmp / (dim - (j + 1))
for j in range(dim):
rho_wizard = rho_wizard + v[j] * outer(w[:, j])
return rho_wizard
###############################################################
# Wigner function tomography
###############################################################
def build_wigner_circuits(circuit, phis, thetas, qubits,
qreg, creg):
"""Create the circuits to rotate to points in phase space
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
phis (np.matrix[[complex]]): phis
thetas (np.matrix[[complex]]): thetas
qubits (list[int]): a list of the qubit indexes of qreg to be measured.
qreg (QuantumRegister): the quantum register containing qubits to be
measured.
creg (ClassicalRegister): the classical register containing bits to
store measurement outcomes.
Returns:
list: A list of names of the added wigner function circuits.
Raises:
QiskitError: if circuit is not a valid QuantumCircuit.
"""
if not isinstance(circuit, QuantumCircuit):
raise QiskitError('Input circuit must be a QuantumCircuit object')
tomography_circuits = []
points = len(phis[0])
for point in range(points):
label = '_wigner_phase_point'
label += str(point)
tmp_circ = QuantumCircuit(qreg, creg, name=label)
for qubit, _ in enumerate(qubits):
tmp_circ.u3(thetas[qubit][point], 0,
phis[qubit][point], qreg[qubits[qubit]])
tmp_circ.measure(qreg[qubits[qubit]], creg[qubits[qubit]])
# Add to original circuit
tmp_circ = circuit + tmp_circ
tmp_circ.name = circuit.name + label
tomography_circuits.append(tmp_circ)
logger.info('>> Created Wigner function circuits for "%s"', circuit.name)
return tomography_circuits
def wigner_data(q_result, meas_qubits, labels, shots=None):
"""Get the value of the Wigner function from measurement results.
Args:
q_result (Result): Results from execution of a state tomography
circuits on a backend.
meas_qubits (list[int]): a list of the qubit indexes measured.
labels (list[str]): a list of names of the circuits
shots (int): number of shots
Returns:
list: The values of the Wigner function at measured points in
phase space
"""
num = len(meas_qubits)
dim = 2**num
p = [0.5 + 0.5 * np.sqrt(3), 0.5 - 0.5 * np.sqrt(3)]
parity = 1
for i in range(num):
parity = np.kron(parity, p)
w = [0] * len(labels)
wpt = 0
counts = [marginal_counts(q_result.get_counts(circ), meas_qubits)
for circ in labels]
for entry in counts:
x = [0] * dim
for i in range(dim):
if bin(i)[2:].zfill(num) in entry:
x[i] = float(entry[bin(i)[2:].zfill(num)])
if shots is None:
shots = np.sum(x)
for i in range(dim):
w[wpt] = w[wpt] + (x[i] / shots) * parity[i]
wpt += 1
return w
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=too-many-function-args, unexpected-keyword-arg
"""THIS FILE IS DEPRECATED AND WILL BE REMOVED IN RELEASE 0.9.
"""
import warnings
from qiskit.converters import dag_to_circuit, circuit_to_dag
from qiskit.transpiler import CouplingMap
from qiskit import compiler
from qiskit.transpiler.preset_passmanagers import (default_pass_manager_simulator,
default_pass_manager)
def transpile(circuits, backend=None, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""transpile one or more circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
basis_gates (list[str]): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (Layout or dict or list):
Initial position of virtual qubits on physical qubits. The final
layout is not guaranteed to be the same, as the transpiler may permute
qubits through swaps or other means.
seed_mapper (int): random seed for the swap_mapper
pass_manager (PassManager): a pass_manager for the transpiler stages
Returns:
QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
Raises:
TranspilerError: in case of bad inputs to transpiler or errors in passes
"""
warnings.warn("qiskit.transpiler.transpile() has been deprecated and will be "
"removed in the 0.9 release. Use qiskit.compiler.transpile() instead.",
DeprecationWarning)
return compiler.transpile(circuits=circuits, backend=backend,
basis_gates=basis_gates, coupling_map=coupling_map,
initial_layout=initial_layout, seed_transpiler=seed_mapper,
pass_manager=pass_manager)
def transpile_dag(dag, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""Deprecated - Use qiskit.compiler.transpile for transpiling from
circuits to circuits.
Transform a dag circuit into another dag circuit
(transpile), through consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (list[str]): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (Layout or None): A layout object
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
"""
warnings.warn("transpile_dag has been deprecated and will be removed in the "
"0.9 release. Circuits can be transpiled directly to other "
"circuits with the transpile function.", DeprecationWarning)
if basis_gates is None:
basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']
if pass_manager is None:
# default set of passes
# if a coupling map is given compile to the map
if coupling_map:
pass_manager = default_pass_manager(basis_gates,
CouplingMap(coupling_map),
initial_layout,
seed_transpiler=seed_mapper)
else:
pass_manager = default_pass_manager_simulator(basis_gates)
# run the passes specified by the pass manager
# TODO return the property set too. See #1086
name = dag.name
circuit = dag_to_circuit(dag)
circuit = pass_manager.run(circuit)
dag = circuit_to_dag(circuit)
dag.name = name
return dag
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Implementation of Sven Jandura's swap mapper submission for the 2018 QISKit
Developer Challenge, adapted to integrate into the transpiler architecture.
The role of the mapper pass is to modify the starting circuit to be compatible
with the target device's topology (the set of two-qubit gates available on the
hardware.) To do this, the mapper will insert SWAP gates to relocate the virtual
qubits for each upcoming gate onto a set of coupled physical qubits. However, as
SWAP gates are particularly lossy, the goal is to accomplish this remapping while
introducing the fewest possible additional SWAPs.
This algorithm searches through the available combinations of SWAP gates by means
of a narrowed best first/beam search, described as follows:
- Start with a layout of virtual qubits onto physical qubits.
- Find any gates in the input circuit which can be performed with the current
layout and mark them as mapped.
- For all possible SWAP gates, calculate the layout that would result from their
application and rank them according to the distance of the resulting layout
over upcoming gates (see _calc_layout_distance.)
- For the four (SEARCH_WIDTH) highest-ranking SWAPs, repeat the above process on
the layout that would be generated if they were applied.
- Repeat this process down to a depth of four (SEARCH_DEPTH) SWAPs away from the
initial layout, for a total of 256 (SEARCH_WIDTH^SEARCH_DEPTH) prospective
layouts.
- Choose the layout which maximizes the number of two-qubit which could be
performed. Add its mapped gates, including the SWAPs generated, to the
output circuit.
- Repeat the above until all gates from the initial circuit are mapped.
For more details on the algorithm, see Sven's blog post:
https://medium.com/qiskit/improving-a-quantum-compiler-48410d7a7084
"""
from copy import deepcopy
from qiskit import QuantumRegister
from qiskit.dagcircuit import DAGCircuit
from qiskit.extensions.standard import SwapGate
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler import Layout
from qiskit.dagcircuit import DAGNode
SEARCH_DEPTH = 4
SEARCH_WIDTH = 4
class LookaheadSwap(TransformationPass):
"""Map input circuit onto a backend topology via insertion of SWAPs."""
def __init__(self, coupling_map, initial_layout=None):
"""Initialize a LookaheadSwap instance.
Arguments:
coupling_map (CouplingMap): CouplingMap of the target backend.
initial_layout (Layout): The initial layout of the DAG to analyze.
"""
super().__init__()
self._coupling_map = coupling_map
self.initial_layout = initial_layout
def run(self, dag):
"""Run one pass of the lookahead mapper on the provided DAG.
Args:
dag (DAGCircuit): the directed acyclic graph to be mapped
Returns:
DAGCircuit: A dag mapped to be compatible with the coupling_map in
the property_set.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG
"""
coupling_map = self._coupling_map
ordered_virtual_gates = list(dag.serial_layers())
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.qubits()) != len(self.initial_layout):
raise TranspilerError('The layout does not match the amount of qubits in the DAG')
if len(self._coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError(
"Mappers require to have the layout to be the same size as the coupling map")
mapped_gates = []
layout = self.initial_layout.copy()
gates_remaining = ordered_virtual_gates.copy()
while gates_remaining:
best_step = _search_forward_n_swaps(layout, gates_remaining,
coupling_map)
layout = best_step['layout']
gates_mapped = best_step['gates_mapped']
gates_remaining = best_step['gates_remaining']
mapped_gates.extend(gates_mapped)
# Preserve input DAG's name, regs, wire_map, etc. but replace the graph.
mapped_dag = _copy_circuit_metadata(dag, coupling_map)
for node in mapped_gates:
mapped_dag.apply_operation_back(op=node.op, qargs=node.qargs, cargs=node.cargs)
return mapped_dag
def _search_forward_n_swaps(layout, gates, coupling_map,
depth=SEARCH_DEPTH, width=SEARCH_WIDTH):
"""Search for SWAPs which allow for application of largest number of gates.
Arguments:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap of the target backend.
depth (int): Number of SWAP layers to search before choosing a result.
width (int): Number of SWAPs to consider at each layer.
Returns:
dict: Describes solution step found.
layout (Layout): Virtual to physical qubit map after SWAPs.
gates_remaining (list): Gates that could not be mapped.
gates_mapped (list): Gates that were mapped, including added SWAPs.
"""
gates_mapped, gates_remaining = _map_free_gates(layout, gates, coupling_map)
base_step = {'layout': layout,
'swaps_added': 0,
'gates_mapped': gates_mapped,
'gates_remaining': gates_remaining}
if not gates_remaining or depth == 0:
return base_step
possible_swaps = coupling_map.get_edges()
def _score_swap(swap):
"""Calculate the relative score for a given SWAP."""
trial_layout = layout.copy()
trial_layout.swap(*swap)
return _calc_layout_distance(gates, coupling_map, trial_layout)
ranked_swaps = sorted(possible_swaps, key=_score_swap)
best_swap, best_step = None, None
for swap in ranked_swaps[:width]:
trial_layout = layout.copy()
trial_layout.swap(*swap)
next_step = _search_forward_n_swaps(trial_layout, gates_remaining,
coupling_map, depth - 1, width)
# ranked_swaps already sorted by distance, so distance is the tie-breaker.
if best_swap is None or _score_step(next_step) > _score_step(best_step):
best_swap, best_step = swap, next_step
best_swap_gate = _swap_ops_from_edge(best_swap, layout)
return {
'layout': best_step['layout'],
'swaps_added': 1 + best_step['swaps_added'],
'gates_remaining': best_step['gates_remaining'],
'gates_mapped': gates_mapped + best_swap_gate + best_step['gates_mapped'],
}
def _map_free_gates(layout, gates, coupling_map):
"""Map all gates that can be executed with the current layout.
Args:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap for target device topology.
Returns:
tuple:
mapped_gates (list): ops for gates that can be executed, mapped onto layout.
remaining_gates (list): gates that cannot be executed on the layout.
"""
blocked_qubits = set()
mapped_gates = []
remaining_gates = []
for gate in gates:
# Gates without a partition (barrier, snapshot, save, load, noise) may
# still have associated qubits. Look for them in the qargs.
if not gate['partition']:
qubits = [n for n in gate['graph'].nodes() if n.type == 'op'][0].qargs
if not qubits:
continue
if blocked_qubits.intersection(qubits):
blocked_qubits.update(qubits)
remaining_gates.append(gate)
else:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
continue
qubits = gate['partition'][0]
if blocked_qubits.intersection(qubits):
blocked_qubits.update(qubits)
remaining_gates.append(gate)
elif len(qubits) == 1:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
elif coupling_map.distance(*[layout[q] for q in qubits]) == 1:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
else:
blocked_qubits.update(qubits)
remaining_gates.append(gate)
return mapped_gates, remaining_gates
def _calc_layout_distance(gates, coupling_map, layout, max_gates=None):
"""Return the sum of the distances of two-qubit pairs in each CNOT in gates
according to the layout and the coupling.
"""
if max_gates is None:
max_gates = 50 + 10 * len(coupling_map.physical_qubits)
return sum(coupling_map.distance(*[layout[q] for q in gate['partition'][0]])
for gate in gates[:max_gates]
if gate['partition'] and len(gate['partition'][0]) == 2)
def _score_step(step):
"""Count the mapped two-qubit gates, less the number of added SWAPs."""
# Each added swap will add 3 ops to gates_mapped, so subtract 3.
return len([g for g in step['gates_mapped']
if len(g.qargs) == 2]) - 3 * step['swaps_added']
def _copy_circuit_metadata(source_dag, coupling_map):
"""Return a copy of source_dag with metadata but empty.
Generate only a single qreg in the output DAG, matching the size of the
coupling_map."""
target_dag = DAGCircuit()
target_dag.name = source_dag.name
for creg in source_dag.cregs.values():
target_dag.add_creg(creg)
device_qreg = QuantumRegister(len(coupling_map.physical_qubits), 'q')
target_dag.add_qreg(device_qreg)
return target_dag
def _transform_gate_for_layout(gate, layout):
"""Return op implementing a virtual gate on given layout."""
mapped_op_node = deepcopy([n for n in gate['graph'].nodes() if n.type == 'op'][0])
# Workaround until #1816, apply mapped to qargs to both DAGNode and op
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
mapped_qargs = [(device_qreg, layout[a]) for a in mapped_op_node.qargs]
mapped_op_node.qargs = mapped_op_node.op.qargs = mapped_qargs
mapped_op_node.pop('name')
return mapped_op_node
def _swap_ops_from_edge(edge, layout):
"""Generate list of ops to implement a SWAP gate along a coupling edge."""
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
qreg_edge = [(device_qreg, i) for i in edge]
# TODO shouldn't be making other nodes not by the DAG!!
return [
DAGNode({'op': SwapGate(), 'qargs': qreg_edge, 'cargs': [], 'type': 'op'})
]
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# TODO: Remove after 0.7 and the deprecated methods are removed
# pylint: disable=unused-argument
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
from PIL import Image
from qiskit import user_config
from qiskit.visualization import exceptions
from qiskit.visualization import latex as _latex
from qiskit.visualization import text as _text
from qiskit.visualization import utils
from qiskit.visualization import matplotlib as _matplotlib
logger = logging.getLogger(__name__)
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Args:
circuit (QuantumCircuit): the quantum circuit to draw
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. By
default the 'text' drawer is used unless a user config file has
an alternative backend set as the default. If the output is passed
in that backend will always be used.
interactive (bool): when set true show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be silently
ignored.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). However, if you're running in
jupyter the default line length is set to 80 characters. If you
don't want pagination at all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (string): Options are `left`, `right` or `none`, if anything
else is supplied it defaults to left justified. It refers to where
gates should be placed in the output circuit if there is an option.
`none` results in each gate being placed in its own column. Currently
only supported by text drawer.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requieres non-installed libraries.
.. _style-dict-doc:
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'id': 'id',
'u0': 'U_0',
'u1': 'U_1',
'u2': 'U_2',
'u3': 'U_3',
'x': 'X',
'y': 'Y',
'z': 'Z',
'h': 'H',
's': 'S',
'sdg': 'S^\\dagger',
't': 'T',
'tdg': 'T^\\dagger',
'rx': 'R_x',
'ry': 'R_y',
'rz': 'R_z',
'reset': '\\left|0\\right\\rangle'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
"""
image = None
config = user_config.get_config()
# Get default from config file else use text
default_output = 'text'
if config:
default_output = config.get('circuit_drawer', 'text')
if output is None:
output = default_output
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename,
line_length=line_length,
reverse_bits=reverse_bits,
plotbarriers=plot_barriers,
justify=justify)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
elif output == 'latex_source':
return _generate_latex_source(circuit,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
else:
raise exceptions.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"id": "id",
"u0": "U_0",
"u1": "U_1",
"u2": "U_2",
"u3": "U_3",
"x": "X",
"y": "Y",
"z": "Z",
"h": "H",
"s": "S",
"sdg": "S^\\dagger",
"t": "T",
"tdg": "T^\\dagger",
"rx": "R_x",
"ry": "R_y",
"rz": "R_z",
"reset": "\\left|0\\right\\rangle"
},
"displaycolor": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None, line_length=None, reverse_bits=False,
plotbarriers=True, justify=None, vertically_compressed=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reverse_bits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
vertically_compressed (bool): Default is `True`. It merges the lines so the
drawing will take less vertical room.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
reverse_bits=reverse_bits,
justify=justify)
text_drawing = _text.TextDrawing(qregs, cregs, ops)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
text_drawing.vertically_compressed = vertically_compressed
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits, justify=justify)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True, justify=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
str: Latex string appropriate for writing to file.
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
reverse_bits=reverse_bits,
justify=justify)
qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
reverse_bits=reverse_bits,
justify=justify)
qcd = _matplotlib.MatplotlibDrawer(qregs, cregs, ops, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
return qcd.draw(filename)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit_chemistry import FermionicOperator
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit.quantum_info import Pauli
from qiskit_aqua import Operator
from qiskit_aqua.algorithms import IQPE, ExactEigensolver
from qiskit import Aer,QuantumRegister
from qiskit import execute
import yaml as yml
from yaml import SafeLoader as Loader
import numpy as np
import Load_Hamiltonians as lh
from scipy import linalg as las
def construct_twoqubit_pauliham(hI,h0,h1,h2,h3,h4):
return [[hI,Pauli(label='II')],[h0,Pauli(label='IZ')],[h1,Pauli(label='ZI')],[h2,Pauli(label='XX')],[h3,Pauli(label='YY')],[h4,Pauli(label='ZZ')]]
map_type = 'jordan_wigner'
backend = Aer.get_backend('qasm_simulator')
# backend = Aer.get_backend('unitary_simulator')
NW_data_file = str('/Users/mmetcalf/Dropbox/Quantum Embedding/Codes/Lithium_Downfolding/Qiskit Chem/HamiltonianDownfolding_w_IBM/H2.yaml')
print('First File', NW_data_file)
try:
doc = open(NW_data_file, 'r')
data = yml.load(doc, Loader)
finally:
doc.close()
# Import all the data from a yaml file
print('Getting data')
n_spatial_orbitals = data['integral_sets'][0]['n_orbitals']
print('{} spatial orbitals'.format(n_spatial_orbitals))
nuclear_repulsion_energy = data['integral_sets'][0]['coulomb_repulsion']['value']
print('{} Coloumb repulsion'.format(nuclear_repulsion_energy))
n_orbitals = 2 * n_spatial_orbitals
n_particles = data['integral_sets'][0]['n_electrons']
print('{} particles'.format(n_particles))
dist = 2 * data['integral_sets'][0]['geometry']['atoms'][1]['coords'][2]
print('Bond distance is {}'.format(dist))
if map_type == 'parity':
# For two-qubit reduction
n_qubits = n_orbitals - 2
else:
n_qubits = n_orbitals
# Importing the integrals
one_electron_import = data['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values']
two_electron_import = data['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values']
# Getting spatial integrals and spin integrals to construct Hamiltonian
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_electron_import,
two_electron_import,
n_spatial_orbitals)
h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals,two_electron_spatial_integrals,n_spatial_orbitals, .01)
fop = FermionicOperator(h1, h2)
qop_paulis = fop.mapping(map_type)
# #print(qop_paulis._paulis)
# qop1 = Operator(paulis=qop_paulis.paulis)
# qop2 = Operator(paulis=qop_paulis.paulis)
#print(id(qop1),' and ', id(qop2))
init_state = HartreeFock(n_qubits, n_orbitals, n_particles, map_type, two_qubit_reduction=False)
#Hamiltonian from Google Paper
hI = -0.2265
h0 = 0.1843
h1 = -0.0549
h2 = 0.1165
h3 = 0.1165
h4 = 0.4386
t_0 = 9.830
#this function returns a list of pauli operators
google_pauliham = construct_twoqubit_pauliham(hI,h0,h1,h2,h3,h4)
google_op = Operator(paulis=google_pauliham)
google_init_state = HartreeFock(num_qubits=2, num_orbitals=2, num_particles=1, qubit_mapping=map_type, two_qubit_reduction=False)
# a = QuantumRegister(1, name='a')
# q = QuantumRegister(2, name='q')
# Circuit = google_op.construct_evolution_circuit(google_pauliham,t_0 , 1, q,
# ancillary_registers=a, ctl_idx=0, unitary_power=None, use_basis_gates=False,
# shallow_slicing=False)
# print(Circuit)
# result = execute(Circuit, backend).result()
# unitary = result.get_unitary(Circuit)
# print("Circuit unitary:\n", unitary)
# eval, evec = las.eigh(unitary)
# print(eval[0])
k = 7
#print('{} are the Paulis before'.format(qop2.paulis))
algorithm = IQPE(operator=google_op, state_in=google_init_state, num_time_slices=1, num_iterations=k, paulis_grouping='random', expansion_mode='trotter')
#print('New location of other op:', id(qop2))
#manually
# algorithm.identity_phase()
# qc_pea = algorithm.construct_circuit(k=1,omega=0)
# alg = execute(qc_pea, backend)
# result = alg.result()
# count = result.get_counts(qc_pea)
# print(qc_pea)
# print('{} are the state populations'.format(count))
result = algorithm.run(backend)
iqpe_energy = result['energy']
print('{} is the energy i got for {} iterations'.format(iqpe_energy,k))
# exact_eigensolver = ExactEigensolver(operator=google_op, k=2)
# ret = exact_eigensolver.run()
# print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real ))
|
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.
"""
This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations
variational form.
For more information, see https://arxiv.org/abs/1805.04340
"""
import logging
import sys
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.tools import parallel_map
from qiskit.tools.events import TextProgressBar
from qiskit.aqua import Operator, aqua_globals
from qiskit.aqua.components.variational_forms import VariationalForm
from qiskit.chemistry.fermionic_operator import FermionicOperator
from qiskit.chemistry import MP2Info
from qiskit.chemistry import QMolecule as qm
logger = logging.getLogger(__name__)
class UCCSD(VariationalForm):
"""
This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations
variational form.
For more information, see https://arxiv.org/abs/1805.04340
"""
CONFIGURATION = {
'name': 'UCCSD',
'description': 'UCCSD Variational Form',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'uccsd_schema',
'type': 'object',
'properties': {
'depth': {
'type': 'integer',
'default': 1,
'minimum': 1
},
'num_orbitals': {
'type': 'integer',
'default': 4,
'minimum': 1
},
'num_particles': {
'type': 'integer',
'default': 2,
'minimum': 1
},
'active_occupied': {
'type': ['array', 'null'],
'default': None
},
'active_unoccupied': {
'type': ['array', 'null'],
'default': None
},
'qubit_mapping': {
'type': 'string',
'default': 'parity',
'oneOf': [
{'enum': ['jordan_wigner', 'parity', 'bravyi_kitaev']}
]
},
'two_qubit_reduction': {
'type': 'boolean',
'default': False
},
'mp2_reduction': {
'type': 'boolean',
'default': False
},
'num_time_slices': {
'type': 'integer',
'default': 1,
'minimum': 1
},
},
'additionalProperties': False
},
'depends': [
{
'pluggable_type': 'initial_state',
'default': {
'name': 'HartreeFock',
}
},
],
}
def __init__(self, num_qubits, depth, num_orbitals, num_particles,
active_occupied=None, active_unoccupied=None, initial_state=None,
qubit_mapping='parity', two_qubit_reduction=False, mp2_reduction=False, num_time_slices=1,
cliffords=None, sq_list=None, tapering_values=None, symmetries=None,
shallow_circuit_concat=True):
"""Constructor.
Args:
num_orbitals (int): number of spin orbitals
depth (int): number of replica of basic module
num_particles (int): number of particles
active_occupied (list): list of occupied orbitals to consider as active space
active_unoccupied (list): list of unoccupied orbitals to consider as active space
initial_state (InitialState): An initial state object.
qubit_mapping (str): qubit mapping type.
two_qubit_reduction (bool): two qubit reduction is applied or not.
num_time_slices (int): parameters for dynamics.
cliffords ([Operator]): list of unitary Clifford transformation
sq_list ([int]): position of the single-qubit operators that anticommute
with the cliffords
tapering_values ([int]): array of +/- 1 used to select the subspace. Length
has to be equal to the length of cliffords and sq_list
symmetries ([Pauli]): represent the Z2 symmetries
shallow_circuit_concat (bool): indicate whether to use shallow (cheap) mode for circuit concatenation
"""
self.validate(locals())
super().__init__()
self._cliffords = cliffords
self._sq_list = sq_list
self._tapering_values = tapering_values
self._symmetries = symmetries
if self._cliffords is not None and self._sq_list is not None and \
self._tapering_values is not None and self._symmetries is not None:
self._qubit_tapering = True
else:
self._qubit_tapering = False
self._num_qubits = num_orbitals if not two_qubit_reduction else num_orbitals - 2
self._num_qubits = self._num_qubits if not self._qubit_tapering else self._num_qubits - len(sq_list)
if self._num_qubits != num_qubits:
raise ValueError('Computed num qubits {} does not match actual {}'
.format(self._num_qubits, num_qubits))
self._depth = depth
self._num_orbitals = num_orbitals
self._num_particles = num_particles
if self._num_particles > self._num_orbitals:
raise ValueError('# of particles must be less than or equal to # of orbitals.')
self._initial_state = initial_state
self._qubit_mapping = qubit_mapping
self._two_qubit_reduction = two_qubit_reduction
self._num_time_slices = num_time_slices
self._shallow_circuit_concat = shallow_circuit_concat
self._single_excitations, self._double_excitations = \
UCCSD.compute_excitation_lists(num_particles, num_orbitals,
active_occupied, active_unoccupied)
self._single_excitations = []
print('{} are the old doubles'.format(self._double_excitations))
print(mp2_reduction)
if mp2_reduction:
print('Getting new doubles')
self._double_excitations = get_mp2_doubles(self._single_excitations,self._double_excitations)
print('{} are the new doubles'.format(self._double_excitations))
self._hopping_ops, self._num_parameters = self._build_hopping_operators()
self._bounds = [(-np.pi, np.pi) for _ in range(self._num_parameters)]
self._logging_construct_circuit = True
def _build_hopping_operators(self):
from .uccsd import UCCSD
hopping_ops = []
if logger.isEnabledFor(logging.DEBUG):
TextProgressBar(sys.stderr)
results = parallel_map(UCCSD._build_hopping_operator, self._single_excitations + self._double_excitations,
task_args=(self._num_orbitals, self._num_particles,
self._qubit_mapping, self._two_qubit_reduction, self._qubit_tapering,
self._symmetries, self._cliffords, self._sq_list, self._tapering_values),
num_processes=aqua_globals.num_processes)
hopping_ops = [qubit_op for qubit_op in results if qubit_op is not None]
num_parameters = len(hopping_ops) * self._depth
return hopping_ops, num_parameters
@staticmethod
def _build_hopping_operator(index, num_orbitals, num_particles, qubit_mapping,
two_qubit_reduction, qubit_tapering, symmetries,
cliffords, sq_list, tapering_values):
def check_commutativity(op_1, op_2):
com = op_1 * op_2 - op_2 * op_1
com.zeros_coeff_elimination()
return True if com.is_empty() else False
h1 = np.zeros((num_orbitals, num_orbitals))
h2 = np.zeros((num_orbitals, num_orbitals, num_orbitals, num_orbitals))
if len(index) == 2:
i, j = index
h1[i, j] = 1.0
h1[j, i] = -1.0
elif len(index) == 4:
i, j, k, m = index
h2[i, j, k, m] = 1.0
h2[m, k, j, i] = -1.0
dummpy_fer_op = FermionicOperator(h1=h1, h2=h2)
qubit_op = dummpy_fer_op.mapping(qubit_mapping)
qubit_op = qubit_op.two_qubit_reduced_operator(num_particles) \
if two_qubit_reduction else qubit_op
if qubit_tapering:
for symmetry in symmetries:
symmetry_op = Operator(paulis=[[1.0, symmetry]])
symm_commuting = check_commutativity(symmetry_op, qubit_op)
if not symm_commuting:
break
if qubit_tapering:
if symm_commuting:
qubit_op = Operator.qubit_tapering(qubit_op, cliffords,
sq_list, tapering_values)
else:
qubit_op = None
if qubit_op is None:
logger.debug('Excitation ({}) is skipped since it is not commuted '
'with symmetries'.format(','.join([str(x) for x in index])))
return qubit_op
def construct_circuit(self, parameters, q=None):
"""
Construct the variational form, given its parameters.
Args:
parameters (numpy.ndarray): circuit parameters
q (QuantumRegister): Quantum Register for the circuit.
Returns:
QuantumCircuit: a quantum circuit with given `parameters`
Raises:
ValueError: the number of parameters is incorrect.
"""
from .uccsd import UCCSD
if len(parameters) != self._num_parameters:
raise ValueError('The number of parameters has to be {}'.format(self._num_parameters))
if q is None:
q = QuantumRegister(self._num_qubits, name='q')
if self._initial_state is not None:
circuit = self._initial_state.construct_circuit('circuit', q)
else:
circuit = QuantumCircuit(q)
if logger.isEnabledFor(logging.DEBUG) and self._logging_construct_circuit:
logger.debug("Evolving hopping operators:")
TextProgressBar(sys.stderr)
self._logging_construct_circuit = False
num_excitations = len(self._hopping_ops)
results = parallel_map(UCCSD._construct_circuit_for_one_excited_operator,
[(self._hopping_ops[index % num_excitations], parameters[index])
for index in range(self._depth * num_excitations)],
task_args=(q, self._num_time_slices),
num_processes=aqua_globals.num_processes)
for qc in results:
if self._shallow_circuit_concat:
circuit.data += qc.data
else:
circuit += qc
return circuit
@staticmethod
def _construct_circuit_for_one_excited_operator(qubit_op_and_param, qr, num_time_slices):
qubit_op, param = qubit_op_and_param
qc = qubit_op.evolve(None, param * -1j, 'circuit', num_time_slices, qr)
return qc
@property
def preferred_init_points(self):
"""Getter of preferred initial points based on the given initial state."""
if self._initial_state is None:
return None
else:
bitstr = self._initial_state.bitstr
if bitstr is not None:
return np.zeros(self._num_parameters, dtype=np.float)
else:
return None
@staticmethod
def compute_excitation_lists(num_particles, num_orbitals, active_occ_list=None,
active_unocc_list=None, same_spin_doubles=True):
"""
Computes single and double excitation lists
Args:
num_particles: Total number of particles
num_orbitals: Total number of spin orbitals
active_occ_list: List of occupied orbitals to include, indices are
0 to n where n is num particles // 2
active_unocc_list: List of unoccupied orbitals to include, indices are
0 to m where m is (num_orbitals - num particles) // 2
same_spin_doubles: True to include alpha,alpha and beta,beta double excitations
as well as alpha,beta pairings. False includes only alpha,beta
Returns:
Single and double excitation lists
"""
if num_particles < 2 or num_particles % 2 != 0:
raise ValueError('Invalid number of particles {}'.format(num_particles))
if num_orbitals < 4 or num_orbitals % 2 != 0:
raise ValueError('Invalid number of orbitals {}'.format(num_orbitals))
if num_orbitals <= num_particles:
raise ValueError('No unoccupied orbitals')
if active_occ_list is not None:
active_occ_list = [i if i >= 0 else i + num_particles // 2 for i in active_occ_list]
for i in active_occ_list:
if i >= num_particles // 2:
raise ValueError('Invalid index {} in active active_occ_list {}'
.format(i, active_occ_list))
if active_unocc_list is not None:
active_unocc_list = [i + num_particles // 2 if i >=
0 else i + num_orbitals // 2 for i in active_unocc_list]
for i in active_unocc_list:
if i < 0 or i >= num_orbitals // 2:
raise ValueError('Invalid index {} in active active_unocc_list {}'
.format(i, active_unocc_list))
if active_occ_list is None or len(active_occ_list) <= 0:
active_occ_list = [i for i in range(0, num_particles // 2)]
if active_unocc_list is None or len(active_unocc_list) <= 0:
active_unocc_list = [i for i in range(num_particles // 2, num_orbitals // 2)]
single_excitations = []
double_excitations = []
logger.debug('active_occ_list {}'.format(active_occ_list))
logger.debug('active_unocc_list {}'.format(active_unocc_list))
beta_idx = num_orbitals // 2
for occ_alpha in active_occ_list:
for unocc_alpha in active_unocc_list:
single_excitations.append([occ_alpha, unocc_alpha])
for occ_beta in [i + beta_idx for i in active_occ_list]:
for unocc_beta in [i + beta_idx for i in active_unocc_list]:
single_excitations.append([occ_beta, unocc_beta])
for occ_alpha in active_occ_list:
for unocc_alpha in active_unocc_list:
for occ_beta in [i + beta_idx for i in active_occ_list]:
for unocc_beta in [i + beta_idx for i in active_unocc_list]:
double_excitations.append([occ_alpha, unocc_alpha, occ_beta, unocc_beta])
if same_spin_doubles and len(active_occ_list) > 1 and len(active_unocc_list) > 1:
for i, occ_alpha in enumerate(active_occ_list[:-1]):
for j, unocc_alpha in enumerate(active_unocc_list[:-1]):
for occ_alpha_1 in active_occ_list[i + 1:]:
for unocc_alpha_1 in active_unocc_list[j + 1:]:
double_excitations.append([occ_alpha, unocc_alpha,
occ_alpha_1, unocc_alpha_1])
up_active_occ_list = [i + beta_idx for i in active_occ_list]
up_active_unocc_list = [i + beta_idx for i in active_unocc_list]
for i, occ_beta in enumerate(up_active_occ_list[:-1]):
for j, unocc_beta in enumerate(up_active_unocc_list[:-1]):
for occ_beta_1 in up_active_occ_list[i + 1:]:
for unocc_beta_1 in up_active_unocc_list[j + 1:]:
double_excitations.append([occ_beta, unocc_beta,
occ_beta_1, unocc_beta_1])
logger.debug('single_excitations ({}) {}'.format(len(single_excitations), single_excitations))
logger.debug('double_excitations ({}) {}'.format(len(double_excitations), double_excitations))
return single_excitations, double_excitations
def get_mp2_doubles(single_excitations, double_excitations):
print('Is the class still populated with the correct info: ', qm.nuclear_repulsion_energy)
mp2 = MP2Info(qm, single_excitations, double_excitations, threshold=1e-3)
mp2_doubles = mp2._mp2_doubles
return mp2_doubles
|
https://github.com/harshagarine/QISKIT_INDIA_CHALLENGE
|
harshagarine
|
### WRITE YOUR CODE BETWEEN THESE LINES - START
# import libraries that are used in the function below.
from qiskit import QuantumCircuit
import numpy as np
from math import sqrt, pi
### WRITE YOUR CODE BETWEEN THESE LINES - END
def build_state():
circuit = QuantumCircuit(1)
initial_state = [0,1]
circuit.initialize(initial_state, 0)
circuit.ry(pi/3,0)
### WRITE YOUR CODE BETWEEN THESE LINES - END
return circuit
|
https://github.com/harshagarine/QISKIT_INDIA_CHALLENGE
|
harshagarine
|
### WRITE YOUR CODE BETWEEN THESE LINES - START
# import libraries that are used in the function below.
from qiskit import QuantumCircuit
import numpy as np
from math import sqrt, pi
### WRITE YOUR CODE BETWEEN THESE LINES - END
def build_state():
# create a quantum circuit on one qubit
circuit = QuantumCircuit(1)
### WRITE YOUR CODE BETWEEN THESE LINES - START
init = [1/sqrt(2),0-1j/sqrt(2)]
circuit.initialize(init,0)
# apply necessary gates
circuit.rx(pi/2,0)
### WRITE YOUR CODE BETWEEN THESE LINES - END
return circuit
|
https://github.com/harshagarine/QISKIT_INDIA_CHALLENGE
|
harshagarine
|
### WRITE YOUR CODE BETWEEN THESE LINES - START
# import libraries that are used in the function below.
from qiskit import QuantumCircuit
import numpy as np
### WRITE YOUR CODE BETWEEN THESE LINES - END
def build_state():
# create a quantum circuit on two qubits
circuit = QuantumCircuit(2)
qc = QuantumCircuit(2,2)
qc.h(0)
qc.x(1)
qc.cx(0, 1)
qc.z(0)
return qc
return circuit
|
https://github.com/harshagarine/QISKIT_INDIA_CHALLENGE
|
harshagarine
|
### WRITE YOUR CODE BETWEEN THESE LINES - START
# import libraries that are used in the function below.
from qiskit import QuantumCircuit
import numpy as np
### WRITE YOUR CODE BETWEEN THESE LINES - END
def build_state():
# initialize a 3 qubit circuit
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
return qc
### WRITE YOUR CODE BETWEEN THESE LINES - START
# apply necessary gates
### WRITE YOUR CODE BETWEEN THESE LINES - END
return circuit
|
https://github.com/harshagarine/QISKIT_INDIA_CHALLENGE
|
harshagarine
|
### WRITE YOUR CODE BETWEEN THESE LINES - START
# import libraries that are used in the functions below.
from qiskit import QuantumCircuit
import numpy as np
### WRITE YOUR CODE BETWEEN THESE LINES - END
def init_circuit():
# create a quantum circuit on two qubits
qc = QuantumCircuit(2)
# initializing the circuit
qc.h(0)
qc.x(1)
return qc
# The initial state has been defined above.
# You'll now have to apply necessary gates in the build_state() function to convert the state as asked in the question.
def build_state():
### WRITE YOUR CODE BETWEEN THESE LINES - START
# the initialized circuit
circuit = init_circuit()
# apply a single cu3 gate
circuit.cu3(0, -np.pi/2, 0, 0, 1)
### WRITE YOUR CODE BETWEEN THESE LINES - END
return circuit
|
https://github.com/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
|
Aman-Agrawal01
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
qr1 = QuantumRegister(2)
cr1 = ClassicalRegister(2)
circuit1 = QuantumCircuit(qr1,cr1)
circuit1.draw(output='mpl')
circuit1.h(qr1[0])
circuit1.draw(output='mpl')
circuit1.cx(qr1[0],qr1[1])
circuit1.draw(output='mpl')
circuit1.measure(qr1,cr1)
circuit1.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result1 = execute(circuit1,backend=simulator).result()
plot_histogram(result1.get_counts())
qr2 = QuantumRegister(2)
cr2 = ClassicalRegister(2)
circuit2 = QuantumCircuit(qr2,cr2)
circuit2.draw(output='mpl')
circuit2.h(qr2[0])
circuit2.x(qr2[1])
circuit2.draw(output='mpl')
circuit2.cx(control_qubit=qr2[0],target_qubit=qr2[1])
circuit2.draw(output='mpl')
circuit2.measure(qr2,cr2)
circuit2.draw(output='mpl')
result2 = execute(circuit2,backend=simulator).result()
plot_histogram(result2.get_counts())
|
https://github.com/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
|
Aman-Agrawal01
|
from qiskit import *
%matplotlib inline
import numpy as np
from qiskit.visualization import plot_histogram
n = 2 #Number of qubits
qr1 = QuantumRegister(size=n)
qr2 = QuantumRegister(size=1)
cr = ClassicalRegister(size=n)
def function(circuit,fn):
if fn == 'const-0':
circuit.x(qr2)
circuit.barrier()
circuit.h(qr1)
circuit.h(qr2)
circuit.barrier()
circuit.barrier()
circuit.h(qr1)
circuit.barrier()
circuit.measure(qr1,cr)
elif fn == 'const-1':
circuit.x(qr2)
circuit.barrier()
circuit.h(qr1)
circuit.h(qr2)
circuit.barrier()
circuit.x(qr1)
circuit.barrier()
circuit.h(qr1)
circuit.barrier()
circuit.measure(qr1,cr)
elif fn == 'balanced':
circuit.x(qr2)
circuit.barrier()
circuit.h(qr1)
circuit.h(qr2)
circuit.barrier()
circuit.cx(qr1[0],qr2)
circuit.barrier()
circuit.h(qr1)
circuit.barrier()
circuit.measure(qr1,cr)
return circuit
circuit_1 = QuantumCircuit(qr1,qr2,cr)
circuit_1 = function(circuit_1,'const-1')
circuit_1.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit_1,backend=simulator).result()
plot_histogram(result.get_counts())
circuit_0 = QuantumCircuit(qr1,qr2,cr)
circuit_0 = function(circuit_0,'const-0')
circuit_0.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit_0,backend=simulator).result()
plot_histogram(result.get_counts())
circuit_b = QuantumCircuit(qr1,qr2,cr)
circuit_b = function(circuit_b,'balanced')
circuit_b.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit_b,backend=simulator).result()
plot_histogram(result.get_counts())
|
https://github.com/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
|
Aman-Agrawal01
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
qr1 = QuantumRegister(size=2,name='numbers')
qr2 = QuantumRegister(size=1,name='answer-bit')
qr3 = QuantumRegister(size=1,name='carry-bit')
cr1 = ClassicalRegister(size=1,name='answer-cbit')
cr2 = ClassicalRegister(size=1,name='carry-cbit')
circuit = QuantumCircuit(qr1,qr2,qr3,cr1,cr2)
circuit.x(qr1)
circuit.barrier()
circuit.draw(output='mpl')
circuit.cx(control_qubit=qr1[0],target_qubit=qr2)
circuit.cx(control_qubit=qr1[1],target_qubit=qr2)
circuit.draw(output='mpl')
circuit.ccx(control_qubit1=qr1[0],control_qubit2=qr1[1],target_qubit=qr3)
circuit.barrier()
circuit.draw(output='mpl')
circuit.measure(qr2,cr1)
circuit.measure(qr3,cr2)
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit,backend=simulator).result()
plot_histogram(result.get_counts())
|
https://github.com/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
|
Aman-Agrawal01
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
### Creating 3 qubit and 2 classical bits in each separate register
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
### A third party eve helps to create an entangled state
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a, b)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, a, b):
qc.cx(a, b)
qc.h(a)
teleportation_circuit.barrier()
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
teleportation_circuit.barrier()
measure_and_send(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1)
qc.z(qubit).c_if(crz, 1)
teleportation_circuit.barrier()
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
from qiskit.extensions import Initialize
import math
qc = QuantumCircuit(1)
initial_state = [0,1]
init_gate = Initialize(initial_state)
# qc.append(initialize_qubit, [0])
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical registers
crx = ClassicalRegister(1)
qc = QuantumCircuit(qr, crz, crx)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
out_vector = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(out_vector)
inverse_init_gate = init_gate.gates_to_uncompute()
qc.append(inverse_init_gate, [2])
qc.draw()
cr_result = ClassicalRegister(1)
qc.add_register(cr_result)
qc.measure(2,2)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1024).result().get_counts()
plot_histogram(counts)
def bob_gates(qc, a, b, c):
qc.cz(a, c)
qc.cx(b, c)
qc = QuantumCircuit(3,1)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
qc.barrier()
# Alice sends classical bits to Bob
bob_gates(qc, 0, 1, 2)
# We undo the initialisation process
qc.append(inverse_init_gate, [2])
# See the results, we only care about the state of qubit 2
qc.measure(2,0)
# View the results:
qc.draw()
from qiskit import IBMQ
IBMQ.save_account('### IMB TOKEN ')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
job_exp = execute(qc, backend=backend, shots=8192)
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(qc)
print(exp_measurement_result)
plot_histogram(exp_measurement_result)
error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \
* 100./ sum(list(exp_measurement_result.values()))
print("The experimental error rate : ", error_rate_percent, "%")
|
https://github.com/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
|
Aman-Agrawal01
|
from qiskit import *
%matplotlib inline
qc = QuantumRegister(size=2)
circuit = QuantumCircuit(qc)
circuit.draw(output='mpl')
circuit.cx(control_qubit=qc[0],target_qubit=qc[1])
circuit.cx(control_qubit=qc[1],target_qubit=qc[0])
circuit.cx(control_qubit=qc[0],target_qubit=qc[1])
circuit.draw(output='mpl')
|
https://github.com/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
|
Aman-Agrawal01
|
from qiskit import *
%matplotlib inline
import numpy as np
from qiskit.visualization import plot_histogram
n = 2 #Number of qubits
qr1 = QuantumRegister(size=n)
qr2 = QuantumRegister(size=1)
cr = ClassicalRegister(size=n)
def function(circuit,fn):
if fn == 'const-0':
circuit.x(qr2)
circuit.barrier()
circuit.h(qr1)
circuit.h(qr2)
circuit.barrier()
circuit.barrier()
circuit.h(qr1)
circuit.barrier()
circuit.measure(qr1,cr)
elif fn == 'const-1':
circuit.x(qr2)
circuit.barrier()
circuit.h(qr1)
circuit.h(qr2)
circuit.barrier()
circuit.x(qr1)
circuit.barrier()
circuit.h(qr1)
circuit.barrier()
circuit.measure(qr1,cr)
elif fn == 'balanced':
circuit.x(qr2)
circuit.barrier()
circuit.h(qr1)
circuit.h(qr2)
circuit.barrier()
circuit.cx(qr1[0],qr2)
circuit.barrier()
circuit.h(qr1)
circuit.barrier()
circuit.measure(qr1,cr)
return circuit
circuit_1 = QuantumCircuit(qr1,qr2,cr)
circuit_1 = function(circuit_1,'const-1')
circuit_1.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit_1,backend=simulator).result()
plot_histogram(result.get_counts())
circuit_0 = QuantumCircuit(qr1,qr2,cr)
circuit_0 = function(circuit_0,'const-0')
circuit_0.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit_0,backend=simulator).result()
plot_histogram(result.get_counts())
circuit_b = QuantumCircuit(qr1,qr2,cr)
circuit_b = function(circuit_b,'balanced')
circuit_b.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit_b,backend=simulator).result()
plot_histogram(result.get_counts())
|
https://github.com/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
|
Aman-Agrawal01
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
qr1 = QuantumRegister(size=2,name='numbers')
qr2 = QuantumRegister(size=1,name='answer-bit')
qr3 = QuantumRegister(size=1,name='carry-bit')
cr1 = ClassicalRegister(size=1,name='answer-cbit')
cr2 = ClassicalRegister(size=1,name='carry-cbit')
circuit = QuantumCircuit(qr1,qr2,qr3,cr1,cr2)
circuit.x(qr1)
circuit.barrier()
circuit.draw(output='mpl')
circuit.cx(control_qubit=qr1[0],target_qubit=qr2)
circuit.cx(control_qubit=qr1[1],target_qubit=qr2)
circuit.draw(output='mpl')
circuit.ccx(control_qubit1=qr1[0],control_qubit2=qr1[1],target_qubit=qr3)
circuit.barrier()
circuit.draw(output='mpl')
circuit.measure(qr2,cr1)
circuit.measure(qr3,cr2)
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit,backend=simulator).result()
plot_histogram(result.get_counts())
|
https://github.com/Victor1128/shor-qiskit
|
Victor1128
|
from qiskit import QuantumCircuit, Aer, execute, IBMQ
from qiskit.utils import QuantumInstance
import numpy as np
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
my_shor = Shor(quantum_instance)
result_dict = my_shor.factor(15)
print(result_dict)
|
https://github.com/a24l/IBM_Qiskit_QGSS
|
a24l
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
qc.z(0)
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
qc.h(0)
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
qc.h(0)
qc.z(0)
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
qc.h(0)
qc.y(0)
qc.sdg(0)
qc.sdg(0)
qc.sdg(0)
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
qc.h(0)
qc.cx(0,1)
qc.x(1)
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
qc = QuantumCircuit(3,3) # this time, we not only want two qubits, but also two classical bits for the measurement
qc.h(0)
qc.cx(0,1)
qc.x(1)
qc.cx(1,2)
qc.y(2)
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2# put your answer here
max_nr_inputs = 9# put your answer here
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
qc.x(4)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
for qubit in range(n+1):
qc.h(qubit)
# create the superposition state |psi_1>
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
for qubit in range(n):
qc.h(qubit)
# add the measurement by connecting qubits to classical bits
#
#
# FILL YOUR CODE IN HERE
#
#
for i in range(n):
qc.measure(i, i)
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/a24l/IBM_Qiskit_QGSS
|
a24l
|
import numpy as np
from numpy import pi
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader.challenges.qgss_2022 import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader.challenges.qgss_2022 import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader.challenges.qgss_2022 import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0)
qc.s(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader.challenges.qgss_2022 import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
# This time, we not only want two qubits, but also two classical bits for the measurement
qc = QuantumCircuit(2)
#
#
qc.h(0)
qc.x(1)
qc.cx(0,1)
#
#
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader.challenges.qgss_2022 import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure_all() # we measure all the qubits
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
# This time, we need 3 qubits and also add 3 classical bits in case we want to measure
qc = QuantumCircuit(3)
qc.x(0)
qc.h(0)
qc.x(1)
qc.cx(1,2)
qc.cx(0,2)
qc.cx(0,1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
qc.measure_all() # we measure all the qubits
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
from qc_grader.challenges.qgss_2022 import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
print(qc.size())
print(qc.num_nonlocal_gates())
def qft_rotations(circuit, n):
"""Performs qft on the first n qubits in circuit (without swaps)"""
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
# At the end of our function, we call the same function again on
# the next qubits (we reduced n by one earlier in the function)
qft_rotations(circuit, n)
def swap_registers(circuit, n):
"""Swaps registers to match the definition"""
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
"""QFT on the first n qubits in circuit"""
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
qft_rotations(qc,3)
print(qc.size())
print(qc.num_nonlocal_gates())
qc.draw()
def lab1_ex7(n:int) -> int:
#Here we want you to build a function calculating the number of gates needed by the fourier rotation for n qubits.
#numberOfGates=0
#
# FILL YOUR CODE IN HERE
# TRY TO FIND AN EXPLIZIT (NON RECURSIVE) FUNCTION
numberOfGates = (n*(n+1))/2
#
return numberOfGates
print(lab1_ex7(3))
print(lab1_ex7(4))
print(lab1_ex7(5))
print(lab1_ex7(10))
print(lab1_ex7(100))
print(lab1_ex7(200))
# Lab 1, Exercise 7
from qc_grader.challenges.qgss_2022 import grade_lab1_ex7
# Note that the grading function is expecting as input a function!
#(And the function takes n as an input and outputs the number of gates constructed)
grade_lab1_ex7(lab1_ex7)
qc = QuantumCircuit(4)
qc.h(0)
qc.s(0)
qc.s(0)
qc.s(0)
qc.cx(0,1)
qc.cx(1,3)
print(qc.depth())
qc.draw()
qc2 = QuantumCircuit(4)
qc2.h(0)
qc2.s(1)
qc2.cx(0,1)
qc2.s(2)
qc2.s(3)
qc2.cx(2,3)
print(qc2.depth())
qc2.draw()
qc = QuantumCircuit(16)
#Step 1: Preparing the first qubit in superposition
qc.h(0)
#Step 2: Entangling all other qubits with it (1 is included 16 is exclude)
for x in range(1, 16):
qc.cx(0,x)
print(qc.depth())
qc.draw()
def lab1_ex8():
qc = QuantumCircuit(16) #Same as above
#Step 1: Preparing the first qubit in superposition
qc.h(0)
qc.cx(0,3)
qc.cx(0,1)
qc.cx(3,5)
qc.cx(0,7)
qc.cx(7,8)
qc.cx(5,6)
qc.cx(1,2)
qc.cx(3,4)
qc.cx(0,9)
for i in range(1,7):
qc.cx(i, 9+i)
return qc
qc = lab1_ex8()
print(qc.depth())
qc.draw()
from qc_grader.challenges.qgss_2022 import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex8(lab1_ex8())
|
https://github.com/a24l/IBM_Qiskit_QGSS
|
a24l
|
!pip install -U -r resources/requirements.txt
from IPython.display import clear_output
clear_output()
from qiskit import QuantumCircuit
mycircuit = QuantumCircuit(1)
mycircuit.draw('mpl')
from qiskit.quantum_info import Statevector
sv = Statevector.from_label('0')
sv
sv.data
new_sv = sv.evolve(mycircuit)
new_sv
from qiskit.quantum_info import state_fidelity
state_fidelity(sv, new_sv)
from qiskit.visualization import plot_state_qsphere
plot_state_qsphere(sv.data)
mycircuit = QuantumCircuit(1)
mycircuit.x(0)
mycircuit.draw('mpl')
sv = Statevector.from_label('0')
new_sv = sv.evolve(mycircuit)
new_sv
state_fidelity(new_sv, sv)
plot_state_qsphere(new_sv.data)
sv = Statevector.from_label('0')
mycircuit = QuantumCircuit(1)
mycircuit.h(0)
mycircuit.draw('mpl')
new_sv = sv.evolve(mycircuit)
print(new_sv)
plot_state_qsphere(new_sv.data)
sv = Statevector.from_label('1')
mycircuit = QuantumCircuit(1)
mycircuit.h(0)
new_sv = sv.evolve(mycircuit)
print(new_sv)
plot_state_qsphere(new_sv.data)
from resources.qiskit_textbook.widgets import gate_demo
gate_demo(qsphere=True)
sv = Statevector.from_label('00')
plot_state_qsphere(sv.data)
mycircuit = QuantumCircuit(2)
mycircuit.h(0)
mycircuit.cx(0,1)
mycircuit.draw('mpl')
new_sv = sv.evolve(mycircuit)
print(new_sv)
plot_state_qsphere(new_sv.data)
counts = new_sv.sample_counts(shots=1000)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
Tri3=QuantumCircuit(2,2)
Tri3.x(1)
Tri3.h(0)
Tri3.cx(0, 1)
Tri3.draw()
tri3_sv = sv.evolve(Tri3)
print(tri3_sv)
plot_state_qsphere(tri3_sv.data)
counts1 = tri3_sv.sample_counts(shots=1000)
from qiskit.visualization import plot_histogram
plot_histogram(counts1)
#create the above bell state
Sing = QuantumCircuit(2, 2)
#make the gates
Sing.x(1)
Sing.h(0)
Sing.z(0)
Sing.z(1)
Sing.cx(0,1)
Sing.draw()
#print out the statevector
sing_sv = sv.evolve(Sing)
print(sing_sv)
#plot the statevector on qshere
plot_state_qsphere(sing_sv.data)
mycircuit = QuantumCircuit(2, 2)
mycircuit.h(0)
mycircuit.cx(0,1)
mycircuit.measure([0,1], [0,1])
mycircuit.draw('mpl')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
result = execute(mycircuit, simulator, shots=10000).result()
counts = result.get_counts(mycircuit)
plot_histogram(counts)
def initialize_qubit(given_circuit, qubit_index):
import numpy as np
### WRITE YOUR CODE BETWEEN THESE LINES - START
initial_state = [np.sqrt(0.70)+0.j,np.sqrt(0.30)+0.j]
### WRITE YOUR CODE BETWEEN THESE LINES - END
given_circuit.initialize(initial_state, 0)
return given_circuit
def entangle_qubits(given_circuit, qubit_Alice, qubit_Bob):
### WRITE YOUR CODE BETWEEN THESE LINES - START
given_circuit.h(qubit_Alice)
given_circuit.cx(qubit_Alice,qubit_Bob)
### WRITE YOUR CODE BETWEEN THESE LINES - END
return given_circuit
def bell_meas_Alice_qubits(given_circuit, qubit1_Alice, qubit2_Alice, clbit1_Alice, clbit2_Alice):
### WRITE YOUR CODE BETWEEN THESE LINES - START
given_circuit.cx(qubit1_Alice,qubit2_Alice)
given_circuit.h(qubit1_Alice)
given_circuit.measure(qubit1_Alice,clbit1_Alice)
given_circuit.measure(qubit2_Alice,clbit2_Alice)
### WRITE YOUR CODE BETWEEN THESE LINES - END
return given_circuit
def controlled_ops_Bob_qubit(given_circuit, qubit_Bob, clbit1_Alice, clbit2_Alice):
### WRITE YOUR CODE BETWEEN THESE LINES - START
given_circuit.x(qubit_Bob).c_if(clbit2_Alice, 1)
given_circuit.z(qubit_Bob).c_if(clbit1_Alice, 1)
### WRITE YOUR CODE BETWEEN THESE LINES - END
return given_circuit
### imports
from qiskit import QuantumRegister, ClassicalRegister
### set up the qubits and classical bits
all_qubits_Alice = QuantumRegister(2)
all_qubits_Bob = QuantumRegister(1)
creg1_Alice = ClassicalRegister(1)
creg2_Alice = ClassicalRegister(1)
### quantum teleportation circuit here
# Initialize
mycircuit = QuantumCircuit(all_qubits_Alice, all_qubits_Bob, creg1_Alice, creg2_Alice)
initialize_qubit(mycircuit, 0)
mycircuit.barrier()
# Entangle
entangle_qubits(mycircuit, 1, 2)
mycircuit.barrier()
# Do a Bell measurement
bell_meas_Alice_qubits(mycircuit, all_qubits_Alice[0], all_qubits_Alice[1], creg1_Alice, creg2_Alice)
mycircuit.barrier()
# Apply classically controlled quantum gates
controlled_ops_Bob_qubit(mycircuit, all_qubits_Bob[0], creg1_Alice, creg2_Alice)
### Look at the complete circuit
mycircuit.draw()
|
https://github.com/a24l/IBM_Qiskit_QGSS
|
a24l
|
!pip install -U -r resources/requirements.txt
from IPython.display import clear_output
clear_output()
from qiskit.quantum_info import Operator
from qiskit import QuantumCircuit
import numpy as np
def phase_oracle(n, indices_to_mark, name = 'Oracle'):
# create a quantum circuit on n qubits
qc = QuantumCircuit(n, name=name)
### WRITE YOUR CODE BETWEEN THESE LINES - START
# create the identity matrix for n qubits
idenn = np.identity(2**n)
# add the -1 phase to marked elements
for i in indices_to_mark:
idenn[i,i] = -1
### WRITE YOUR CODE BETWEEN THESE LINES - END
# convert your matrix (called oracle_matrix) into an operator, and add it to the quantum circuit
qc.unitary(Operator(idenn), range(n))
return qc
def diffuser(n):
# create a quantum circuit on n qubits
qc = QuantumCircuit(n, name='Diffuser')
### WRITE YOUR CODE BETWEEN THESE LINES - START
# apply hadamard gates to all n qubits
qc.h(range(n))
# take the phase oracle applied to the zero state
qc.append(phase_oracle(n, [0]), range(n))
# apply hadamard gates to all n qubits again
qc.h(range(n))
### WRITE YOUR CODE BETWEEN THESE LINES - END
return qc
def Grover(n, indices_of_marked_elements):
# Create a quantum circuit on n qubits
qc = QuantumCircuit(n, n)
# Determine r
r = int(np.floor(np.pi/4*np.sqrt(2**n/len(indices_of_marked_elements))))
print(f'{n} qubits, basis states {indices_of_marked_elements} marked, {r} rounds')
# step 1: apply Hadamard gates on all qubits
qc.h(range(n))
# step 2: apply r rounds of the phase oracle and the diffuser
for _ in range(r):
qc.append(phase_oracle(n, indices_of_marked_elements), range(n))
qc.append(diffuser(n), range(n))
# step 3: measure all qubits
qc.measure(range(n), range(n))
return qc
mycircuit = Grover(6, [1, 42])
mycircuit.draw()
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
counts = execute(mycircuit, backend=simulator, shots=1000).result().get_counts(mycircuit)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/a24l/IBM_Qiskit_QGSS
|
a24l
|
import numpy as np
from qiskit.opflow import I, X, Y, Z, MatrixEvolution, PauliTrotterEvolution
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit
from qiskit import Aer
from qiskit.compiler import transpile
import qc_grader
# Define which will contain the Paulis
pauli_list = [X,Y,Z,I]
# Define Paulis and add them to the list
###INSERT CODE BELOW THIS LINE
###DO NOT EDIT BELOW THIS LINE
for pauli in pauli_list:
print(pauli, '\n')
from qc_grader.challenges.qgss_2022 import grade_lab2_ex1
grade_lab2_ex1(pauli_list)
# Define list of ladder operators
s_plus, s_minus = (X+(1j*Y))/2, (X-(1j*Y))/2
ladder_operator_list = [s_plus, s_minus]
# Define ladder operators and add the to the list
###INSERT CODE BELOW THIS LINE
###DO NOT EDIT BELOW THIS LINE
for ladder_operator in ladder_operator_list:
print(ladder_operator, '\n')
from qc_grader.challenges.qgss_2022 import grade_lab2_ex2
grade_lab2_ex2(ladder_operator_list)
# Define list which will contain the matrices representing the Pauli operators
matrix_sigma_list = []
# Add matrix representation of Paulis to the list
###INSERT CODE BELOW THIS LINE
for op in pauli_list:
matrix_sigma_list.append(op.to_matrix())
###DO NOT EDIT BELOW THIS LINE
for matrix_sigma in matrix_sigma_list:
print(matrix_sigma, '\n')
from qc_grader.challenges.qgss_2022 import grade_lab2_ex3
grade_lab2_ex3(matrix_sigma_list)
# Define a list which will contain the circuit representation of the Paulis
circuit_sigma_list = []
# Add circuits to list
###INSERT CODE BELOW THIS LINE
for gate in pauli_list:
circuit_sigma_list.append(gate.to_circuit())
###DO NOT EDIT BELOW THIS LINE
for circuit in circuit_sigma_list:
print(circuit, '\n')
from qc_grader.challenges.qgss_2022 import grade_lab2_ex4
grade_lab2_ex4(circuit_sigma_list)
# Define a variable theta to be a parameter with name 'theta'
theta = Parameter('theta')
# Set number of qubits to 1
qubits_count = 1
# Initialize a quantum circuit with one qubit
quantum_circuit = QuantumCircuit(qubits_count)
# Add a parametrized RX rotation on the qubit
###INSERT CODE BELOW THIS LINE
quantum_circuit.rx(theta,0)
###DO NOT EDIT BELOW THIS LINE
print(quantum_circuit)
quantum_circuit.draw()
from qc_grader.challenges.qgss_2022 import grade_lab2_ex5
grade_lab2_ex5(quantum_circuit)
# Set the value of the parameter
theta_value = np.pi
# Bind the value to the parametrized circuit
###INSERT CODE BELOW THIS LINE
quantum_circuit = quantum_circuit.bind_parameters({theta: theta_value})
###DO NOT EDIT BELOW THIS LINE
print(quantum_circuit)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex6
grade_lab2_ex6(quantum_circuit)
print(I.to_matrix())
# Use the formula above to define the Hamiltonian operator
###INSERT CODE BELOW THIS LINE
###DO NOT EDIT BELOW THIS LINE
H = 1/2*((I^I)+(X^X)+(Y^Y)+(Z^Z))
# Get its matrix representation
H_matrix = H.to_matrix()
print(H_matrix)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex7
grade_lab2_ex7(H_matrix)
# Define a parameter t for the time in the time evolution operator
t = Parameter('t')
# Follow the instructions above to define a time-evolution operator
###INSERT CODE BELOW THIS LINE
time_evolution_operator=(H*t).exp_i()
###DO NOT EDIT BELOW THIS LINE
print(time_evolution_operator)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex8
grade_lab2_ex8(time_evolution_operator)
# Set a total time for the time evolution
evolution_time = 0.5
# Instantiate a MatrixEvolution() object to convert the time evolution operator
qc = MatrixEvolution().convert(time_evolution_operator)
# and bind the value for the time parameter
bound_matrix_exponentiation_circuit = qc.bind_parameters({t: evolution_time})
###INSERT CODE BELOW THIS LINE
###DO NOT EDIT BELOW THIS LINE
print(bound_matrix_exponentiation_circuit)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex9
grade_lab2_ex9(bound_matrix_exponentiation_circuit)
# Define a value for the duration of the time-step
time_step_value = 0.1
# Instantiate a PauliTrotterEvolution() object and convert the time-evolution operator
# to then bind the value of the time step
###INSERT CODE BELOW THIS LINE
trotter_circuit=PauliTrotterEvolution().convert(time_evolution_operator)
bound_trotter_exponentiation_circuit = trotter_circuit.bind_parameters({t: time_step_value})
###DO NOT EDIT BELOW THIS LINE
print(bound_trotter_exponentiation_circuit)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex10
grade_lab2_ex10(bound_trotter_exponentiation_circuit)
# Define the number of steps needed to reach the previously set total time-evolution
steps = int(evolution_time/time_step_value)
# Compose the operator for a Trotter step several times to generate the
# operator for the full time-evolution
###INSERT CODE BELOW THIS LINE
trot = bound_trotter_exponentiation_circuit
U = trot
for i in range(steps-1):
trot@=U
total_time_evolution_circuit = trot
###DO NOT EDIT BELOW THIS LINE
print(total_time_evolution_circuit)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex11
grade_lab2_ex11(total_time_evolution_circuit)
# Set number of qubits
num_qubits = 3
# Define time parameter
t = Parameter('t')
# Set total evolution time
evolution_time_t = 2
# Set size of time-step for Trotter evolution
time_step_value_t = 0.1
# Define the number of steps
steps_t = int(evolution_time_t/time_step_value_t)
# Create circuit
tight_binding_circuit = QuantumCircuit(num_qubits)
# Add initial state preparation
tight_binding_circuit.x(0)
# Define the Hamiltonian, the time-evolution operator, the Trotter step and the total evolution
###INSERT CODE BELOW THIS LINE
XXs = (I^X^X) + (X^X^I) #make the sigmax first term
YYs = (I^Y^Y) + (Y^Y^I) #make the sigmay second term
H = (XXs + YYs) # prepare the Hamiltonian
time_evolution_operator = (t * H).exp_i() # make the time evolution
trotter_circuit=PauliTrotterEvolution().convert(time_evolution_operator) #trotterize it.
bound = trotter_circuit.bind_parameters({t: time_step_value_t}) #bind it
#tight_binding_circuit.append(bound,[[0],[1],[2]])
for _ in range(steps_t):
tight_binding_circuit.append(bound, [[0], [1], [2]])
full_time_evolution_circuit=tight_binding_circuit
###DO NOT EDIT BELOW THIS LINE
print(full_time_evolution_circuit)
full_time_evolution_circuit.decompose().decompose().decompose().draw() # create a trotterized decomposition
from qc_grader.challenges.qgss_2022 import grade_lab2_ex12
grade_lab2_ex12(full_time_evolution_circuit)
|
https://github.com/a24l/IBM_Qiskit_QGSS
|
a24l
|
import networkx as nx
import numpy as np
import plotly.graph_objects as go
import matplotlib as mpl
import pandas as pd
from IPython.display import clear_output
from plotly.subplots import make_subplots
from matplotlib import pyplot as plt
from qiskit import Aer
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_city
from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM
from time import time
from copy import copy
from typing import List
from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs
mpl.rcParams['figure.dpi'] = 300
from qiskit.circuit import Parameter, ParameterVector
#Parameters are initialized with a simple string identifier
parameter_0 = Parameter('θ[0]')
parameter_1 = Parameter('θ[1]')
circuit = QuantumCircuit(1)
#We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates
circuit.ry(theta = parameter_0, qubit = 0)
circuit.rx(theta = parameter_1, qubit = 0)
circuit.draw('mpl')
parameter = Parameter('θ')
circuit = QuantumCircuit(1)
circuit.ry(theta = parameter, qubit = 0)
circuit.rx(theta = parameter, qubit = 0)
circuit.draw('mpl')
#Set the number of layers and qubits
n=3
num_layers = 2
#ParameterVectors are initialized with a string identifier and an integer specifying the vector length
parameters = ParameterVector('θ', n*(num_layers+1))
circuit = QuantumCircuit(n, n)
for layer in range(num_layers):
#Appending the parameterized Ry gates using parameters from the vector constructed above
for i in range(n):
circuit.ry(parameters[n*layer+i], i)
circuit.barrier()
#Appending the entangling CNOT gates
for i in range(n):
for j in range(i):
circuit.cx(j,i)
circuit.barrier()
#Appending one additional layer of parameterized Ry gates
for i in range(n):
circuit.ry(parameters[n*num_layers+i], i)
circuit.barrier()
circuit.draw('mpl')
print(circuit.parameters)
#Create parameter dictionary with random values to bind
param_dict = {parameter: np.random.random() for parameter in parameters}
print(param_dict)
#Assign parameters using the assign_parameters method
bound_circuit = circuit.assign_parameters(parameters = param_dict)
bound_circuit.draw('mpl')
new_parameters = ParameterVector('Ψ',9)
new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[k] for k in range(9)])
new_circuit.draw('mpl')
#Run the circuit with assigned parameters on Aer's statevector simulator
simulator = Aer.get_backend('statevector_simulator')
result = simulator.run(bound_circuit).result()
statevector = result.get_statevector(bound_circuit)
plot_state_city(statevector)
#The following line produces an error when run because 'circuit' still contains non-assigned parameters
#result = simulator.run(circuit).result()
for key in graphs.keys():
print(key)
graph = nx.Graph()
#Add nodes and edges
graph.add_nodes_from(np.arange(0,6,1))
edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)]
graph.add_weighted_edges_from(edges)
graphs['custom'] = graph
#Display widget
display_maxcut_widget(graphs['custom'])
def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float:
"""
Computes the maxcut cost function value for a given graph and cut represented by some bitstring
Args:
graph: The graph to compute cut values for
bitstring: A list of integer values '0' or '1' specifying a cut of the graph
Returns:
The value of the cut
"""
#Get the weight matrix of the graph
weight_matrix = nx.adjacency_matrix(graph).toarray()
size = weight_matrix.shape[0]
value = 0.
#INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE
for i in range(size):
for j in range(size):
value+=float(weight_matrix[i][j])*float(bitstring[i])*(1-float(bitstring[j]))
return value
def plot_maxcut_histogram(graph: nx.Graph) -> None:
"""
Plots a bar diagram with the values for all possible cuts of a given graph.
Args:
graph: The graph to compute cut values for
"""
num_vars = graph.number_of_nodes()
#Create list of bitstrings and corresponding cut values
bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)]
values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings]
#Sort both lists by largest cut value
values, bitstrings = zip(*sorted(zip(values, bitstrings)))
#Plot bar diagram
bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value')))
fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600))
fig.show()
plot_maxcut_histogram(graph = graphs['custom'])
from qc_grader import grade_lab2_ex1
bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE
# Note that the grading function is expecting a list of integers '0' and '1'
grade_lab2_ex1(bitstring)
from qiskit_optimization import QuadraticProgram
quadratic_program = QuadraticProgram('sample_problem')
print(quadratic_program.export_as_lp_string())
quadratic_program.binary_var(name = 'x_0')
quadratic_program.integer_var(name = 'x_1')
quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8)
quadratic = [[0,1,2],[3,4,5],[0,1,2]]
linear = [10,20,30]
quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5)
print(quadratic_program.export_as_lp_string())
def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram:
"""Constructs a quadratic program from a given graph for a MaxCut problem instance.
Args:
graph: Underlying graph of the problem.
Returns:
QuadraticProgram
"""
#Get weight matrix of graph
weight_matrix = nx.adjacency_matrix(graph)
shape = weight_matrix.shape
size = shape[0]
#Build qubo matrix Q from weight matrix W
qubo_matrix = np.zeros((size, size))
qubo_vector = np.zeros(size)
for i in range(size):
for j in range(size):
qubo_matrix[i, j] -= weight_matrix[i, j]
for i in range(size):
for j in range(size):
qubo_vector[i] += weight_matrix[i,j]
#INSERT YOUR CODE HERE
quadratic_program=QuadraticProgram('sample_problem')
for i in range(size):
quadratic_program.binary_var(name='x_{}'.format(i))
quadratic_program.maximize(quadratic=qubo_matrix,linear=qubo_vector)
return quadratic_program
quadratic_program = quadratic_program_from_graph(graphs['custom'])
print(quadratic_program.export_as_lp_string())
from qc_grader import grade_lab2_ex2
# Note that the grading function is expecting a quadratic program
grade_lab2_ex2(quadratic_program)
def qaoa_circuit(qubo: QuadraticProgram, p: int = 1):
"""
Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers.
Args:
qubo: The quadratic program instance
p: The number of layers in the QAOA circuit
Returns:
The parameterized QAOA circuit
"""
size = len(qubo.variables)
qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True)
qubo_linearity = qubo.objective.linear.to_array()
#Prepare the quantum and classical registers
qaoa_circuit = QuantumCircuit(size,size)
#Apply the initial layer of Hadamard gates to all qubits
qaoa_circuit.h(range(size))
#Create the parameters to be used in the circuit
gammas = ParameterVector('gamma', p)
betas = ParameterVector('beta', p)
#Outer loop to create each layer
for i in range(p):
#Apply R_Z rotational gates from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
qmsc = 0.0
for k in range(size):
qmsc+=qubo_matrix[j,k]
qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qmsc),j)
#Apply R_ZZ rotational gates for entangled qubit rotations from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
for k in range(size):
if j!=k:
qaoa_circuit.rzz(gammas[i] * qubo_matrix[j,k] * 0.5, j, k)
# Apply single qubit X - rotations with angle 2beta_i to all qubits
#INSERT YOUR CODE HERE
for j in range(size):
qaoa_circuit.rx(2*betas[i],j)
return qaoa_circuit
quadratic_program = quadratic_program_from_graph(graphs['custom'])
custom_circuit = qaoa_circuit(qubo = quadratic_program)
test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters))
from qc_grader import grade_lab2_ex3
# Note that the grading function is expecting a quantum circuit
grade_lab2_ex3(test)
from qiskit.algorithms import QAOA
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = Aer.get_backend('statevector_simulator')
qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1])
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
quadratic_program = quadratic_program_from_graph(graphs['custom'])
result = eigen_optimizer.solve(quadratic_program)
print(result)
def plot_samples(samples):
"""
Plots a bar diagram for the samples of a quantum algorithm
Args:
samples
"""
#Sort samples by probability
samples = sorted(samples, key = lambda x: x.probability)
#Get list of probabilities, function values and bitstrings
probabilities = [sample.probability for sample in samples]
values = [sample.fval for sample in samples]
bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples]
#Plot bar diagram
sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value')))
fig = go.Figure(
data=sample_plot,
layout = dict(
xaxis=dict(
type = 'category'
)
)
)
fig.show()
plot_samples(result.samples)
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name])
trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]}
offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum()
def callback(eval_count, params, mean, std_dev):
trajectory['beta_0'].append(params[1])
trajectory['gamma_0'].append(params[0])
trajectory['energy'].append(-mean + offset)
optimizers = {
'cobyla': COBYLA(),
'slsqp': SLSQP(),
'adam': ADAM()
}
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
result = eigen_optimizer.solve(quadratic_program)
fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples)
fig.show()
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graphs[graph_name])
#Create callback to record total number of evaluations
max_evals = 0
def callback(eval_count, params, mean, std_dev):
global max_evals
max_evals = eval_count
#Create empty lists to track values
energies = []
runtimes = []
num_evals=[]
#Run QAOA for different values of p
for p in range(1,10):
print(f'Evaluating for p = {p}...')
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
start = time()
result = eigen_optimizer.solve(quadratic_program)
runtimes.append(time()-start)
num_evals.append(max_evals)
#Calculate energy of final state from samples
avg_value = 0.
for sample in result.samples:
avg_value += sample.probability*sample.fval
energies.append(avg_value)
#Create and display plots
energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma'))
runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma'))
num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma'))
fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations'])
fig.update_layout(width=1800,height=600, showlegend=False)
fig.add_trace(energy_plot, row=1, col=1)
fig.add_trace(runtime_plot, row=1, col=2)
fig.add_trace(num_evals_plot, row=1, col=3)
clear_output()
fig.show()
def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None):
num_shots = 1000
seed = 42
simulator = Aer.get_backend('qasm_simulator')
simulator.set_options(seed_simulator = 42)
#Generate circuit
circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1)
circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes()))
#Create dictionary with precomputed cut values for all bitstrings
cut_values = {}
size = graph.number_of_nodes()
for i in range(2**size):
bitstr = '{:b}'.format(i).rjust(size, '0')[::-1]
x = [int(bit) for bit in bitstr]
cut_values[bitstr] = maxcut_cost_fn(graph, x)
#Perform grid search over all parameters
data_points = []
max_energy = None
for beta in np.linspace(0,np.pi, 50):
for gamma in np.linspace(0, 4*np.pi, 50):
bound_circuit = circuit.assign_parameters([beta, gamma])
result = simulator.run(bound_circuit, shots = num_shots).result()
statevector = result.get_counts(bound_circuit)
energy = 0
measured_cuts = []
for bitstring, count in statevector.items():
measured_cuts = measured_cuts + [cut_values[bitstring]]*count
if cvar is None:
#Calculate the mean of all cut values
energy = sum(measured_cuts)/num_shots
else:
#raise NotImplementedError()
measured_cuts = sorted(measured_cuts, reverse = True)
new_size = np.ceil(num_shots*cvar)
for i in range(int(new_size)):
energy += measured_cuts[i]
energy /= new_size
#Update optimal parameters
if max_energy is None or energy > max_energy:
max_energy = energy
optimum = {'beta': beta, 'gamma': gamma, 'energy': energy}
#Update data
data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy})
#Create and display surface plot from data_points
df = pd.DataFrame(data_points)
df = df.pivot(index='beta', columns='gamma', values='energy')
matrix = df.to_numpy()
beta_values = df.index.tolist()
gamma_values = df.columns.tolist()
surface_plot = go.Surface(
x=gamma_values,
y=beta_values,
z=matrix,
coloraxis = 'coloraxis'
)
fig = go.Figure(data = surface_plot)
fig.show()
#Return optimum
return optimum
graph = graphs['custom']
optimal_parameters = plot_qaoa_energy_landscape(graph = graph)
print('Optimal parameters:')
print(optimal_parameters)
optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2)
print(optimal_parameters)
from qc_grader import grade_lab2_ex4
# Note that the grading function is expecting a python dictionary
# with the entries 'beta', 'gamma' and 'energy'
grade_lab2_ex4(optimal_parameters)
|
https://github.com/a24l/IBM_Qiskit_QGSS
|
a24l
|
# General Imports
import numpy as np
# Visualisation Imports
import matplotlib.pyplot as plt
# Scikit Imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Qiskit Imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Load digits dataset
digits = datasets.load_digits(n_class=2)
# Plot example '0' and '1'
fig, axs = plt.subplots(1, 2, figsize=(6,3))
axs[0].set_axis_off()
axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest')
axs[1].set_axis_off()
axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
# Split dataset
sample_train, sample_test, label_train, label_test = train_test_split(
digits.data, digits.target, test_size=0.2, random_state=22)
# Reduce dimensions
n_dim = 4
pca = PCA(n_components=n_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Normalise
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Scale
samples = np.append(sample_train, sample_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
sample_train = minmax_scale.transform(sample_train)
sample_test = minmax_scale.transform(sample_test)
# Select
train_size = 100
sample_train = sample_train[:train_size]
label_train = label_train[:train_size]
test_size = 20
sample_test = sample_test[:test_size]
label_test = label_test[:test_size]
print(sample_train[0], label_train[0])
print(sample_test[0], label_test[0])
# 3 features, depth 2
map_z = ZFeatureMap(feature_dimension=3, reps=2)
map_z.draw('mpl')
# 3 features, depth 1
map_zz = ZZFeatureMap(feature_dimension=3, reps=1)
map_zz.draw('mpl')
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear')
map_zz.draw('mpl')
# 3 features, depth 1, circular entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular')
map_zz.draw('mpl')
# 3 features, depth 1
map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ'])
map_pauli.draw('mpl')
def custom_data_map_func(x):
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x))
return coeff
map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'],
data_map_func=custom_data_map_func)
#map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map
twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='circular', insert_barriers=True)
twolocal.draw('mpl')
twolocaln = NLocal(num_qubits=3, reps=2,
rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))],
entanglement_blocks=CXGate(),
entanglement='circular', insert_barriers=True)
twolocaln.draw('mpl')
# rotation block:
rot = QuantumCircuit(2)
params = ParameterVector('r', 2)
rot.ry(params[0], 0)
rot.rz(params[1], 1)
# entanglement block:
ent = QuantumCircuit(4)
params = ParameterVector('e', 3)
ent.crx(params[0], 0, 1)
ent.crx(params[1], 1, 2)
ent.crx(params[2], 2, 3)
nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent,
entanglement='linear', insert_barriers=True)
nlocal.draw('mpl')
qubits = 3
repeats = 2
x = ParameterVector('x', length=qubits)
var_custom = QuantumCircuit(qubits)
for _ in range(repeats):
for i in range(qubits):
var_custom.rx(x[i], i)
for i in range(qubits):
for j in range(i + 1, qubits):
var_custom.cx(i, j)
var_custom.p(x[i] * x[j], j)
var_custom.cx(i, j)
var_custom.barrier()
var_custom.draw('mpl')
print(sample_train[0])
encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
encode_circuit = encode_map.bind_parameters(sample_train[0])
encode_circuit.draw(output='mpl')
x = [-0.1,0.2]
encode_map = ZZFeatureMap(feature_dimension=2, reps=4, entanglement='linear', insert_barriers=True, data_map_func = None )
encode_circuit = encode_map.bind_parameters(x)
encode_circuit.draw(output='mpl')
# YOUR CODE HERE
from qc_grader import grade_lab3_ex1
# Note that the grading function is expecting a quantum circuit
grade_lab3_ex1(encode_circuit)
zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator'))
print(sample_train[0])
print(sample_train[1])
zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1])
zz_circuit.decompose().decompose().draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(zz_circuit, backend, shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts = job.result().get_counts(zz_circuit)
counts['0000']/sum(counts.values())
matrix_train = zz_kernel.evaluate(x_vec=sample_train)
matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_test),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("testing kernel matrix")
plt.show()
x = [-0.1,0.2]
y = [0.4,-0.6]
# YOUR CODE HERE
fmap = ZZFeatureMap(feature_dimension = 2, reps = 4, insert_barriers = True)
zz_kernel = QuantumKernel(feature_map = fmap, quantum_instance = Aer.get_backend('statevector_simulator'))
zz_circuit = zz_kernel.construct_circuit(x,y)
backend = Aer.get_backend("qasm_simulator")
job = execute(zz_circuit,backend,seed_simulator=1024, seed_transpiler = 1024, shots = 8192)
result = job.result().get_counts(zz_circuit)
amplitude = result['00']/sum(result.values())
print(result,"amplitude:",amplitude)
zz_circuit.decompose().decompose().draw('mpl')
from qc_grader import grade_lab3_ex2
# Note that the grading function is expecting a floating point number
grade_lab3_ex2(amplitude)
zzpc_svc = SVC(kernel='precomputed')
zzpc_svc.fit(matrix_train, label_train)
zzpc_score = zzpc_svc.score(matrix_test, label_test)
print(f'Precomputed kernel classification test score: {zzpc_score}')
zzcb_svc = SVC(kernel=zz_kernel.evaluate)
zzcb_svc.fit(sample_train, label_train)
zzcb_score = zzcb_svc.score(sample_test, label_test)
print(f'Callable kernel classification test score: {zzcb_score}')
classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid']
for kernel in classical_kernels:
classical_svc = SVC(kernel=kernel)
classical_svc.fit(sample_train, label_train)
classical_score = classical_svc.score(sample_test, label_test)
print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
|
https://github.com/a24l/IBM_Qiskit_QGSS
|
a24l
|
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), Pauli operators (X, Y, Z), and the identity operator (I)
from qiskit.opflow import Zero, One, X, Y, Z, I
# Returns the XXX Heisenberg model for 3 spin-1/2 particles in a line
def ex1_compute_H_heis3():
# FILL YOUR CODE IN HERE
xspin = (I^X^X)+(X^X^I)
yspin = (I^Y^Y)+(Y^Y^I)
zspin = (I^Z^Z)+(Z^Z^I)
H = xspin + yspin + zspin
# Return Hamiltonian
return H
from qc_grader.challenges.qgss_2022 import grade_lab4_ex1
# The grading function is expecting a PauliSumOp operator
grade_lab4_ex1(ex1_compute_H_heis3())
# Returns the time evolution operator U_heis3(t) for a given time t assuming an XXX Heisenberg Hamiltonian for 3 spins-1/2 particles in a line
def ex2_compute_U_heis3(t):
# FILL YOUR CODE IN HERE
U=(ex1_compute_H_heis3()*t).exp_i()
return U
from qc_grader.challenges.qgss_2022 import grade_lab4_ex2
# The grading function is expecting a funtion that returns PauliSumOp operator
grade_lab4_ex2(ex2_compute_U_heis3)
# Define array of time points
ts = np.linspace(0, np.pi, 100)
# Define initial state |110>
initial_state = One^One^Zero
# Compute probability of remaining in |110> state over the array of time points
# ~initial_state gives the bra of the initial state (<110|)
# @ is short hand for matrix multiplication
# ex2_compute_U_heis3(t) is the unitary time evolution at time t
# t needs to be wrapped with float(t) to avoid a bug
# (...).eval() returns the inner product <110|ex2_compute_U_heis3(t)|110>
# np.abs(...)**2 is the modulus squared of the innner product which is the expectation value, or probability, of remaining in |110>
probs_110 = [np.abs((~initial_state @ ex2_compute_U_heis3(float(t)) @ initial_state).eval())**2 for t in ts]
# Plot evolution of |110>
plt.figure(facecolor='white')
plt.plot(ts, probs_110, linewidth=2)
plt.xlabel('time')
plt.ylabel(r'probability of state $|110\rangle$')
plt.title(r'Evolution of state $|110\rangle$ under $H_{Heis3}$')
plt.ylim([-0.05,1.05])
plt.grid()
plt.show()
import qiskit
qiskit.__version__
pip install qiskit-ignis
# Importing standard Qiskit modules
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# load IBMQ Account data
# IBMQ.save_account(TOKEN) # replace TOKEN with your API token string (https://quantum-computing.ibm.com/lab/docs/iql/manage/account/ibmq)
provider = IBMQ.load_account()
# Get backend for experiment
provider = IBMQ.get_provider(hub='ibm-q')
manila = provider.get_backend('ibmq_manila')
# properties = manila.properties()
# Simulated backend based on ibmq_manila's device noise profile
sim_noisy_manila = QasmSimulator.from_backend(provider.get_backend('ibmq_manila'))
# Noiseless simulated backend
sim = QasmSimulator()
# Parameterize variable t to be evaluated at t=pi later
t = Parameter('t')
# Build a subcircuit for XX(t) two-qubit gate
def compute_XX_gate(t):
XX_qr = QuantumRegister(2)
XX_qc = QuantumCircuit(XX_qr, name='XX')
XX_qc.ry(np.pi/2,[0,1])
XX_qc.cnot(0,1)
XX_qc.rz(2 * t, 1)
XX_qc.cnot(0,1)
XX_qc.ry(-np.pi/2,[0,1])
# Convert custom quantum circuit into a gate
XX = XX_qc.to_instruction()
return XX
# Build a subcircuit for YY(t) two-qubit gate
def ex3_compute_YY_gate(t):
# FILL YOUR CODE IN HERE
YY_qr = QuantumRegister(2)
YY_qc = QuantumCircuit(YY_qr, name='YY')
YY_qc.rx(np.pi/2,[0,1])
YY_qc.cnot(0,1)
YY_qc.rz(2 * t, 1)
YY_qc.cnot(0,1)
YY_qc.rx(-np.pi/2,[0,1])
# Convert custom quantum circuit into a gate
YY = YY_qc.to_instruction()
return YY
from qc_grader.challenges.qgss_2022 import grade_lab4_ex3
# The grading function is expecting an Instruction
grade_lab4_ex3(ex3_compute_YY_gate(t))
# Build a subcircuit for ZZ(t) two-qubit gate
def ex4_compute_ZZ_gate(t):
# FILL YOUR CODE IN HERE
ZZ_qr = QuantumRegister(2)
ZZ_qc = QuantumCircuit(ZZ_qr, name='ZZ')
ZZ_qc.cnot(0,1)
ZZ_qc.rz(2 * t, 1)
ZZ_qc.cnot(0,1)
# Convert custom quantum circuit into a gate
ZZ = ZZ_qc.to_instruction()
return ZZ
from qc_grader.challenges.qgss_2022 import grade_lab4_ex4
# The grading function is expecting an Instruction
grade_lab4_ex4(ex4_compute_ZZ_gate(t))
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# Define two-qubit interactions Parameterized by t
XX = compute_XX_gate(t)
YY = ex3_compute_YY_gate(t)
ZZ = ex4_compute_ZZ_gate(t)
Trot_qr = QuantumRegister(num_qubits)
Trot_qc = QuantumCircuit(Trot_qr, name='Trot')
for i in range(0, num_qubits - 1):
Trot_qc.append(ZZ, [Trot_qr[i], Trot_qr[i+1]])
Trot_qc.append(YY, [Trot_qr[i], Trot_qr[i+1]])
Trot_qc.append(XX, [Trot_qr[i], Trot_qr[i+1]])
# Convert custom quantum circuit into a gate
Trot_gate = Trot_qc.to_instruction()
# Setup experiment parameters
# The final time of the state evolution
target_time = np.pi # DO NOT MODIFY
# Number of trotter steps
trotter_steps = 4 ### CAN BE >= 4
# Select which qubits to use for the simulation
q_regs = [0,1,2]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(5)
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on manila qubits (q_5, q_3, q_1) corresponding to the state |110>)
qc.x([q_regs[2], q_regs[1]]) # For example this could be (q_regs=[2, 1, 0] which corresponds to => |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, q_regs)
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({t: target_time/trotter_steps})
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, q_regs)
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw() # only view trotter gates
shots = 8192
reps = 4
# Pick the simulated or real backend for manila
backend = sim # Noiseless simulator
# backend = sim_noisy_manila # Simulator that mimics ibmq_manila
# backend = manila # The real manila backend
jobs = []
for _ in range(reps):
# Execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
for job in jobs:
job_monitor(job)
try:
if job.error_message() is not None:
print(job.error_message())
except:
pass
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
fids = []
for job in jobs:
fid = state_tomo(job.result(), st_qcs)
fids.append(fid)
# Share tomography fidelity of discord to compete and collaborate with other students
print('state tomography fidelity on ' + str(backend) + ' = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
# Share what lectures and techniques were useful in optimizing your results
print('Inspiration: Measurement error mitigation, Olivia Lanes\'s 2nd lecture')
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/barankiewicz/Deutsch-Jozsa
|
barankiewicz
|
# zaimportuj Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, assemble, transpile
# zaimportuj narzędzie Qiskit do wizualizacji
from qiskit.visualization import plot_histogram
# initialization
import numpy as np
qn = 4 #Liczba kubitów
balanced_function = True #Wybór funkcji stałej lub zbalansowanej
def generate_oracle(balanced, n):
oracle_qc = QuantumCircuit(n+1)
if balanced == True:
# Wygeneruj losowy ciąg bitów, żeby określić, na których kubitach użyć bramki X
if n <= 10:
pot = n
else:
pot = 16
b = np.random.randint(1,2**pot)
b_str = format(b, '0'+str(n)+'b')
#Iteracja przez ciąg bitów; jeżeli znak to 0 - nie rób nic, jeżeli 1 - użyj bramki X
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
#Zbalansowanie wyroczni poprzez zastosowanie bramek CNOT
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Powtórzenie bramek X
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
if balanced == False:
#Najpierw losowy generujemy 0 lub 1, następnie tworzymy wyrocznię, która zwraca jedynie wygenerowaną liczbę
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Wyrocznia Uf" # To show when we display the circuit
return oracle_gate
def deutsch_jozsa(oracle):
# W wyroczni jest jeden kubit więcej, niż znaków wejściowych funkcji f
n = oracle.num_qubits - 1;
#Utworzenie obwodu kwantowego
final_circuit = QuantumCircuit(n+1, n)
# Krok 1:
final_circuit.x(n)
final_circuit.h(n)
for qubit in range(n):
final_circuit.h(qubit)
# Krok 2:
final_circuit.append(oracle, range(n+1))
# Krok 3:
for qubit in range(n):
final_circuit.h(qubit)
# Krok 4:
for i in range(n):
final_circuit.measure(i, i)
return final_circuit
oracle_gate = generate_oracle(balanced_function, qn)
circuit = deutsch_jozsa(oracle_gate)
circuit.draw()
aer_sim = Aer.get_backend('aer_simulator')
transpiled_circuit = transpile(circuit, aer_sim)
qobj = assemble(transpiled_circuit)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
#IBMQ.save_account('')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (qn+1) and
not x.configuration().simulator and x.status().operational==True))
print("Najmniej zajęty procesor: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_circuit = transpile(circuit, backend, optimization_level=3)
job = backend.run(transpiled_circuit)
job_monitor(job, interval=2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/declanmillar/qiskit-simulation
|
declanmillar
|
# General imports
import numpy as np
# SciPy minimizer routine
from scipy.optimize import minimize
# Plotting functions
import matplotlib.pyplot as plt
# Pre-defined ansatz circuit and operator class for Hamiltonian
from qiskit import QuantumCircuit
from qiskit.circuit.library import EfficientSU2
from qiskit.quantum_info import SparsePauliOp
# Qiskit Primitive imports
from qiskit.primitives import BaseEstimatorV2, BackendEstimatorV2 as Estimator
from qiskit.providers.fake_provider import GenericBackendV2
hamiltonian = SparsePauliOp.from_list(
[("YZ", 0.3980), ("ZI", -0.3980), ("ZZ", -0.0113), ("XX", 0.1810)]
)
ansatz = EfficientSU2(hamiltonian.num_qubits)
ansatz.decompose().draw("mpl", style="iqp")
num_params = ansatz.num_parameters
num_params
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
backend = GenericBackendV2(hamiltonian.num_qubits)
target = backend.target
pm = generate_preset_pass_manager(target=target, optimization_level=3)
ansatz_isa = pm.run(ansatz)
ansatz_isa.draw(output="mpl", idle_wires=False, style="iqp")
hamiltonian_isa = hamiltonian.apply_layout(layout=ansatz_isa.layout)
def cost_func(
params: np.ndarray,
ansatz: QuantumCircuit,
hamiltonian: SparsePauliOp,
estimator: BaseEstimatorV2,
history: dict,
) -> float:
"""Return estimate of energy from estimator
Parameters:
params: Array of ansatz parameters.
ansatz: Parameterized ansatz circuit.
hamiltonian: Operator representation of Hamiltonian.
estimator: Estimator primitive instance.
history: Dictionary for storing intermediate results.
Returns:
Energy estimate.
"""
pub = (ansatz, [hamiltonian], [params])
result = estimator.run(pubs=[pub]).result()
energy = result[0].data.evs[0]
history["iters"] += 1
history["prev_vector"] = params
history["cost_history"].append(energy)
print(f"Iters. done: {history['iters']} [Current cost: {energy}]")
return energy
history = {
"prev_vector": None,
"iters": 0,
"cost_history": [],
}
x0 = 2 * np.pi * np.random.random(num_params)
x0
estimator = Estimator(backend=backend)
estimator.options.default_shots = 10000
res = minimize(
cost_func,
x0,
args=(ansatz_isa, hamiltonian_isa, estimator, history),
method="cobyla",
)
res
all(history["prev_vector"] == res.x)
history["iters"] == res.nfev
fig, ax = plt.subplots()
ax.plot(range(history["iters"]), history["cost_history"])
ax.set_xlabel("Iterations")
ax.set_ylabel("Cost")
plt.draw()
import qiskit
qiskit.version.get_version_info()
import qiskit_aer
qiskit_aer.version.get_version_info()
|
https://github.com/declanmillar/qiskit-simulation
|
declanmillar
|
# General imports
import numpy as np
# SciPy minimizer routine
from scipy.optimize import minimize
# rustworkx graph library
import rustworkx as rx
from rustworkx.visualization import mpl_draw
# Pre-defined ansatz circuit, operator class and visualization tools
from qiskit import QuantumCircuit
from qiskit.circuit.library import QAOAAnsatz
from qiskit.quantum_info import SparsePauliOp
from qiskit.visualization import plot_distribution
# Qiskit Primitive imports
from qiskit.primitives import BaseEstimatorV2, BackendEstimatorV2 as Estimator
from qiskit.primitives import BackendSamplerV2 as Sampler
from qiskit.providers.fake_provider import GenericBackendV2
num_nodes = 5
# The edge syntax is (start, end, weight)
edges = [(0, 1, 1), (0, 2, 1), (0, 3, 1), (0, 4, 1)]
G = rx.PyGraph()
G.add_nodes_from(range(num_nodes))
G.add_edges_from(edges)
mpl_draw(
G, pos=rx.bipartite_layout(G, {0}), with_labels=True, node_color="#EE5396", font_color="#F4F4F4"
)
# Problem to Hamiltonian operator
hamiltonian = SparsePauliOp.from_list([("IIIZZ", 1), ("IIZIZ", 1), ("IZIIZ", 1), ("ZIIIZ", 1)])
# QAOA ansatz circuit
ansatz = QAOAAnsatz(hamiltonian, reps=2)
ansatz.decompose(reps=3).draw(output="mpl", style="iqp")
ansatz.decompose().draw(output="mpl", style="iqp")
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
backend = GenericBackendV2(hamiltonian.num_qubits)
target = backend.target
pm = generate_preset_pass_manager(target=target, optimization_level=3)
ansatz_isa = pm.run(ansatz)
ansatz_isa.draw(output="mpl", idle_wires=False, style="iqp")
hamiltonian_isa = hamiltonian.apply_layout(ansatz_isa.layout)
hamiltonian_isa
def cost_func(
params: np.ndarray,
ansatz: QuantumCircuit,
hamiltonian: SparsePauliOp,
estimator: BaseEstimatorV2,
) -> float:
"""Return estimate of energy from estimator
Parameters:
params: Array of ansatz parameters.
ansatz: Parameterized ansatz circuit.
hamiltonian: Operator representation of Hamiltonian.
estimator: Estimator primitive instance.
Returns:
Energy estimate
"""
pub = (ansatz, [hamiltonian], [params])
result = estimator.run(pubs=[pub]).result()
cost = result[0].data.evs[0]
return cost
# Configure estimator
estimator = Estimator(backend=backend)
estimator.options.default_shots = 10_000
# Configure sampler
sampler = Sampler(backend=backend)
sampler.options.default_shots = 10_000
x0 = 2 * np.pi * np.random.rand(ansatz_isa.num_parameters)
res = minimize(cost_func, x0, args=(ansatz_isa, hamiltonian_isa, estimator), method="COBYLA")
res
# Assign solution parameters to ansatz
qc = ansatz.assign_parameters(res.x)
# Add measurements to our circuit
qc.measure_all()
qc_isa = pm.run(qc)
qc_isa.draw(output="mpl", idle_wires=False, style="iqp")
result = sampler.run([qc_isa]).result()
samp_dist = result[0].data.meas.get_counts()
plot_distribution(samp_dist, figsize=(15, 5))
# Reverse 11110 to convert quantum result to classical solution
solution = [0, 1, 1, 1, 1]
mpl_draw(
G,
pos=rx.bipartite_layout(G, {0}),
with_labels=True,
node_color=["#EE5396" if kk else "#0F62FE" for kk in solution],
font_color="#F4F4F4",
)
import qiskit
qiskit.version.get_version_info()
import qiskit_aer
qiskit_aer.version.get_version_info()
|
https://github.com/Herbrant/shor-algorithm-qiskit
|
Herbrant
|
"""The following is python code utilizing the qiskit library that can be run on extant quantum
hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding,
for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find
r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1,
results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>).
To find the factor, use the equivalence a^r mod 15. From this:
(a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r
values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15
Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients,
gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15,
so the result of running shors algorithm to find the prime factors of an integer using quantum
hardware are demonstrated. Note, this is not the same as the technical implementation of shor's
algorithm described in this section for breaking the discrete log hardness assumption,
though the proof of concept remains."""
# Import libraries
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from numpy import pi
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
# Initialize qubit registers
qreg_q = QuantumRegister(5, 'q')
creg_c = ClassicalRegister(5, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.reset(qreg_q[0])
circuit.reset(qreg_q[1])
circuit.reset(qreg_q[2])
circuit.reset(qreg_q[3])
circuit.reset(qreg_q[4])
# Apply Hadamard transformations to qubit registers
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
# Apply first QFT, modular exponentiation, and another QFT
circuit.h(qreg_q[1])
circuit.cx(qreg_q[2], qreg_q[3])
circuit.crx(pi/2, qreg_q[0], qreg_q[1])
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4])
circuit.h(qreg_q[0])
circuit.rx(pi/2, qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
# Measure the qubit registers 0-2
circuit.measure(qreg_q[2], creg_c[2])
circuit.measure(qreg_q[1], creg_c[1])
circuit.measure(qreg_q[0], creg_c[0])
# Get least busy quantum hardware backend to run on
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
# Run the circuit on available quantum hardware and plot histogram
from qiskit.tools.monitor import job_monitor
job = execute(circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(circuit)
plot_histogram(answer)
#largest amplitude results correspond with r values used to find the prime factor of N.
|
https://github.com/OldGinko/Qiskit-CKS-Algorithm
|
OldGinko
|
"""
THIS VERSION DOES NOT NEED TO TURN U INTO A MATRIX TO EXPONENT IT,
WE USE THE QISKIT LANGUAGE FOR IT. WE ALSO USE QISKIT TO CREATE cU
AUTOMATICALLY INSTEWAD BY HAND AS IT IS BADLY IN IPE_BOX
This is the same IPE as in "IPE with HamiltonSiumlation" instead of applying
U 2^k times we apply U^(2k) once the k-th itartation step.
@author: ugsga
What to fix: Use GPE instead of IPE to reduce number of gates and
increase Nr of qubits
"""
from qiskit import *
import numpy as np
from qiskit.visualization import plot_histogram
import qiskit.tools.jupyter
import matplotlib.pyplot as plt
from qiskit.aqua.algorithms import IQPE
from scipy.linalg import expm, sinm, cosm #for the bridge Hamiltonian simulation
from qiskit.extensions import *
from qiskit.quantum_info.operators import Operator
# A = np.array([[1/2+0.j,-1/3],[-1/3,1/2]])
# A =A/np.linalg.norm(A) #Norm the matrix as stated in Problem 1 CKS
def IPE_box(A,m,hist=False, draw=False):
"""
Iterative Phase Estiamtion for 2x2 Hermitian Matrix
Input:
A: hermitian matrix
m: m- bit desired resbpresentation of output
hist: return histogram, default == False
draw: return circuit plot, defualt == False
Output:
Tuple:
(EW, IPE.png, hist.png)
"""
U_list_temp = [0]*m
U_list = []
# control = np.array([[1.+0.j,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]])
x = np.arange(0,m,1) #save output of classical register here
U = qiskit.extensions.HamiltonianGate(A, -1,"Hsim") #generate unitary in H-Gate class
#-1 to get same as expm(A*1j)
for k in range(0,m):
U_list_temp[k]=U.power(2**k)
# control[2:,2:] = U_list_temp[k]
# U_list.append(control.copy())
eigenvec = np.linalg.eig(A)
dim_b = int(np.log2(len(eigenvec[1][1])))
sim = Aer.get_backend('qasm_simulator')
q = QuantumRegister(1) #build q-register
b = QuantumRegister(dim_b) #register for |b>
c = ClassicalRegister(m) #build classical-register
circuit = QuantumCircuit(q,b,c) #build curicuit from register "q"
initial_state = eigenvec[1][1] # Define initial_state, last index is cahngeable to 1/0
# print(initial_state)
circuit.initialize(initial_state, b)
cU = [0]*m
for i in range(0,m):
cU[i] = U_list_temp[i].control() #generate controlled operator U
for i in range(1,m+1):
repetitions = 2**(m-i)
circuit.h([0])
circuit.append(cU[m-i],list(range(0,dim_b+1))) #apply cU
if i == 1:
pass
else:
circuit.rz(-2*np.pi*x[i-2]/2**(m-i-1),q[0])
circuit.h(0)
circuit.measure(q[0],c[i-1])
job = execute(circuit, sim, shots=1, memory=True)
x[m-i] = int(job.result().get_memory()[0][m-i])
circuit.reset(q[0])
if draw == True:
circuit.draw(filename="IPE.png", output="mpl")
else:
pass
n=m
count0 = execute(circuit, sim,shots=4096).result().get_counts()
key_new = [str(int(key,2)/2**n) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
if hist == True:
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, ax=ax[1])
fig.savefig("hist.png")
plt.tight_layout()
plt.close()
else:
pass
#get maximum of plot
maxim = count0.most_frequent() #Return the most frequent count
maxim_dec = int(maxim,2)/2**n # Convert a binary string to a decimal int.
EW = np.exp(maxim_dec*2*np.pi*1j) #get eigenvalues in mixed for(re and im are mixed)
EW1 = EW.real
EW2 = EW.imag
print("EW1=",EW1, "EW2=",EW2)
return [EW,"IPE.png","hist.png"]
# B = np.array([[1+0.j,2,3,4],[2,1,2,3],[3,2,4,1],[4,3,1,2]])
# B = B/np.linalg.norm(B)
# print(IPE_box(B,6,draw=True,hist=True))
# print(np.matmul(B,B.transpose()))
# print("EW by numpy:",np.linalg.eig(B)[0])
|
https://github.com/OldGinko/Qiskit-CKS-Algorithm
|
OldGinko
|
"""
Implementing the inversion of A with Hamiltonmian SImulation
(Fourier approach in CKS paper, see red box1 Page 5)
"""
from qiskit import *
import numpy as np
from qiskit.visualization import plot_histogram
import qiskit.tools.jupyter
import matplotlib.pyplot as plt
from qiskit.aqua.algorithms import IQPE
from scipy.linalg import expm, sinm, cosm #for the bridge Hamiltonian simulation
from qiskit.extensions import *
from qiskit.quantum_info.operators import Operator
A = np.array([[1/2+0.j,-1/3],[-1/3,1/2]])
# A =A/np.linalg.norm(A)
A_inv = qiskit.extensions.HamiltonianGate(A, 1)
A_inv1 = A_inv.to_matrix()
numpInv=np.linalg.inv(A)
print(np.dot(A,A_inv1))
|
https://github.com/shaurya010/Shor-s-Algorithm-
|
shaurya010
|
from qiskit import IBMQ
from qiskit.utils import QuantumInstance
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API KEY HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator') # Specifies the quantum device
print('\n Shors Algorithm')
print('--------------------')
print('\nExecuting...\n')
factors = Shor(QuantumInstance(backend, shots=100, skip_qobj_validation=False))
result_dict = factors.factor(N=21, a=2) # Where N is the integer to be factored
result = result_dict.factors
print(result)
print('\nPress any key to close')
input()
|
https://github.com/mattalcasabas/quantum-shors-algorithm
|
mattalcasabas
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit import QuantumCircuit, Aer, execute
from math import gcd
import pandas as pd
from qiskit.visualization import plot_histogram
|
https://github.com/mattalcasabas/quantum-shors-algorithm
|
mattalcasabas
|
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
from qiskit_ibm_runtime import QiskitRuntimeService
import numpy as np
# Define a function for creating a controlled unitary operator for a^power mod 15
def c_amod15(a, power):
# Create a quantum circuit with 4 qubits
U = QuantumCircuit(4)
# Apply the controlled swaps and X gates based on the specified power
for iteration in range(power):
# Apply swaps to create the effect of the controlled modular multiplication
U.swap(2, 3)
U.swap(1, 2)
U.swap(0, 1)
# Apply X gate to all qubits
for q in range(4):
U.x(q)
# Convert the circuit to a gate
U = U.to_gate()
# Set the gate name to indicate the operation being performed
U.name = "%i^%i mod 15" % (a, power)
# Create the controlled version of the gate
c_U = U.control()
# Return the controlled gate
return c_U
qubit_count = 8 # number of qubits we'll be using to count
a = 7 # this is our guess
# Define a function for creating the inverse Quantum Fourier Transform (QFT)
def qft_dagger(n):
# Create a quantum circuit with n qubits
qc = QuantumCircuit(n)
# Apply swaps to reverse the order of qubits
for qubit in range(n // 2):
qc.swap(qubit, n - qubit - 1)
# Apply controlled phase shifts and Hadamard gates
for j in range(n):
# Iterate over qubits m less than j
for m in range(j):
# Apply a controlled-phase gate with a decreasing angle
qc.cp(-np.pi / float(2**(j - m)), m, j)
# Apply Hadamard gate to the j-th qubit
qc.h(j)
# Set the name of the circuit to indicate that it is the inverse QFT
qc.name = "QFT dagger"
# Return the quantum circuit
return qc
# Create a quantum circuit with qubit_count + 4 qubits, and qubit_count classical bits
qc = QuantumCircuit(qubit_count + 4, qubit_count)
# Apply Hadamard gates to the first qubit_count qubits
for q in range(qubit_count):
qc.h(q)
# Apply X gate to the qubit at position 3 + qubit_count
qc.x(3 + qubit_count)
# Apply controlled modular exponentiation gates for each qubit in a loop
for q in range(qubit_count):
qc.append(c_amod15(a, 2**q), [q] + [i + qubit_count for i in range(4)])
# Apply the inverse Quantum Fourier Transform to the first qubit_count qubits
qc.append(qft_dagger(qubit_count), range(qubit_count))
# Measure the first qubit_count qubits and map the result to classical bits
qc.measure(range(qubit_count), range(qubit_count))
# Draw the quantum circuit in text format
qc.draw('text')
# Choose the Qiskit Aer backend for simulating quantum computation
backend = Aer.get_backend('qasm_simulator')
# Execute the quantum circuit on the chosen backend, specifying the number of shots
result = execute(qc, backend, shots=2048).result()
# Get the counts of different measurement outcomes from the result
counts = result.get_counts()
# Plot a histogram of the measurement outcomes
plot_histogram(counts)
# Save account to disk.
QiskitRuntimeService.save_account(channel="ibm_quantum", token="1b79f356170deeac5fdf52081b78581d5bc4f5708f124fa04b4f316ac96b16320f037201caf33bc8ab511d7af999dd07c8737051176abacfa5e318edee4e0837", name="mattalcasabas", overwrite=True)
service = QiskitRuntimeService(name="mattalcasabas")
backend = service.backend("ibm_brisbane")
# Execute the quantum circuit on the chosen backend, specifying the number of shots
result = execute(qc, backend, shots=2048).result()
# Get the counts of different measurement outcomes from the result
counts = result.get_counts()
# Plot a histogram of the measurement outcomes
plot_histogram(counts)
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
from qiskit.quantum_info import DensityMatrix, Operator
# Quantum circuit to unitary matrix
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
state_0 = np.array([1, 0]) # |0>
state_1 = np.array([0, 1]) # |1>
from functools import reduce
Dag = lambda matrix: matrix.conj().T # Dag(M) = M†
Kron = lambda *matrices: reduce(np.kron, matrices) # Kron(state_0, state_0) is |00>
def pm(matrix):
for row in range(len(matrix)):
for col in range (len(matrix[row])):
print("{:.3f}".format(matrix[row][col]), end = " ")
print()
# https://qiskit.org/textbook/ch-algorithms/grover.html
def initCircuit(n):
circuit = QuantumCircuit(n, n)
for i in range(n):
circuit.h(i)
circuit.barrier()
return circuit
inputCircuit_2q = initCircuit(2)
inputCircuit_2q.draw(output='mpl')
def createOracle_3():
circuit = QuantumCircuit(2, 2)
# Oracle for find 3
# U_f
circuit.cz(0, 1)
circuit.barrier()
return circuit
oracleCircuit_3 = createOracle_3()
oracleCircuit_3.draw(output='mpl')
O_3 = Operator(oracleCircuit_3).data
pm(O_3)
# all possible states
state_00 = Kron(state_0, state_0)
state_01 = Kron(state_0, state_1)
state_10 = Kron(state_1, state_0)
state_11 = Kron(state_1, state_1)
print("O|00>", O_3 @ state_00)
print("O|01>", O_3 @ state_01)
print("O|10>", O_3 @ state_10)
print("O|11>", O_3 @ state_11) # flip phase
# H R H, where R = 2|0><0| - I
def createR_2q():
circuit = QuantumCircuit(2, 2)
circuit.z(0)
circuit.z(1)
circuit.cz(0, 1)
return circuit
R_2q = createR_2q()
R_2q.draw(output='mpl')
R_2q = Operator(R_2q).data
pm(R_2q)
# flip phase(no work on zero states) => Conditional Phase Shift gate
print("RO|00>", R_2q @ O_3 @ state_00) # zero state => would not flip
print("RO|01>", R_2q @ O_3 @ state_01)
print("RO|10>", R_2q @ O_3 @ state_10)
print("RO|11>", R_2q @ O_3 @ state_11)
# H R H
def createDiffuser_2q():
circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.h(1)
circuit = circuit.compose(createR_2q())
circuit.h(0)
circuit.h(1)
circuit.barrier()
return circuit
diffuserCircuit_2q = createDiffuser_2q()
diffuserCircuit_2q.draw(output='mpl')
diff_2q = Operator(diffuserCircuit_2q).data
pm(diff_2q)
DB = 0.5 * state_00 + 0.5 * state_01 + 0.5 * state_10 + 0.5 * state_11
print("DO|DB>", diff_2q @ O_3 @ DB)
def createGroverIteration(oracle, diffuser):
return oracle.compose(diffuser)
groverIteration_2q = createGroverIteration(createOracle_3(), createDiffuser_2q())
groverIteration_2q.draw(output='mpl')
groverIteration_2q = createGroverIteration(createOracle_3(), createDiffuser_2q())
grover_2q_1 = initCircuit(2).compose(groverIteration_2q.copy())
grover_2q_1.draw(output='mpl')
grover_2q_1.measure([0, 1], [0, 1])
job = execute(grover_2q_1, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_2q_1)
print(counts) # 100%
plot_histogram(counts, figsize=(1, 5), color="#CC3333", title="one iteration - find 3")
grover_2q_2 = initCircuit(2).compose(groverIteration_2q.copy()).compose(groverIteration_2q.copy())
grover_2q_2.draw(output='mpl')
grover_2q_2.measure([0, 1], [0, 1])
job = execute(grover_2q_2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_2q_2)
print(counts)
plot_histogram(counts, figsize=(7, 5), color="#FF9999", title="two iterations - find 3")
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
from qiskit.quantum_info import DensityMatrix, Operator
# Quantum circuit to unitary matrix
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
state_0 = np.array([1, 0]) # |0>
state_1 = np.array([0, 1]) # |1>
from functools import reduce
Dag = lambda matrix: matrix.conj().T # Dag(M) = M†
Kron = lambda *matrices: reduce(np.kron, matrices) # Kron(state_0, state_0) is |00>
def pm(matrix):
for row in range(len(matrix)):
for col in range (len(matrix[row])):
print("{:.3f}".format(matrix[row][col]), end = " ")
print()
# https://qiskit.org/textbook/ch-algorithms/grover.html
def initCircuit(n):
circuit = QuantumCircuit(n, n)
for i in range(n):
circuit.h(i)
circuit.barrier()
return circuit
inputCircuit_3q = initCircuit(3)
inputCircuit_3q.draw(output='mpl')
def createOracle_6():
circuit = QuantumCircuit(3, 3)
# Oracle for find 6
# U_f
circuit.x(0)
circuit.h(2)
circuit.ccx(0, 1, 2)
circuit.h(2)
circuit.x(0)
circuit.barrier()
return circuit
oracleCircuit_6 = createOracle_6()
oracleCircuit_6.draw(output='mpl')
# where the entry that correspond to the marked item will have a negative phase
pm(Operator(oracleCircuit_6).data)
Operator(oracleCircuit_6).data
# H R H, where R = 2|0><0| - I
def createR_3q():
circuit = QuantumCircuit(3, 3)
circuit.x(2)
circuit.x(0)
circuit.x(1)
circuit.h(2)
circuit.ccx(0, 1, 2)
circuit.barrier(0)
circuit.barrier(1)
circuit.h(2)
circuit.x(2)
circuit.x(0)
circuit.x(1)
return circuit
R_3q = createR_3q()
R_3q.draw(output='mpl')
pm(Operator(R_3q).data)
print('|000>', Kron(state_0, state_0, state_0))
print('R|000>',Operator(R_3q).data @ Kron(state_0, state_0, state_0) )
print('|010>', Kron(state_0, state_1, state_0))
print('R|010>',Operator(R_3q).data @ Kron(state_0, state_1, state_0) )
print('|110>', Kron(state_1, state_1, state_0))
print('R|110>',Operator(R_3q).data @ Kron(state_1, state_1, state_0) )
# H R H
def createDiffuser_3q():
circuit = QuantumCircuit(3, 3)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit = circuit.compose(createR_3q())
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.barrier()
return circuit
diffuserCircuit_3q = createDiffuser_3q()
diffuserCircuit_3q.draw(output='mpl')
pm(Operator(diffuserCircuit_3q).data)
def createGroverIteration(oracle, diffuser):
return oracle.compose(diffuser)
groverIteration_3q = createGroverIteration(createOracle_6(), createDiffuser_3q())
groverIteration_3q.draw(output='mpl')
groverIteration_3q = createGroverIteration(createOracle_6(), createDiffuser_3q())
inputCircuit_3q = initCircuit(3)
inputCircuit_3q.draw(output='mpl')
inputCircuit_3q.measure([0, 1, 2], [0, 1, 2])
job = execute(inputCircuit_3q, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(inputCircuit_3q)
print(counts)
plot_histogram(counts, figsize=(10, 5), color="#FFFFCC", title="superposition state - 3 qubits")
grover_3q_1 = initCircuit(3).compose(groverIteration_3q.copy())
grover_3q_1.draw(output='mpl')
grover_3q_1.measure([0, 1, 2], [0, 1, 2])
job = execute(grover_3q_1, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_3q_1)
print(counts)
plot_histogram(counts, figsize=(10, 5), color="#FFBB00", title="one iteration - find 6")
grover_3q_2 = initCircuit(3).compose(groverIteration_3q.copy()).compose(groverIteration_3q.copy())
# grover_3q_2.draw(output='mpl')
grover_3q_2.measure([0, 1, 2], [0, 1, 2])
job = execute(grover_3q_2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_3q_2)
print(counts)
plot_histogram(counts, figsize=(10, 5), color="#FF8822", title="two iteration - find 6")
grover_3q_3 = initCircuit(3).compose(groverIteration_3q.copy()).compose(groverIteration_3q.copy()).compose(groverIteration_3q.copy())
# grover_3q_3.draw(output='mpl')
grover_3q_3.measure([0, 1, 2], [0, 1, 2])
job = execute(grover_3q_3, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_3q_3)
print(counts)
plot_histogram(counts, figsize=(10, 5), color="#FFFF3F", title="three iteration - find 6")
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
from qiskit.quantum_info import DensityMatrix, Statevector, Operator
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
state_0 = np.array([1, 0])
state_1 = np.array([0, 1])
from functools import reduce
Dag = lambda matrix: matrix.conj().T
Kron = lambda *matrices: reduce(np.kron, matrices)
def pm(matrix):
for row in range(len(matrix)):
for col in range (len(matrix[row])):
print("{:.3f}".format(matrix[row][col]), end = " ")
print()
# H R H, where R = 2|0><0| - I
# A R A^(-1)
def initAACircuit(n):
circuit = QuantumCircuit(n, n)
circuit.x(0)
circuit.h(1)
circuit.z(1)
circuit.h(0)
circuit.barrier()
return circuit
inputAACircuit = initAACircuit(2)
inputAACircuit.draw(output='mpl')
A = Operator(initAACircuit(2))
np.allclose(A.data @ Dag(A.data), np.eye(4))
inputAACircuit.measure([0, 1], [0, 1])
job = execute(inputAACircuit, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(inputAACircuit)
print(counts)
plot_histogram(counts, figsize=(7, 5), color="#CCCC66", title="measurements result of A")
def createOracle_3():
circuit = QuantumCircuit(2, 2)
# Oracle for find 3
# U_f
circuit.cz(0, 1)
circuit.barrier()
return circuit
oracleCircuit_3 = createOracle_3()
oracleCircuit_3.draw(output='mpl')
def createR_2q():
circuit = QuantumCircuit(2, 2)
circuit.z(0)
circuit.z(1)
circuit.cz(0, 1)
return circuit
def createAADiffuser():
circuit = QuantumCircuit(2, 2)
circuit.append(A, [0, 1])
circuit = circuit.compose(createR_2q())
circuit.append(A.conjugate(), [0, 1])
circuit.barrier()
return circuit
diffuserAACircuit = createAADiffuser()
diffuserAACircuit.draw(output='mpl')
def createGroverIteration(oracle, diffuser):
return oracle.compose(diffuser)
aaGroverIteration = createGroverIteration(createOracle_3(), createAADiffuser())
aaGroverIteration.draw(output='mpl')
def createDiffuser_2q():
circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.h(1)
circuit = circuit.compose(createR_2q())
circuit.h(0)
circuit.h(1)
circuit.barrier()
return circuit
incorrectGroverIteration = createGroverIteration(createOracle_3(), createDiffuser_2q())
grover_incorrect_diffuser = initAACircuit(2).compose(incorrectGroverIteration)
grover_incorrect_diffuser.draw(output='mpl')
grover_incorrect_diffuser.measure([0, 1], [0, 1])
job = execute(grover_incorrect_diffuser, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(grover_incorrect_diffuser)
print(counts)
plot_histogram(counts, figsize=(1, 5), color="#99CC33", title="using incorrect diffuser - find 3")
### 3.5.2 correct diffuser
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.