code
stringlengths 66
870k
| docstring
stringlengths 19
26.7k
| func_name
stringlengths 1
138
| language
stringclasses 1
value | repo
stringlengths 7
68
| path
stringlengths 5
324
| url
stringlengths 46
389
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def control_state(self, state):
"""
Set control_state to state.
Args:
state (int,str,projectq.meta.CtrtAll): state of control qubit (ie. positive or negative)
"""
# NB: avoid circular imports
from projectq.meta import ( # pylint: disable=import-outside-toplevel
canonical_ctrl_state,
)
self._control_state = canonical_ctrl_state(state, len(self._control_qubits)) |
Set control_state to state.
Args:
state (int,str,projectq.meta.CtrtAll): state of control qubit (ie. positive or negative)
| control_state | python | ProjectQ-Framework/ProjectQ | projectq/ops/_command.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_command.py | Apache-2.0 |
def add_control_qubits(self, qubits, state=CtrlAll.One):
"""
Add (additional) control qubits to this command object.
They are sorted to ensure a canonical order. Also Qubit objects
are converted to WeakQubitRef objects to allow garbage collection and
thus early deallocation of qubits.
Args:
qubits (list of Qubit objects): List of qubits which control this gate
state (int,str,CtrlAll): Control state (ie. positive or negative) for the qubits being added as
control qubits.
"""
# NB: avoid circular imports
from projectq.meta import ( # pylint: disable=import-outside-toplevel
canonical_ctrl_state,
)
if not isinstance(qubits, list):
raise ValueError('Control qubits must be a list of qubits!')
self._control_qubits.extend([WeakQubitRef(qubit.engine, qubit.id) for qubit in qubits])
self._control_state += canonical_ctrl_state(state, len(qubits))
zipped = sorted(zip(self._control_qubits, self._control_state), key=lambda x: x[0].id)
unzipped_qubit, unzipped_state = zip(*zipped)
self._control_qubits, self._control_state = list(unzipped_qubit), ''.join(unzipped_state)
# Make sure that we do not have contradicting control states for any control qubits
for _, data in itertools.groupby(zipped, key=lambda x: x[0].id):
qubits, states = list(zip(*data))
if len(set(states)) != 1:
raise IncompatibleControlState(
f'Control qubits {list(qubits)} cannot have conflicting control states: {states}'
) |
Add (additional) control qubits to this command object.
They are sorted to ensure a canonical order. Also Qubit objects
are converted to WeakQubitRef objects to allow garbage collection and
thus early deallocation of qubits.
Args:
qubits (list of Qubit objects): List of qubits which control this gate
state (int,str,CtrlAll): Control state (ie. positive or negative) for the qubits being added as
control qubits.
| add_control_qubits | python | ProjectQ-Framework/ProjectQ | projectq/ops/_command.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_command.py | Apache-2.0 |
def engine(self, engine):
"""
Set / Change engine of all qubits to engine.
Args:
engine: New owner of qubits and owner of this Command object
"""
self._engine = engine
for qureg in self.qubits:
for qubit in qureg:
qubit.engine = engine
for qubit in self.control_qubits:
qubit.engine = engine |
Set / Change engine of all qubits to engine.
Args:
engine: New owner of qubits and owner of this Command object
| engine | python | ProjectQ-Framework/ProjectQ | projectq/ops/_command.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_command.py | Apache-2.0 |
def __eq__(self, other):
"""
Compare this command to another command.
Args:
other (Command): Command object to compare this to
Returns: True if Command objects are equal (same gate, applied to same
qubits; ordered modulo interchangeability; and same tags)
"""
if (
isinstance(other, self.__class__)
and self.gate == other.gate
and self.tags == other.tags
and self.engine == other.engine
and self.all_qubits == other.all_qubits
):
return True
return False |
Compare this command to another command.
Args:
other (Command): Command object to compare this to
Returns: True if Command objects are equal (same gate, applied to same
qubits; ordered modulo interchangeability; and same tags)
| __eq__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_command.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_command.py | Apache-2.0 |
def to_string(self, symbols=False):
"""Get string representation of this Command object."""
qubits = self.qubits
ctrlqubits = self.control_qubits
if len(ctrlqubits) > 0:
qubits = (self.control_qubits,) + qubits
qstring = ""
if len(qubits) == 1:
qstring = str(Qureg(qubits[0]))
else:
qstring = "( "
for qreg in qubits:
qstring += str(Qureg(qreg))
qstring += ", "
qstring = f"{qstring[:-2]} )"
cstring = "C" * len(ctrlqubits)
return f"{cstring + self.gate.to_string(symbols)} | {qstring}" | Get string representation of this Command object. | to_string | python | ProjectQ-Framework/ProjectQ | projectq/ops/_command.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_command.py | Apache-2.0 |
def matrix(self):
"""Access to the matrix property of this gate."""
# fmt: off
return np.matrix([[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1]])
# fmt: on | Access to the matrix property of this gate. | matrix | python | ProjectQ-Framework/ProjectQ | projectq/ops/_gates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_gates.py | Apache-2.0 |
def matrix(self):
"""Access to the matrix property of this gate."""
return np.matrix(
[
[1, 0, 0, 0],
[0, 0.5 + 0.5j, 0.5 - 0.5j, 0],
[0, 0.5 - 0.5j, 0.5 + 0.5j, 0],
[0, 0, 0, 1],
]
) | Access to the matrix property of this gate. | matrix | python | ProjectQ-Framework/ProjectQ | projectq/ops/_gates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_gates.py | Apache-2.0 |
def matrix(self):
"""Access to the matrix property of this gate."""
return np.matrix(
[
[math.cos(0.5 * self.angle), -1j * math.sin(0.5 * self.angle)],
[-1j * math.sin(0.5 * self.angle), math.cos(0.5 * self.angle)],
]
) | Access to the matrix property of this gate. | matrix | python | ProjectQ-Framework/ProjectQ | projectq/ops/_gates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_gates.py | Apache-2.0 |
def matrix(self):
"""Access to the matrix property of this gate."""
return np.matrix(
[
[math.cos(0.5 * self.angle), -math.sin(0.5 * self.angle)],
[math.sin(0.5 * self.angle), math.cos(0.5 * self.angle)],
]
) | Access to the matrix property of this gate. | matrix | python | ProjectQ-Framework/ProjectQ | projectq/ops/_gates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_gates.py | Apache-2.0 |
def matrix(self):
"""Access to the matrix property of this gate."""
return np.matrix(
[
[cmath.exp(-0.5 * 1j * self.angle), 0],
[0, cmath.exp(0.5 * 1j * self.angle)],
]
) | Access to the matrix property of this gate. | matrix | python | ProjectQ-Framework/ProjectQ | projectq/ops/_gates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_gates.py | Apache-2.0 |
def matrix(self):
"""Access to the matrix property of this gate."""
return np.matrix(
[
[cmath.cos(0.5 * self.angle), 0, 0, -1j * cmath.sin(0.5 * self.angle)],
[0, cmath.cos(0.5 * self.angle), -1j * cmath.sin(0.5 * self.angle), 0],
[0, -1j * cmath.sin(0.5 * self.angle), cmath.cos(0.5 * self.angle), 0],
[-1j * cmath.sin(0.5 * self.angle), 0, 0, cmath.cos(0.5 * self.angle)],
]
) | Access to the matrix property of this gate. | matrix | python | ProjectQ-Framework/ProjectQ | projectq/ops/_gates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_gates.py | Apache-2.0 |
def matrix(self):
"""Access to the matrix property of this gate."""
return np.matrix(
[
[cmath.cos(0.5 * self.angle), 0, 0, 1j * cmath.sin(0.5 * self.angle)],
[0, cmath.cos(0.5 * self.angle), -1j * cmath.sin(0.5 * self.angle), 0],
[0, -1j * cmath.sin(0.5 * self.angle), cmath.cos(0.5 * self.angle), 0],
[1j * cmath.sin(0.5 * self.angle), 0, 0, cmath.cos(0.5 * self.angle)],
]
) | Access to the matrix property of this gate. | matrix | python | ProjectQ-Framework/ProjectQ | projectq/ops/_gates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_gates.py | Apache-2.0 |
def matrix(self):
"""Access to the matrix property of this gate."""
return np.matrix(
[
[cmath.exp(-0.5 * 1j * self.angle), 0, 0, 0],
[0, cmath.exp(0.5 * 1j * self.angle), 0, 0],
[0, 0, cmath.exp(0.5 * 1j * self.angle), 0],
[0, 0, 0, cmath.exp(-0.5 * 1j * self.angle)],
]
) | Access to the matrix property of this gate. | matrix | python | ProjectQ-Framework/ProjectQ | projectq/ops/_gates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_gates.py | Apache-2.0 |
def __or__(self, qubits):
"""
Operator| overload which enables the syntax Gate | qubits.
Previously (ProjectQ <= v0.3.6) MeasureGate/Measure was allowed to be applied to any number of quantum
registers. Now the MeasureGate/Measure is strictly a single qubit gate.
Raises:
RuntimeError: Since ProjectQ v0.6.0 if the gate is applied to multiple qubits.
"""
num_qubits = 0
for qureg in self.make_tuple_of_qureg(qubits):
for qubit in qureg:
num_qubits += 1
cmd = self.generate_command(([qubit],))
apply_command(cmd)
if num_qubits > 1: # pragma: no cover
raise RuntimeError('Measure is a single qubit gate. Use All(Measure) | qureg instead') |
Operator| overload which enables the syntax Gate | qubits.
Previously (ProjectQ <= v0.3.6) MeasureGate/Measure was allowed to be applied to any number of quantum
registers. Now the MeasureGate/Measure is strictly a single qubit gate.
Raises:
RuntimeError: Since ProjectQ v0.6.0 if the gate is applied to multiple qubits.
| __or__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_gates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_gates.py | Apache-2.0 |
def __init__(self, bits_to_flip):
"""
Initialize a FlipBits gate.
Example:
.. code-block:: python
qureg = eng.allocate_qureg(2)
FlipBits([0, 1]) | qureg
Args:
bits_to_flip(list[int]|list[bool]|str|int): int or array of 0/1, True/False, or string of 0/1 identifying
the qubits to flip. In case of int, the bits to flip are determined from the binary digits, with the
least significant bit corresponding to qureg[0]. If bits_to_flip is negative, exactly all qubits which
would not be flipped for the input -bits_to_flip-1 are flipped, i.e., bits_to_flip=-1 flips all qubits.
"""
super().__init__()
if isinstance(bits_to_flip, int):
self.bits_to_flip = bits_to_flip
else:
self.bits_to_flip = 0
for i in reversed(list(bits_to_flip)):
bit = 0b1 if i == '1' or i == 1 or i is True else 0b0
self.bits_to_flip = (self.bits_to_flip << 1) | bit |
Initialize a FlipBits gate.
Example:
.. code-block:: python
qureg = eng.allocate_qureg(2)
FlipBits([0, 1]) | qureg
Args:
bits_to_flip(list[int]|list[bool]|str|int): int or array of 0/1, True/False, or string of 0/1 identifying
the qubits to flip. In case of int, the bits to flip are determined from the binary digits, with the
least significant bit corresponding to qureg[0]. If bits_to_flip is negative, exactly all qubits which
would not be flipped for the input -bits_to_flip-1 are flipped, i.e., bits_to_flip=-1 flips all qubits.
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_gates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_gates.py | Apache-2.0 |
def __or__(self, qubits):
"""Operator| overload which enables the syntax Gate | qubits."""
quregs_tuple = self.make_tuple_of_qureg(qubits)
if len(quregs_tuple) > 1:
raise ValueError(
f"{str(self)} can only be applied to qubits, quregs, arrays of qubits, "
"and tuples with one individual qubit"
)
for qureg in quregs_tuple:
for i, qubit in enumerate(qureg):
if (self.bits_to_flip >> i) & 1:
XGate() | qubit | Operator| overload which enables the syntax Gate | qubits. | __or__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_gates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_gates.py | Apache-2.0 |
def __init__(self, gate):
"""
Initialize a DaggeredGate representing the inverse of the gate 'gate'.
Args:
gate: Any gate object of which to represent the inverse.
"""
super().__init__()
self._gate = gate
try:
# Hermitian conjugate is inverse matrix
self.matrix = gate.matrix.getH()
except AttributeError:
pass |
Initialize a DaggeredGate representing the inverse of the gate 'gate'.
Args:
gate: Any gate object of which to represent the inverse.
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_metagates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_metagates.py | Apache-2.0 |
def tex_str(self):
"""Return the Latex string representation of a Daggered gate."""
if hasattr(self._gate, 'tex_str'):
return f"{self._gate.tex_str()}${{}}^\\dagger$"
return f"{str(self._gate)}${{}}^\\dagger$" | Return the Latex string representation of a Daggered gate. | tex_str | python | ProjectQ-Framework/ProjectQ | projectq/ops/_metagates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_metagates.py | Apache-2.0 |
def get_inverse(gate):
"""
Return the inverse of a gate.
Tries to call gate.get_inverse and, upon failure, creates a DaggeredGate instead.
Args:
gate: Gate of which to get the inverse
Example:
.. code-block:: python
get_inverse(H) # returns a Hadamard gate (HGate object)
"""
try:
return gate.get_inverse()
except NotInvertible:
return DaggeredGate(gate) |
Return the inverse of a gate.
Tries to call gate.get_inverse and, upon failure, creates a DaggeredGate instead.
Args:
gate: Gate of which to get the inverse
Example:
.. code-block:: python
get_inverse(H) # returns a Hadamard gate (HGate object)
| get_inverse | python | ProjectQ-Framework/ProjectQ | projectq/ops/_metagates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_metagates.py | Apache-2.0 |
def __init__(self, gate, n=1):
"""
Initialize a ControlledGate object.
Args:
gate: Gate to wrap.
n (int): Number of control qubits.
"""
super().__init__()
if isinstance(gate, ControlledGate):
self._gate = gate._gate
self._n = gate._n + n
else:
self._gate = gate
self._n = n |
Initialize a ControlledGate object.
Args:
gate: Gate to wrap.
n (int): Number of control qubits.
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_metagates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_metagates.py | Apache-2.0 |
def __or__(self, qubits):
"""
Apply the controlled gate to qubits, using the first n qubits as controls.
Note: The control qubits can be split across the first quregs. However, the n-th control qubit needs to be
the last qubit in a qureg. The following quregs belong to the gate.
Args:
qubits (tuple of lists of Qubit objects): qubits to which to apply
the gate.
"""
qubits = BasicGate.make_tuple_of_qureg(qubits)
ctrl = []
gate_quregs = []
adding_to_controls = True
for reg in qubits:
if adding_to_controls:
ctrl += reg
adding_to_controls = len(ctrl) < self._n
else:
gate_quregs.append(reg)
# Test that there were enough control quregs and that that
# the last control qubit was the last qubit in a qureg.
if len(ctrl) != self._n:
raise ControlQubitError(
"Wrong number of control qubits. "
"First qureg(s) need to contain exactly "
"the required number of control quregs."
)
import projectq.meta # pylint: disable=import-outside-toplevel
with projectq.meta.Control(gate_quregs[0][0].engine, ctrl):
self._gate | tuple(gate_quregs) |
Apply the controlled gate to qubits, using the first n qubits as controls.
Note: The control qubits can be split across the first quregs. However, the n-th control qubit needs to be
the last qubit in a qureg. The following quregs belong to the gate.
Args:
qubits (tuple of lists of Qubit objects): qubits to which to apply
the gate.
| __or__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_metagates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_metagates.py | Apache-2.0 |
def __init__(self, gate):
"""Initialize a Tensor object for the gate."""
super().__init__()
self._gate = gate | Initialize a Tensor object for the gate. | __init__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_metagates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_metagates.py | Apache-2.0 |
def __or__(self, qubits):
"""Operator| overload which enables the syntax Gate | qubits."""
if isinstance(qubits, tuple):
if len(qubits) != 1:
raise ValueError('Tensor/All must be applied to a single quantum register!')
qubits = qubits[0]
if not isinstance(qubits, list):
raise ValueError('Tensor/All must be applied to a list of qubits!')
for qubit in qubits:
self._gate | qubit | Operator| overload which enables the syntax Gate | qubits. | __or__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_metagates.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_metagates.py | Apache-2.0 |
def __init__(self, term=None, coefficient=1.0): # pylint: disable=too-many-branches
"""
Initialize a QubitOperator object.
The init function only allows to initialize one term. Additional terms have to be added using += (which is
fast) or using + of two QubitOperator objects:
Example:
.. code-block:: python
ham = QubitOperator('X0 Y3', 0.5) + 0.6 * QubitOperator('X0 Y3')
# Equivalently
ham2 = QubitOperator('X0 Y3', 0.5)
ham2 += 0.6 * QubitOperator('X0 Y3')
Note:
Adding terms to QubitOperator is faster using += (as this is done by in-place addition). Specifying the
coefficient in the __init__ is faster than by multiplying a QubitOperator with a scalar as calls an
out-of-place multiplication.
Args:
coefficient (complex float, optional): The coefficient of the first term of this QubitOperator. Default is
1.0.
term (optional, empty tuple, a tuple of tuples, or a string):
1) Default is None which means there are no terms in the QubitOperator hence it is the "zero" Operator
2) An empty tuple means there are no non-trivial Pauli operators acting on the qubits hence only
identities with a coefficient (which by default is 1.0).
3) A sorted tuple of tuples. The first element of each tuple is an integer indicating the qubit on
which a non-trivial local operator acts, starting from zero. The second element of each tuple is a
string, either 'X', 'Y' or 'Z', indicating which local operator acts on that qubit.
4) A string of the form 'X0 Z2 Y5', indicating an X on qubit 0, Z on qubit 2, and Y on qubit 5. The
string should be sorted by the qubit number. '' is the identity.
Raises:
QubitOperatorError: Invalid operators provided to QubitOperator.
"""
super().__init__()
if not isinstance(coefficient, (int, float, complex)):
raise ValueError('Coefficient must be a numeric type.')
self.terms = {}
if term is None:
return
if isinstance(term, tuple):
if term == ():
self.terms[()] = coefficient
else:
# Test that input is a tuple of tuples and correct action
for local_operator in term:
if not isinstance(local_operator, tuple) or len(local_operator) != 2:
raise ValueError("term specified incorrectly.")
qubit_num, action = local_operator
if not isinstance(action, str) or action not in 'XYZ':
raise ValueError("Invalid action provided: must be string 'X', 'Y', or 'Z'.")
if not (isinstance(qubit_num, int) and qubit_num >= 0):
raise QubitOperatorError(
"Invalid qubit number provided to QubitTerm: must be a non-negative int."
)
# Sort and add to self.terms:
term = list(term)
term.sort(key=lambda loc_operator: loc_operator[0])
self.terms[tuple(term)] = coefficient
elif isinstance(term, str):
list_ops = []
for element in term.split():
if len(element) < 2:
raise ValueError('term specified incorrectly.')
list_ops.append((int(element[1:]), element[0]))
# Test that list_ops has correct format of tuples
for local_operator in list_ops:
qubit_num, action = local_operator
if not isinstance(action, str) or action not in 'XYZ':
raise ValueError("Invalid action provided: must be string 'X', 'Y', or 'Z'.")
if not (isinstance(qubit_num, int) and qubit_num >= 0):
raise QubitOperatorError("Invalid qubit number provided to QubitTerm: must be a non-negative int.")
# Sort and add to self.terms:
list_ops.sort(key=lambda loc_operator: loc_operator[0])
self.terms[tuple(list_ops)] = coefficient
else:
raise ValueError('term specified incorrectly.') |
Initialize a QubitOperator object.
The init function only allows to initialize one term. Additional terms have to be added using += (which is
fast) or using + of two QubitOperator objects:
Example:
.. code-block:: python
ham = QubitOperator('X0 Y3', 0.5) + 0.6 * QubitOperator('X0 Y3')
# Equivalently
ham2 = QubitOperator('X0 Y3', 0.5)
ham2 += 0.6 * QubitOperator('X0 Y3')
Note:
Adding terms to QubitOperator is faster using += (as this is done by in-place addition). Specifying the
coefficient in the __init__ is faster than by multiplying a QubitOperator with a scalar as calls an
out-of-place multiplication.
Args:
coefficient (complex float, optional): The coefficient of the first term of this QubitOperator. Default is
1.0.
term (optional, empty tuple, a tuple of tuples, or a string):
1) Default is None which means there are no terms in the QubitOperator hence it is the "zero" Operator
2) An empty tuple means there are no non-trivial Pauli operators acting on the qubits hence only
identities with a coefficient (which by default is 1.0).
3) A sorted tuple of tuples. The first element of each tuple is an integer indicating the qubit on
which a non-trivial local operator acts, starting from zero. The second element of each tuple is a
string, either 'X', 'Y' or 'Z', indicating which local operator acts on that qubit.
4) A string of the form 'X0 Z2 Y5', indicating an X on qubit 0, Z on qubit 2, and Y on qubit 5. The
string should be sorted by the qubit number. '' is the identity.
Raises:
QubitOperatorError: Invalid operators provided to QubitOperator.
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def compress(self, abs_tol=1e-12):
"""
Compress the coefficient of a QubitOperator.
Eliminate all terms with coefficients close to zero and removes imaginary parts of coefficients that are close
to zero.
Args:
abs_tol(float): Absolute tolerance, must be at least 0.0
"""
new_terms = {}
for term, coeff in self.terms.items():
if abs(coeff.imag) <= abs_tol:
coeff = coeff.real
if abs(coeff) > abs_tol:
new_terms[term] = coeff
self.terms = new_terms |
Compress the coefficient of a QubitOperator.
Eliminate all terms with coefficients close to zero and removes imaginary parts of coefficients that are close
to zero.
Args:
abs_tol(float): Absolute tolerance, must be at least 0.0
| compress | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def isclose(self, other, rel_tol=1e-12, abs_tol=1e-12):
"""
Return True if other (QubitOperator) is close to self.
Comparison is done for each term individually. Return True if the difference between each term in self and
other is less than the relative tolerance w.r.t. either other or self (symmetric test) or if the difference is
less than the absolute tolerance.
Args:
other(QubitOperator): QubitOperator to compare against.
rel_tol(float): Relative tolerance, must be greater than 0.0
abs_tol(float): Absolute tolerance, must be at least 0.0
"""
# terms which are in both:
for term in set(self.terms).intersection(set(other.terms)):
left = self.terms[term]
right = other.terms[term]
# math.isclose does this in Python >=3.5
if not abs(left - right) <= max(rel_tol * max(abs(left), abs(right)), abs_tol):
return False
# terms only in one (compare to 0.0 so only abs_tol)
for term in set(self.terms).symmetric_difference(set(other.terms)):
if term in self.terms:
if not abs(self.terms[term]) <= abs_tol:
return False
elif not abs(other.terms[term]) <= abs_tol:
return False
return True |
Return True if other (QubitOperator) is close to self.
Comparison is done for each term individually. Return True if the difference between each term in self and
other is less than the relative tolerance w.r.t. either other or self (symmetric test) or if the difference is
less than the absolute tolerance.
Args:
other(QubitOperator): QubitOperator to compare against.
rel_tol(float): Relative tolerance, must be greater than 0.0
abs_tol(float): Absolute tolerance, must be at least 0.0
| isclose | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def __or__(self, qubits): # pylint: disable=too-many-locals
"""
Operator| overload which enables the syntax Gate | qubits.
In particular, enable the following syntax:
.. code-block:: python
QubitOperator(...) | qureg
QubitOperator(...) | (qureg,)
QubitOperator(...) | qubit
QubitOperator(...) | (qubit,)
Unlike other gates, this gate is only allowed to be applied to one
quantum register or one qubit and only if the QubitOperator is
unitary, i.e., consists of one term with a coefficient whose absolute
values is 1.
Example:
.. code-block:: python
eng = projectq.MainEngine()
qureg = eng.allocate_qureg(6)
QubitOperator('X0 X5', 1.0j) | qureg # Applies X to qubit 0 and 5
# with an additional global
# phase of 1.j
While in the above example the QubitOperator gate is applied to 6
qubits, it only acts non-trivially on the two qubits qureg[0] and
qureg[5]. Therefore, the operator| will create a new rescaled
QubitOperator, i.e, it sends the equivalent of the following new gate
to the MainEngine:
.. code-block:: python
QubitOperator('X0 X1', 1.0j) | [qureg[0], qureg[5]]
which is only a two qubit gate.
Args:
qubits: one Qubit object, one list of Qubit objects, one Qureg
object, or a tuple of the former three cases.
Raises:
TypeError: If QubitOperator is not unitary or applied to more than
one quantum register.
ValueError: If quantum register does not have enough qubits
"""
# Check that input is only one qureg or one qubit
qubits = self.make_tuple_of_qureg(qubits)
if len(qubits) != 1:
raise TypeError("Only one qubit or qureg allowed.")
# Check that operator is unitary
if not len(self.terms) == 1:
raise TypeError(
"Too many terms. Only QubitOperators consisting "
"of a single term (single n-qubit Pauli operator) "
"with a coefficient of unit length can be applied "
"to qubits with this function."
)
((term, coefficient),) = self.terms.items()
phase = cmath.phase(coefficient)
if abs(coefficient) < 1 - EQ_TOLERANCE or abs(coefficient) > 1 + EQ_TOLERANCE:
raise TypeError(
"abs(coefficient) != 1. Only QubitOperators "
"consisting of a single term (single n-qubit "
"Pauli operator) with a coefficient of unit "
"length can be applied to qubits with this "
"function."
)
# Test if we need to apply only Ph
if term == ():
Ph(phase) | qubits[0][0]
return
# Check that Qureg has enough qubits:
num_qubits = len(qubits[0])
non_trivial_qubits = set()
for index, _ in term:
non_trivial_qubits.add(index)
if max(non_trivial_qubits) >= num_qubits:
raise ValueError("QubitOperator acts on more qubits than the gate is applied to.")
# Apply X, Y, Z, if QubitOperator acts only on one qubit
if len(term) == 1:
if term[0][1] == "X":
X | qubits[0][term[0][0]]
elif term[0][1] == "Y":
Y | qubits[0][term[0][0]]
elif term[0][1] == "Z":
Z | qubits[0][term[0][0]]
Ph(phase) | qubits[0][term[0][0]]
return
# Create new QubitOperator gate with rescaled qubit indices in
# 0,..., len(non_trivial_qubits) - 1
new_index = {}
non_trivial_qubits = sorted(non_trivial_qubits)
for i, qubit in enumerate(non_trivial_qubits):
new_index[qubit] = i
new_qubitoperator = QubitOperator()
new_term = tuple((new_index[index], action) for index, action in term)
new_qubitoperator.terms[new_term] = coefficient
new_qubits = [qubits[0][i] for i in non_trivial_qubits]
# Apply new gate
cmd = new_qubitoperator.generate_command(new_qubits)
apply_command(cmd) |
Operator| overload which enables the syntax Gate | qubits.
In particular, enable the following syntax:
.. code-block:: python
QubitOperator(...) | qureg
QubitOperator(...) | (qureg,)
QubitOperator(...) | qubit
QubitOperator(...) | (qubit,)
Unlike other gates, this gate is only allowed to be applied to one
quantum register or one qubit and only if the QubitOperator is
unitary, i.e., consists of one term with a coefficient whose absolute
values is 1.
Example:
.. code-block:: python
eng = projectq.MainEngine()
qureg = eng.allocate_qureg(6)
QubitOperator('X0 X5', 1.0j) | qureg # Applies X to qubit 0 and 5
# with an additional global
# phase of 1.j
While in the above example the QubitOperator gate is applied to 6
qubits, it only acts non-trivially on the two qubits qureg[0] and
qureg[5]. Therefore, the operator| will create a new rescaled
QubitOperator, i.e, it sends the equivalent of the following new gate
to the MainEngine:
.. code-block:: python
QubitOperator('X0 X1', 1.0j) | [qureg[0], qureg[5]]
which is only a two qubit gate.
Args:
qubits: one Qubit object, one list of Qubit objects, one Qureg
object, or a tuple of the former three cases.
Raises:
TypeError: If QubitOperator is not unitary or applied to more than
one quantum register.
ValueError: If quantum register does not have enough qubits
| __or__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def get_inverse(self):
"""
Return the inverse gate of a QubitOperator if applied as a gate.
Raises:
NotInvertible: Not implemented for QubitOperators which have
multiple terms or a coefficient with absolute value
not equal to 1.
"""
if len(self.terms) == 1:
((term, coefficient),) = self.terms.items()
if not abs(coefficient) < 1 - EQ_TOLERANCE and not abs(coefficient) > 1 + EQ_TOLERANCE:
return QubitOperator(term, coefficient ** (-1))
raise NotInvertible("BasicGate: No get_inverse() implemented.") |
Return the inverse gate of a QubitOperator if applied as a gate.
Raises:
NotInvertible: Not implemented for QubitOperators which have
multiple terms or a coefficient with absolute value
not equal to 1.
| get_inverse | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def get_merged(self, other):
"""
Return this gate merged with another gate.
Standard implementation of get_merged:
Raises:
NotMergeable: merging is not possible
"""
if isinstance(other, self.__class__) and len(other.terms) == 1 and len(self.terms) == 1:
return self * other
raise NotMergeable() |
Return this gate merged with another gate.
Standard implementation of get_merged:
Raises:
NotMergeable: merging is not possible
| get_merged | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def __imul__(self, multiplier): # pylint: disable=too-many-locals,too-many-branches
"""
In-place multiply (*=) terms with scalar or QubitOperator.
Args:
multiplier(complex float, or QubitOperator): multiplier
"""
# Handle scalars.
if isinstance(multiplier, (int, float, complex)):
for term in self.terms:
self.terms[term] *= multiplier
return self
# Handle QubitOperator.
if isinstance(multiplier, QubitOperator): # pylint: disable=too-many-nested-blocks
result_terms = {}
for left_term, left_coeff in self.terms.items():
for right_term, right_coeff in multiplier.terms.items():
new_coefficient = left_coeff * right_coeff
# Loop through local operators and create new sorted list
# of representing the product local operator:
product_operators = []
left_operator_index = 0
right_operator_index = 0
n_operators_left = len(left_term)
n_operators_right = len(right_term)
while left_operator_index < n_operators_left and right_operator_index < n_operators_right:
(left_qubit, left_loc_op) = left_term[left_operator_index]
(right_qubit, right_loc_op) = right_term[right_operator_index]
# Multiply local operators acting on the same qubit
if left_qubit == right_qubit:
left_operator_index += 1
right_operator_index += 1
(scalar, loc_op) = _PAULI_OPERATOR_PRODUCTS[(left_loc_op, right_loc_op)]
# Add new term.
if loc_op != 'I':
product_operators += [(left_qubit, loc_op)]
new_coefficient *= scalar
# Note if loc_op == 'I', then scalar == 1.0
# If left_qubit > right_qubit, add right_loc_op; else,
# add left_loc_op.
elif left_qubit > right_qubit:
product_operators += [(right_qubit, right_loc_op)]
right_operator_index += 1
else:
product_operators += [(left_qubit, left_loc_op)]
left_operator_index += 1
# Finish the remainding operators:
if left_operator_index == n_operators_left:
product_operators += right_term[right_operator_index::]
elif right_operator_index == n_operators_right:
product_operators += left_term[left_operator_index::]
# Add to result dict
tmp_key = tuple(product_operators)
if tmp_key in result_terms:
result_terms[tmp_key] += new_coefficient
else:
result_terms[tmp_key] = new_coefficient
self.terms = result_terms
return self
raise TypeError('Cannot in-place multiply term of invalid type to QubitTerm.') |
In-place multiply (*=) terms with scalar or QubitOperator.
Args:
multiplier(complex float, or QubitOperator): multiplier
| __imul__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def __mul__(self, multiplier):
"""
Return self * multiplier for a scalar, or a QubitOperator.
Args:
multiplier: A scalar, or a QubitOperator.
Returns:
product: A QubitOperator.
Raises:
TypeError: Invalid type cannot be multiply with QubitOperator.
"""
if isinstance(multiplier, (int, float, complex, QubitOperator)):
product = copy.deepcopy(self)
product *= multiplier
return product
raise TypeError('Object of invalid type cannot multiply with QubitOperator.') |
Return self * multiplier for a scalar, or a QubitOperator.
Args:
multiplier: A scalar, or a QubitOperator.
Returns:
product: A QubitOperator.
Raises:
TypeError: Invalid type cannot be multiply with QubitOperator.
| __mul__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def __rmul__(self, multiplier):
"""
Return multiplier * self for a scalar.
We only define __rmul__ for scalars because the left multiply
exist for QubitOperator and left multiply
is also queried as the default behavior.
Args:
multiplier: A scalar to multiply by.
Returns:
product: A new instance of QubitOperator.
Raises:
TypeError: Object of invalid type cannot multiply QubitOperator.
"""
if not isinstance(multiplier, (int, float, complex)):
raise TypeError('Object of invalid type cannot multiply with QubitOperator.')
return self * multiplier |
Return multiplier * self for a scalar.
We only define __rmul__ for scalars because the left multiply
exist for QubitOperator and left multiply
is also queried as the default behavior.
Args:
multiplier: A scalar to multiply by.
Returns:
product: A new instance of QubitOperator.
Raises:
TypeError: Object of invalid type cannot multiply QubitOperator.
| __rmul__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def __truediv__(self, divisor):
"""
Return self / divisor for a scalar.
Note:
This is always floating point division.
Args:
divisor: A scalar to divide by.
Returns:
A new instance of QubitOperator.
Raises:
TypeError: Cannot divide local operator by non-scalar type.
"""
if not isinstance(divisor, (int, float, complex)):
raise TypeError('Cannot divide QubitOperator by non-scalar type.')
return self * (1.0 / divisor) |
Return self / divisor for a scalar.
Note:
This is always floating point division.
Args:
divisor: A scalar to divide by.
Returns:
A new instance of QubitOperator.
Raises:
TypeError: Cannot divide local operator by non-scalar type.
| __truediv__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def __iadd__(self, addend):
"""
In-place method for += addition of QubitOperator.
Args:
addend: A QubitOperator.
Raises:
TypeError: Cannot add invalid type.
"""
if isinstance(addend, QubitOperator):
for term in addend.terms:
if term in self.terms:
if abs(addend.terms[term] + self.terms[term]) > 0.0:
self.terms[term] += addend.terms[term]
else:
self.terms.pop(term)
else:
self.terms[term] = addend.terms[term]
else:
raise TypeError('Cannot add invalid type to QubitOperator.')
return self |
In-place method for += addition of QubitOperator.
Args:
addend: A QubitOperator.
Raises:
TypeError: Cannot add invalid type.
| __iadd__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def __isub__(self, subtrahend):
"""
In-place method for -= subtraction of QubitOperator.
Args:
subtrahend: A QubitOperator.
Raises:
TypeError: Cannot subtract invalid type from QubitOperator.
"""
if isinstance(subtrahend, QubitOperator):
for term in subtrahend.terms:
if term in self.terms:
if abs(self.terms[term] - subtrahend.terms[term]) > 0.0:
self.terms[term] -= subtrahend.terms[term]
else:
self.terms.pop(term)
else:
self.terms[term] = -subtrahend.terms[term]
else:
raise TypeError('Cannot subtract invalid type from QubitOperator.')
return self |
In-place method for -= subtraction of QubitOperator.
Args:
subtrahend: A QubitOperator.
Raises:
TypeError: Cannot subtract invalid type from QubitOperator.
| __isub__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def __str__(self):
"""Return a string representation of the object."""
if not self.terms:
return '0'
string_rep = ''
for term, coeff in self.terms.items():
tmp_string = f'{coeff}'
if term == ():
tmp_string += ' I'
for operator in term:
if operator[1] == 'X':
tmp_string += f' X{operator[0]}'
elif operator[1] == 'Y':
tmp_string += f' Y{operator[0]}'
elif operator[1] == 'Z':
tmp_string += f' Z{operator[0]}'
else: # pragma: no cover
raise ValueError('Internal compiler error: operator must be one of X, Y, Z!')
string_rep += f'{tmp_string} +\n'
return string_rep[:-3] | Return a string representation of the object. | __str__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_qubit_operator.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_qubit_operator.py | Apache-2.0 |
def __init__(self, final_state):
"""
Initialize a StatePreparation gate.
Example:
.. code-block:: python
qureg = eng.allocate_qureg(2)
StatePreparation([0.5, -0.5j, -0.5, 0.5]) | qureg
Note:
final_state[k] is taken to be the amplitude of the computational basis state whose string is equal to the
binary representation of k.
Args:
final_state(list[complex]): wavefunction of the desired quantum state. len(final_state) must be
2**len(qureg). Must be normalized!
"""
super().__init__()
self.final_state = list(final_state) |
Initialize a StatePreparation gate.
Example:
.. code-block:: python
qureg = eng.allocate_qureg(2)
StatePreparation([0.5, -0.5j, -0.5, 0.5]) | qureg
Note:
final_state[k] is taken to be the amplitude of the computational basis state whose string is equal to the
binary representation of k.
Args:
final_state(list[complex]): wavefunction of the desired quantum state. len(final_state) must be
2**len(qureg). Must be normalized!
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_state_prep.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_state_prep.py | Apache-2.0 |
def get_merged(self, other):
"""
Return self merged with another TimeEvolution gate if possible.
Two TimeEvolution gates are merged if:
1) both have the same terms
2) the proportionality factor for each of the terms must have relative error <= 1e-9 compared to the
proportionality factors of the other terms.
Note:
While one could merge gates for which both hamiltonians commute, we are not doing this as in general the
resulting gate would have to be decomposed again.
Note:
We are not comparing if terms are proportional to each other with an absolute tolerance. It is up to the
user to remove terms close to zero because we cannot choose a suitable absolute error which works for
everyone. Use, e.g., a decomposition rule for that.
Args:
other: TimeEvolution gate
Raises:
NotMergeable: If the other gate is not a TimeEvolution gate or hamiltonians are not suitable for merging.
Returns:
New TimeEvolution gate equivalent to the two merged gates.
"""
rel_tol = 1e-9
if isinstance(other, TimeEvolution) and set(self.hamiltonian.terms) == set(other.hamiltonian.terms):
factor = None
for term in self.hamiltonian.terms:
if factor is None:
factor = self.hamiltonian.terms[term] / float(other.hamiltonian.terms[term])
else:
tmp = self.hamiltonian.terms[term] / float(other.hamiltonian.terms[term])
if not abs(factor - tmp) <= (rel_tol * max(abs(factor), abs(tmp))):
raise NotMergeable("Cannot merge these two gates.")
# Terms are proportional to each other
new_time = self.time + other.time / factor
return TimeEvolution(time=new_time, hamiltonian=self.hamiltonian)
raise NotMergeable("Cannot merge these two gates.") |
Return self merged with another TimeEvolution gate if possible.
Two TimeEvolution gates are merged if:
1) both have the same terms
2) the proportionality factor for each of the terms must have relative error <= 1e-9 compared to the
proportionality factors of the other terms.
Note:
While one could merge gates for which both hamiltonians commute, we are not doing this as in general the
resulting gate would have to be decomposed again.
Note:
We are not comparing if terms are proportional to each other with an absolute tolerance. It is up to the
user to remove terms close to zero because we cannot choose a suitable absolute error which works for
everyone. Use, e.g., a decomposition rule for that.
Args:
other: TimeEvolution gate
Raises:
NotMergeable: If the other gate is not a TimeEvolution gate or hamiltonians are not suitable for merging.
Returns:
New TimeEvolution gate equivalent to the two merged gates.
| get_merged | python | ProjectQ-Framework/ProjectQ | projectq/ops/_time_evolution.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_time_evolution.py | Apache-2.0 |
def __or__(self, qubits):
"""
Operator| overload which enables the syntax Gate | qubits.
In particular, enable the following syntax:
.. code-block:: python
TimeEvolution(...) | qureg
TimeEvolution(...) | (qureg,)
TimeEvolution(...) | qubit
TimeEvolution(...) | (qubit,)
Unlike other gates, this gate is only allowed to be applied to one quantum register or one qubit.
Example:
.. code-block:: python
wavefunction = eng.allocate_qureg(5)
hamiltonian = QubitOperator("X1 Y3", 0.5)
TimeEvolution(time=2.0, hamiltonian=hamiltonian) | wavefunction
While in the above example the TimeEvolution gate is applied to 5 qubits, the hamiltonian of this
TimeEvolution gate acts only non-trivially on the two qubits wavefunction[1] and wavefunction[3]. Therefore,
the operator| will rescale the indices in the hamiltonian and sends the equivalent of the following new gate
to the MainEngine:
.. code-block:: python
h = QubitOperator("X0 Y1", 0.5)
TimeEvolution(2.0, h) | [wavefunction[1], wavefunction[3]]
which is only a two qubit gate.
Args:
qubits: one Qubit object, one list of Qubit objects, one Qureg object, or a tuple of the former three
cases.
"""
# Check that input is only one qureg or one qubit
qubits = self.make_tuple_of_qureg(qubits)
if len(qubits) != 1:
raise TypeError("Only one qubit or qureg allowed.")
# Check that if hamiltonian has only an identity term,
# apply a global phase:
if len(self.hamiltonian.terms) == 1 and () in self.hamiltonian.terms:
Ph(-1 * self.time * self.hamiltonian.terms[()]) | qubits[0][0]
return
num_qubits = len(qubits[0])
non_trivial_qubits = set()
for term in self.hamiltonian.terms:
for index, _ in term:
non_trivial_qubits.add(index)
if max(non_trivial_qubits) >= num_qubits:
raise ValueError("hamiltonian acts on more qubits than the gate is applied to.")
# create new TimeEvolution gate with rescaled qubit indices in
# self.hamiltonian which are ordered from
# 0,...,len(non_trivial_qubits) - 1
new_index = {}
non_trivial_qubits = sorted(non_trivial_qubits)
for i, qubit in enumerate(non_trivial_qubits):
new_index[qubit] = i
new_hamiltonian = QubitOperator()
for term in self.hamiltonian.terms:
new_term = tuple((new_index[index], action) for index, action in term)
new_hamiltonian.terms[new_term] = self.hamiltonian.terms[term]
new_gate = TimeEvolution(time=self.time, hamiltonian=new_hamiltonian)
new_qubits = [qubits[0][i] for i in non_trivial_qubits]
# Apply new gate
cmd = new_gate.generate_command(new_qubits)
apply_command(cmd) |
Operator| overload which enables the syntax Gate | qubits.
In particular, enable the following syntax:
.. code-block:: python
TimeEvolution(...) | qureg
TimeEvolution(...) | (qureg,)
TimeEvolution(...) | qubit
TimeEvolution(...) | (qubit,)
Unlike other gates, this gate is only allowed to be applied to one quantum register or one qubit.
Example:
.. code-block:: python
wavefunction = eng.allocate_qureg(5)
hamiltonian = QubitOperator("X1 Y3", 0.5)
TimeEvolution(time=2.0, hamiltonian=hamiltonian) | wavefunction
While in the above example the TimeEvolution gate is applied to 5 qubits, the hamiltonian of this
TimeEvolution gate acts only non-trivially on the two qubits wavefunction[1] and wavefunction[3]. Therefore,
the operator| will rescale the indices in the hamiltonian and sends the equivalent of the following new gate
to the MainEngine:
.. code-block:: python
h = QubitOperator("X0 Y1", 0.5)
TimeEvolution(2.0, h) | [wavefunction[1], wavefunction[3]]
which is only a two qubit gate.
Args:
qubits: one Qubit object, one list of Qubit objects, one Qureg object, or a tuple of the former three
cases.
| __or__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_time_evolution.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_time_evolution.py | Apache-2.0 |
def get_merged(self, other):
"""Return self merged with another gate."""
if isinstance(other, self.__class__):
new_angles = [angle1 + angle2 for (angle1, angle2) in zip(self.angles, other.angles)]
return self.__class__(new_angles)
raise NotMergeable() | Return self merged with another gate. | get_merged | python | ProjectQ-Framework/ProjectQ | projectq/ops/_uniformly_controlled_rotation.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_uniformly_controlled_rotation.py | Apache-2.0 |
def __eq__(self, other):
"""Return True if same class, same rotation angles."""
if isinstance(other, self.__class__):
return self.angles == other.angles
return False | Return True if same class, same rotation angles. | __eq__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_uniformly_controlled_rotation.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_uniformly_controlled_rotation.py | Apache-2.0 |
def get_merged(self, other):
"""Return self merged with another gate."""
if isinstance(other, self.__class__):
new_angles = [angle1 + angle2 for (angle1, angle2) in zip(self.angles, other.angles)]
return self.__class__(new_angles)
raise NotMergeable() | Return self merged with another gate. | get_merged | python | ProjectQ-Framework/ProjectQ | projectq/ops/_uniformly_controlled_rotation.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_uniformly_controlled_rotation.py | Apache-2.0 |
def __eq__(self, other):
"""Return True if same class, same rotation angles."""
if isinstance(other, self.__class__):
return self.angles == other.angles
return False | Return True if same class, same rotation angles. | __eq__ | python | ProjectQ-Framework/ProjectQ | projectq/ops/_uniformly_controlled_rotation.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/ops/_uniformly_controlled_rotation.py | Apache-2.0 |
def get_engine_list(token=None, device=None):
"""Return the default list of compiler engine for the AQT platform."""
# Access to the hardware properties via show_devices
# Can also be extended to take into account gate fidelities, new available
# gate, etc..
devices = show_devices(token)
aqt_setup = []
if device not in devices:
raise DeviceOfflineError('Error when configuring engine list: device requested for Backend not connected')
if device == 'aqt_simulator':
# The 11 qubit online simulator doesn't need a specific mapping for
# gates. Can also run wider gateset but this setup keep the
# restrictedgateset setup for coherence
mapper = BasicMapperEngine()
# Note: Manual Mapper doesn't work, because its map is updated only if
# gates are applied if gates in the register are not used, then it
# will lead to state errors
res = {}
for i in range(devices[device]['nq']):
res[i] = i
mapper.current_mapping = res
aqt_setup = [mapper]
else:
# If there is an online device not handled into ProjectQ it's not too
# bad, the engine_list can be constructed manually with the
# appropriate mapper and the 'coupling_map' parameter
raise DeviceNotHandledError('Device not yet fully handled by ProjectQ')
# Most gates need to be decomposed into a subset that is manually converted
# in the backend (until the implementation of the U1,U2,U3)
setup = restrictedgateset.get_engine_list(one_qubit_gates=(Rx, Ry), two_qubit_gates=(Rxx,), other_gates=(Barrier,))
setup.extend(aqt_setup)
return setup | Return the default list of compiler engine for the AQT platform. | get_engine_list | python | ProjectQ-Framework/ProjectQ | projectq/setups/aqt.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/aqt.py | Apache-2.0 |
def get_engine_list(credentials=None, device=None):
"""Return the default list of compiler engine for the AWS Braket platform."""
# Access to the hardware properties via show_devices
# Can also be extended to take into account gate fidelities, new available
# gate, etc..
devices = show_devices(credentials)
if device not in devices:
raise DeviceOfflineError('Error when configuring engine list: device requested for Backend not available')
# We left the real device to manage the mapping and optimizacion: "The IonQ
# and Rigetti devices compile the provided circuit into their respective
# native gate sets automatically, and they map the abstract qubit indices
# to physical qubits on the respective QPU."
# (see: https://docs.aws.amazon.com/braket/latest/developerguide/braket-submit-to-qpu.html)
# TODO: Investigate if explicit mapping is an advantage
if device == 'SV1':
setup = restrictedgateset.get_engine_list(
one_qubit_gates=(R, H, Rx, Ry, Rz, S, Sdag, T, Tdag, X, Y, Z, SqrtX),
two_qubit_gates=(Swap,),
other_gates=(Barrier,),
)
return setup
if device == 'Aspen-8':
setup = restrictedgateset.get_engine_list(
one_qubit_gates=(R, H, Rx, Ry, Rz, S, Sdag, T, Tdag, X, Y, Z),
two_qubit_gates=(Swap,),
other_gates=(Barrier,),
)
return setup
if device == 'IonQ Device':
setup = restrictedgateset.get_engine_list(
one_qubit_gates=(H, Rx, Ry, Rz, S, Sdag, T, Tdag, X, Y, Z, SqrtX),
two_qubit_gates=(Swap,),
other_gates=(Barrier,),
)
return setup
raise DeviceNotHandledError(f'Unsupported device type: {device}!') # pragma: no cover | Return the default list of compiler engine for the AWS Braket platform. | get_engine_list | python | ProjectQ-Framework/ProjectQ | projectq/setups/awsbraket.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/awsbraket.py | Apache-2.0 |
def get_engine_list():
"""Return the default list of compiler engine."""
rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
return [TagRemover(), LocalOptimizer(10), AutoReplacer(rule_set), TagRemover(), LocalOptimizer(10)] | Return the default list of compiler engine. | get_engine_list | python | ProjectQ-Framework/ProjectQ | projectq/setups/default.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/default.py | Apache-2.0 |
def get_engine_list(num_rows, num_columns, one_qubit_gates="any", two_qubit_gates=(CNOT, Swap)):
"""
Return an engine list to compile to a 2-D grid of qubits.
Note:
If you choose a new gate set for which the compiler does not yet have standard rules, it raises an
`NoGateDecompositionError` or a `RuntimeError: maximum recursion depth exceeded...`. Also note that even the
gate sets which work might not yet be optimized. So make sure to double check and potentially extend the
decomposition rules. This implementation currently requires that the one qubit gates must contain Rz and at
least one of {Ry(best), Rx, H} and the two qubit gate must contain CNOT (recommended) or CZ.
Note:
Classical instructions gates such as e.g. Flush and Measure are automatically allowed.
Example:
get_engine_list(num_rows=2, num_columns=3,
one_qubit_gates=(Rz, Ry, Rx, H),
two_qubit_gates=(CNOT,))
Args:
num_rows(int): Number of rows in the grid
num_columns(int): Number of columns in the grid.
one_qubit_gates: "any" allows any one qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. X), it allows all gates which are equal to it. If the gate is
a class (Rz), it allows all instances of this class. Default is "any"
two_qubit_gates: "any" allows any two qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. CNOT), it allows all gates which are equal to it. If the gate
is a class, it allows all instances of this class. Default is (CNOT, Swap).
Raises:
TypeError: If input is for the gates is not "any" or a tuple.
Returns:
A list of suitable compiler engines.
"""
return get_engine_list_linear_grid_base(
GridMapper(num_rows=num_rows, num_columns=num_columns), one_qubit_gates, two_qubit_gates
) |
Return an engine list to compile to a 2-D grid of qubits.
Note:
If you choose a new gate set for which the compiler does not yet have standard rules, it raises an
`NoGateDecompositionError` or a `RuntimeError: maximum recursion depth exceeded...`. Also note that even the
gate sets which work might not yet be optimized. So make sure to double check and potentially extend the
decomposition rules. This implementation currently requires that the one qubit gates must contain Rz and at
least one of {Ry(best), Rx, H} and the two qubit gate must contain CNOT (recommended) or CZ.
Note:
Classical instructions gates such as e.g. Flush and Measure are automatically allowed.
Example:
get_engine_list(num_rows=2, num_columns=3,
one_qubit_gates=(Rz, Ry, Rx, H),
two_qubit_gates=(CNOT,))
Args:
num_rows(int): Number of rows in the grid
num_columns(int): Number of columns in the grid.
one_qubit_gates: "any" allows any one qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. X), it allows all gates which are equal to it. If the gate is
a class (Rz), it allows all instances of this class. Default is "any"
two_qubit_gates: "any" allows any two qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. CNOT), it allows all gates which are equal to it. If the gate
is a class, it allows all instances of this class. Default is (CNOT, Swap).
Raises:
TypeError: If input is for the gates is not "any" or a tuple.
Returns:
A list of suitable compiler engines.
| get_engine_list | python | ProjectQ-Framework/ProjectQ | projectq/setups/grid.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/grid.py | Apache-2.0 |
def get_engine_list(token=None, device=None):
"""Return the default list of compiler engine for the IBM QE platform."""
# Access to the hardware properties via show_devices
# Can also be extended to take into account gate fidelities, new available
# gate, etc..
devices = show_devices(token)
ibm_setup = []
if device not in devices:
raise DeviceOfflineError('Error when configuring engine list: device requested for Backend not connected')
if devices[device]['nq'] == 5:
# The requested device is a 5 qubit processor
# Obtain the coupling map specific to the device
coupling_map = devices[device]['coupling_map']
coupling_map = list2set(coupling_map)
mapper = IBM5QubitMapper(coupling_map)
ibm_setup = [mapper, SwapAndCNOTFlipper(coupling_map), LocalOptimizer(10)]
elif device == 'ibmq_qasm_simulator':
# The 32 qubit online simulator doesn't need a specific mapping for
# gates. Can also run wider gateset but this setup keep the
# restrictedgateset setup for coherence
mapper = BasicMapperEngine()
# Note: Manual Mapper doesn't work, because its map is updated only if
# gates are applied if gates in the register are not used, then it
# will lead to state errors
res = {}
for i in range(devices[device]['nq']):
res[i] = i
mapper.current_mapping = res
ibm_setup = [mapper]
elif device == 'ibmq_16_melbourne':
# Only 15 qubits available on this ibmqx2 unit(in particular qubit 7
# on the grid), therefore need custom grid mapping
grid_to_physical = {
0: 0,
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 15,
8: 14,
9: 13,
10: 12,
11: 11,
12: 10,
13: 9,
14: 8,
15: 7,
}
coupling_map = devices[device]['coupling_map']
coupling_map = list2set(coupling_map)
ibm_setup = [
GridMapper(2, 8, grid_to_physical),
LocalOptimizer(5),
SwapAndCNOTFlipper(coupling_map),
LocalOptimizer(5),
]
else:
# If there is an online device not handled into ProjectQ it's not too
# bad, the engine_list can be constructed manually with the
# appropriate mapper and the 'coupling_map' parameter
raise DeviceNotHandledError('Device not yet fully handled by ProjectQ')
# Most IBM devices accept U1,U2,U3,CX gates.
# Most gates need to be decomposed into a subset that is manually converted
# in the backend (until the implementation of the U1,U2,U3)
# available gates decomposable now for U1,U2,U3: Rx,Ry,Rz and H
setup = restrictedgateset.get_engine_list(
one_qubit_gates=(Rx, Ry, Rz, H), two_qubit_gates=(CNOT,), other_gates=(Barrier,)
)
setup.extend(ibm_setup)
return setup | Return the default list of compiler engine for the IBM QE platform. | get_engine_list | python | ProjectQ-Framework/ProjectQ | projectq/setups/ibm.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/ibm.py | Apache-2.0 |
def get_engine_list(token=None, device=None):
"""Return the default list of compiler engine for the IonQ platform."""
service = IonQ()
if token is not None:
service.authenticate(token=token)
devices = service.show_devices()
if not device or device not in devices:
raise DeviceOfflineError(f"Error checking engine list: no '{device}' devices available")
#
# Qubit mapper
#
mapper = BoundedQubitMapper(devices[device]['nq'])
#
# Basis Gates
#
# Declare the basis gateset for the IonQ's API.
engine_list = restrictedgateset.get_engine_list(
one_qubit_gates=(X, Y, Z, Rx, Ry, Rz, H, S, Sdag, T, Tdag, SqrtX),
two_qubit_gates=(Swap, Rxx, Ryy, Rzz),
other_gates=(Barrier,),
)
return engine_list + [mapper] | Return the default list of compiler engine for the IonQ platform. | get_engine_list | python | ProjectQ-Framework/ProjectQ | projectq/setups/ionq.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/ionq.py | Apache-2.0 |
def get_engine_list(num_qubits, cyclic=False, one_qubit_gates="any", two_qubit_gates=(CNOT, Swap)):
"""
Return an engine list to compile to a linear chain of qubits.
Note:
If you choose a new gate set for which the compiler does not yet have standard rules, it raises an
`NoGateDecompositionError` or a `RuntimeError: maximum recursion depth exceeded...`. Also note that even the
gate sets which work might not yet be optimized. So make sure to double check and potentially extend the
decomposition rules. This implementation currently requires that the one qubit gates must contain Rz and at
least one of {Ry(best), Rx, H} and the two qubit gate must contain CNOT (recommended) or CZ.
Note:
Classical instructions gates such as e.g. Flush and Measure are automatically allowed.
Example:
get_engine_list(num_qubits=10, cyclic=False,
one_qubit_gates=(Rz, Ry, Rx, H),
two_qubit_gates=(CNOT,))
Args:
num_qubits(int): Number of qubits in the chain
cyclic(bool): If a circle or not. Default is False
one_qubit_gates: "any" allows any one qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. X), it allows all gates which are equal to it. If the gate is
a class (Rz), it allows all instances of this class. Default is "any"
two_qubit_gates: "any" allows any two qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. CNOT), it allows all gates which are equal to it. If the gate
is a class, it allows all instances of this class. Default is (CNOT, Swap).
Raises:
TypeError: If input is for the gates is not "any" or a tuple.
Returns:
A list of suitable compiler engines.
"""
return get_engine_list_linear_grid_base(
LinearMapper(num_qubits=num_qubits, cyclic=cyclic), one_qubit_gates, two_qubit_gates
) |
Return an engine list to compile to a linear chain of qubits.
Note:
If you choose a new gate set for which the compiler does not yet have standard rules, it raises an
`NoGateDecompositionError` or a `RuntimeError: maximum recursion depth exceeded...`. Also note that even the
gate sets which work might not yet be optimized. So make sure to double check and potentially extend the
decomposition rules. This implementation currently requires that the one qubit gates must contain Rz and at
least one of {Ry(best), Rx, H} and the two qubit gate must contain CNOT (recommended) or CZ.
Note:
Classical instructions gates such as e.g. Flush and Measure are automatically allowed.
Example:
get_engine_list(num_qubits=10, cyclic=False,
one_qubit_gates=(Rz, Ry, Rx, H),
two_qubit_gates=(CNOT,))
Args:
num_qubits(int): Number of qubits in the chain
cyclic(bool): If a circle or not. Default is False
one_qubit_gates: "any" allows any one qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. X), it allows all gates which are equal to it. If the gate is
a class (Rz), it allows all instances of this class. Default is "any"
two_qubit_gates: "any" allows any two qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. CNOT), it allows all gates which are equal to it. If the gate
is a class, it allows all instances of this class. Default is (CNOT, Swap).
Raises:
TypeError: If input is for the gates is not "any" or a tuple.
Returns:
A list of suitable compiler engines.
| get_engine_list | python | ProjectQ-Framework/ProjectQ | projectq/setups/linear.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/linear.py | Apache-2.0 |
def get_engine_list( # pylint: disable=too-many-branches,too-many-statements
one_qubit_gates="any",
two_qubit_gates=(CNOT,),
other_gates=(),
compiler_chooser=default_chooser,
):
"""
Return an engine list to compile to a restricted gate set.
Note:
If you choose a new gate set for which the compiler does not yet have standard rules, it raises an
`NoGateDecompositionError` or a `RuntimeError: maximum recursion depth exceeded...`. Also note that even the
gate sets which work might not yet be optimized. So make sure to double check and potentially extend the
decomposition rules. This implementation currently requires that the one qubit gates must contain Rz and at
least one of {Ry(best), Rx, H} and the two qubit gate must contain CNOT (recommended) or CZ.
Note:
Classical instructions gates such as e.g. Flush and Measure are automatically allowed.
Example:
get_engine_list(one_qubit_gates=(Rz, Ry, Rx, H),
two_qubit_gates=(CNOT,),
other_gates=(TimeEvolution,))
Args:
one_qubit_gates: "any" allows any one qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. X), it allows all gates which are equal to it. If the gate is
a class (Rz), it allows all instances of this class.
Default is "any"
two_qubit_gates: "any" allows any two qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. CNOT), it allows all gates which are equal to it. If the gate
is a class, it allows all instances of this class.
Default is (CNOT,).
other_gates: A tuple of the allowed gates. If the gates are instances of a class (e.g. QFT), it allows all
gates which are equal to it. If the gate is a class, it allows all instances of this class.
compiler_chooser:function selecting the decomposition to use in the Autoreplacer engine
Raises:
TypeError: If input is for the gates is not "any" or a tuple. Also if element within tuple is not a class or
instance of BasicGate (e.g. CRz which is a shortcut function)
Returns:
A list of suitable compiler engines.
"""
if two_qubit_gates != "any" and not isinstance(two_qubit_gates, tuple):
raise TypeError(
"two_qubit_gates parameter must be 'any' or a tuple. "
"When supplying only one gate, make sure to correctly "
"create the tuple (don't miss the comma), "
"e.g. two_qubit_gates=(CNOT,)"
)
if one_qubit_gates != "any" and not isinstance(one_qubit_gates, tuple):
raise TypeError("one_qubit_gates parameter must be 'any' or a tuple.")
if not isinstance(other_gates, tuple):
raise TypeError("other_gates parameter must be a tuple.")
rule_set = DecompositionRuleSet(modules=[projectq.libs.math, projectq.setups.decompositions])
allowed_gate_classes = [] # n-qubit gates
allowed_gate_instances = []
allowed_gate_classes1 = [] # 1-qubit gates
allowed_gate_instances1 = []
allowed_gate_classes2 = [] # 2-qubit gates
allowed_gate_instances2 = []
if one_qubit_gates != "any":
for gate in one_qubit_gates:
if inspect.isclass(gate):
allowed_gate_classes1.append(gate)
elif isinstance(gate, BasicGate):
allowed_gate_instances1.append(gate)
else:
raise TypeError("unsupported one_qubit_gates argument")
if two_qubit_gates != "any":
for gate in two_qubit_gates:
if inspect.isclass(gate):
# Controlled gate classes don't yet exists and would require
# separate treatment
if isinstance(gate, ControlledGate): # pragma: no cover
raise RuntimeError('Support for controlled gate not implemented!')
allowed_gate_classes2.append(gate)
elif isinstance(gate, BasicGate):
if isinstance(gate, ControlledGate):
allowed_gate_instances2.append((gate._gate, gate._n)) # pylint: disable=protected-access
else:
allowed_gate_instances2.append((gate, 0))
else:
raise TypeError("unsupported two_qubit_gates argument")
for gate in other_gates:
if inspect.isclass(gate):
# Controlled gate classes don't yet exists and would require
# separate treatment
if isinstance(gate, ControlledGate): # pragma: no cover
raise RuntimeError('Support for controlled gate not implemented!')
allowed_gate_classes.append(gate)
elif isinstance(gate, BasicGate):
if isinstance(gate, ControlledGate):
allowed_gate_instances.append((gate._gate, gate._n)) # pylint: disable=protected-access
else:
allowed_gate_instances.append((gate, 0))
else:
raise TypeError("unsupported other_gates argument")
allowed_gate_classes = tuple(allowed_gate_classes)
allowed_gate_instances = tuple(allowed_gate_instances)
allowed_gate_classes1 = tuple(allowed_gate_classes1)
allowed_gate_instances1 = tuple(allowed_gate_instances1)
allowed_gate_classes2 = tuple(allowed_gate_classes2)
allowed_gate_instances2 = tuple(allowed_gate_instances2)
def low_level_gates(eng, cmd): # pylint: disable=unused-argument,too-many-return-statements
all_qubits = [q for qr in cmd.all_qubits for q in qr]
if isinstance(cmd.gate, ClassicalInstructionGate):
# This is required to allow Measure, Allocate, Deallocate, Flush
return True
if one_qubit_gates == "any" and len(all_qubits) == 1:
return True
if two_qubit_gates == "any" and len(all_qubits) == 2:
return True
if isinstance(cmd.gate, allowed_gate_classes):
return True
if (cmd.gate, len(cmd.control_qubits)) in allowed_gate_instances:
return True
if isinstance(cmd.gate, allowed_gate_classes1) and len(all_qubits) == 1:
return True
if isinstance(cmd.gate, allowed_gate_classes2) and len(all_qubits) == 2:
return True
if cmd.gate in allowed_gate_instances1 and len(all_qubits) == 1:
return True
if (cmd.gate, len(cmd.control_qubits)) in allowed_gate_instances2 and len(all_qubits) == 2:
return True
return False
return [
AutoReplacer(rule_set, compiler_chooser),
TagRemover(),
InstructionFilter(high_level_gates),
LocalOptimizer(5),
AutoReplacer(rule_set, compiler_chooser),
TagRemover(),
InstructionFilter(one_and_two_qubit_gates),
LocalOptimizer(5),
AutoReplacer(rule_set, compiler_chooser),
TagRemover(),
InstructionFilter(low_level_gates),
LocalOptimizer(5),
] |
Return an engine list to compile to a restricted gate set.
Note:
If you choose a new gate set for which the compiler does not yet have standard rules, it raises an
`NoGateDecompositionError` or a `RuntimeError: maximum recursion depth exceeded...`. Also note that even the
gate sets which work might not yet be optimized. So make sure to double check and potentially extend the
decomposition rules. This implementation currently requires that the one qubit gates must contain Rz and at
least one of {Ry(best), Rx, H} and the two qubit gate must contain CNOT (recommended) or CZ.
Note:
Classical instructions gates such as e.g. Flush and Measure are automatically allowed.
Example:
get_engine_list(one_qubit_gates=(Rz, Ry, Rx, H),
two_qubit_gates=(CNOT,),
other_gates=(TimeEvolution,))
Args:
one_qubit_gates: "any" allows any one qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. X), it allows all gates which are equal to it. If the gate is
a class (Rz), it allows all instances of this class.
Default is "any"
two_qubit_gates: "any" allows any two qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. CNOT), it allows all gates which are equal to it. If the gate
is a class, it allows all instances of this class.
Default is (CNOT,).
other_gates: A tuple of the allowed gates. If the gates are instances of a class (e.g. QFT), it allows all
gates which are equal to it. If the gate is a class, it allows all instances of this class.
compiler_chooser:function selecting the decomposition to use in the Autoreplacer engine
Raises:
TypeError: If input is for the gates is not "any" or a tuple. Also if element within tuple is not a class or
instance of BasicGate (e.g. CRz which is a shortcut function)
Returns:
A list of suitable compiler engines.
| get_engine_list | python | ProjectQ-Framework/ProjectQ | projectq/setups/restrictedgateset.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/restrictedgateset.py | Apache-2.0 |
def chooser_Ry_reducer(cmd, decomposition_list): # pylint: disable=invalid-name, too-many-return-statements
"""
Choose the decomposition to maximise Ry cancellations.
Choose the decomposition so as to maximise Ry cancellations, based on the previous decomposition used for the
given qubit.
Note:
Classical instructions gates e.g. Flush and Measure are automatically
allowed.
Returns:
A decomposition object from the decomposition_list.
"""
decomp_rule = {}
name = 'default'
for decomp in decomposition_list:
try:
# NB: need to (possibly) raise an exception before setting the
# name variable below
decomposition = decomp.decompose.__name__.split('_')
decomp_rule[decomposition[3]] = decomp
name = decomposition[2]
# 'M' stands for minus, 'P' stands for plus 'N' stands for neutral
# e.g. decomp_rule['M'] will give you the decomposition_rule that
# ends with a Ry(-pi/2)
except IndexError:
pass
local_prev_Ry_sign = prev_Ry_sign.setdefault(cmd.engine, {}) # pylint: disable=invalid-name
if name == 'cnot2rxx':
ctrl_id = cmd.control_qubits[0].id
if local_prev_Ry_sign.get(ctrl_id, -1) <= 0:
# If the previous qubit had Ry(-pi/2) choose the decomposition
# that starts with Ry(pi/2)
local_prev_Ry_sign[ctrl_id] = -1
# Now the prev_Ry_sign is set to -1 since at the end of the
# decomposition we will have a Ry(-pi/2)
return decomp_rule['M']
# Previous qubit had Ry(pi/2) choose decomposition that starts
# with Ry(-pi/2) and ends with R(pi/2)
local_prev_Ry_sign[ctrl_id] = 1
return decomp_rule['P']
if name == 'h2rx':
qubit_id = [qb.id for qureg in cmd.qubits for qb in qureg]
qubit_id = qubit_id[0]
if local_prev_Ry_sign.get(qubit_id, 0) == 0:
local_prev_Ry_sign[qubit_id] = 1
return decomp_rule['M']
local_prev_Ry_sign[qubit_id] = 0
return decomp_rule['N']
if name == 'rz2rx':
qubit_id = [qb.id for qureg in cmd.qubits for qb in qureg]
qubit_id = qubit_id[0]
if local_prev_Ry_sign.get(qubit_id, -1) <= 0:
local_prev_Ry_sign[qubit_id] = -1
return decomp_rule['M']
local_prev_Ry_sign[qubit_id] = 1
return decomp_rule['P']
# No decomposition chosen, so use the first decomposition in the list like the default function
return decomposition_list[0] |
Choose the decomposition to maximise Ry cancellations.
Choose the decomposition so as to maximise Ry cancellations, based on the previous decomposition used for the
given qubit.
Note:
Classical instructions gates e.g. Flush and Measure are automatically
allowed.
Returns:
A decomposition object from the decomposition_list.
| chooser_Ry_reducer | python | ProjectQ-Framework/ProjectQ | projectq/setups/trapped_ion_decomposer.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/trapped_ion_decomposer.py | Apache-2.0 |
def get_engine_list():
"""
Return an engine list compiling code into a trapped ion based compiled circuit code.
Note:
- Classical instructions gates such as e.g. Flush and Measure are automatically allowed.
- The restricted gate set engine does not work with Rxx gates, as ProjectQ will by default bounce back and
forth between Cz gates and Cx gates. An appropriate decomposition chooser needs to be used!
Returns:
A list of suitable compiler engines.
"""
return restrictedgateset.get_engine_list(
one_qubit_gates=(Rx, Ry),
two_qubit_gates=(Rxx,),
compiler_chooser=chooser_Ry_reducer,
) |
Return an engine list compiling code into a trapped ion based compiled circuit code.
Note:
- Classical instructions gates such as e.g. Flush and Measure are automatically allowed.
- The restricted gate set engine does not work with Rxx gates, as ProjectQ will by default bounce back and
forth between Cz gates and Cx gates. An appropriate decomposition chooser needs to be used!
Returns:
A list of suitable compiler engines.
| get_engine_list | python | ProjectQ-Framework/ProjectQ | projectq/setups/trapped_ion_decomposer.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/trapped_ion_decomposer.py | Apache-2.0 |
def get_engine_list_linear_grid_base(mapper, one_qubit_gates="any", two_qubit_gates=(CNOT, Swap)):
"""
Return an engine list to compile to a 2-D grid of qubits.
Note:
If you choose a new gate set for which the compiler does not yet have standard rules, it raises an
`NoGateDecompositionError` or a `RuntimeError: maximum recursion depth exceeded...`. Also note that even the
gate sets which work might not yet be optimized. So make sure to double check and potentially extend the
decomposition rules. This implementation currently requires that the one qubit gates must contain Rz and at
least one of {Ry(best), Rx, H} and the two qubit gate must contain CNOT (recommended) or CZ.
Note:
Classical instructions gates such as e.g. Flush and Measure are automatically allowed.
Example:
get_engine_list(num_rows=2, num_columns=3,
one_qubit_gates=(Rz, Ry, Rx, H),
two_qubit_gates=(CNOT,))
Args:
num_rows(int): Number of rows in the grid
num_columns(int): Number of columns in the grid.
one_qubit_gates: "any" allows any one qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. X), it allows all gates which are equal to it. If the gate is
a class (Rz), it allows all instances of this class. Default is "any"
two_qubit_gates: "any" allows any two qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. CNOT), it allows all gates which are equal to it. If the gate
is a class, it allows all instances of this class. Default is (CNOT, Swap).
Raises:
TypeError: If input is for the gates is not "any" or a tuple.
Returns:
A list of suitable compiler engines.
"""
if two_qubit_gates != "any" and not isinstance(two_qubit_gates, tuple):
raise TypeError(
"two_qubit_gates parameter must be 'any' or a tuple. When supplying only one gate, make sure to"
"correctly create the tuple (don't miss the comma), e.g. two_qubit_gates=(CNOT,)"
)
if one_qubit_gates != "any" and not isinstance(one_qubit_gates, tuple):
raise TypeError("one_qubit_gates parameter must be 'any' or a tuple.")
rule_set = DecompositionRuleSet(modules=[projectq.libs.math, projectq.setups.decompositions])
allowed_gate_classes = []
allowed_gate_instances = []
if one_qubit_gates != "any":
for gate in one_qubit_gates:
if inspect.isclass(gate):
allowed_gate_classes.append(gate)
else:
allowed_gate_instances.append((gate, 0))
if two_qubit_gates != "any":
for gate in two_qubit_gates:
if inspect.isclass(gate):
# Controlled gate classes don't yet exists and would require
# separate treatment
if isinstance(gate, ControlledGate): # pragma: no cover
raise RuntimeError('Support for controlled gate not implemented!')
allowed_gate_classes.append(gate)
else:
if isinstance(gate, ControlledGate):
allowed_gate_instances.append((gate._gate, gate._n)) # pylint: disable=protected-access
else:
allowed_gate_instances.append((gate, 0))
allowed_gate_classes = tuple(allowed_gate_classes)
allowed_gate_instances = tuple(allowed_gate_instances)
def low_level_gates(eng, cmd): # pylint: disable=unused-argument
all_qubits = [q for qr in cmd.all_qubits for q in qr]
if len(all_qubits) > 2: # pragma: no cover
raise ValueError('Filter function cannot handle gates with more than 2 qubits!')
if isinstance(cmd.gate, ClassicalInstructionGate):
# This is required to allow Measure, Allocate, Deallocate, Flush
return True
if one_qubit_gates == "any" and len(all_qubits) == 1:
return True
if two_qubit_gates == "any" and len(all_qubits) == 2:
return True
if isinstance(cmd.gate, allowed_gate_classes):
return True
if (cmd.gate, len(cmd.control_qubits)) in allowed_gate_instances:
return True
return False
return [
AutoReplacer(rule_set),
TagRemover(),
InstructionFilter(high_level_gates),
LocalOptimizer(5),
AutoReplacer(rule_set),
TagRemover(),
InstructionFilter(one_and_two_qubit_gates),
LocalOptimizer(5),
mapper,
AutoReplacer(rule_set),
TagRemover(),
InstructionFilter(low_level_gates),
LocalOptimizer(5),
] |
Return an engine list to compile to a 2-D grid of qubits.
Note:
If you choose a new gate set for which the compiler does not yet have standard rules, it raises an
`NoGateDecompositionError` or a `RuntimeError: maximum recursion depth exceeded...`. Also note that even the
gate sets which work might not yet be optimized. So make sure to double check and potentially extend the
decomposition rules. This implementation currently requires that the one qubit gates must contain Rz and at
least one of {Ry(best), Rx, H} and the two qubit gate must contain CNOT (recommended) or CZ.
Note:
Classical instructions gates such as e.g. Flush and Measure are automatically allowed.
Example:
get_engine_list(num_rows=2, num_columns=3,
one_qubit_gates=(Rz, Ry, Rx, H),
two_qubit_gates=(CNOT,))
Args:
num_rows(int): Number of rows in the grid
num_columns(int): Number of columns in the grid.
one_qubit_gates: "any" allows any one qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. X), it allows all gates which are equal to it. If the gate is
a class (Rz), it allows all instances of this class. Default is "any"
two_qubit_gates: "any" allows any two qubit gate, otherwise provide a tuple of the allowed gates. If the gates
are instances of a class (e.g. CNOT), it allows all gates which are equal to it. If the gate
is a class, it allows all instances of this class. Default is (CNOT, Swap).
Raises:
TypeError: If input is for the gates is not "any" or a tuple.
Returns:
A list of suitable compiler engines.
| get_engine_list_linear_grid_base | python | ProjectQ-Framework/ProjectQ | projectq/setups/_utils.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/_utils.py | Apache-2.0 |
def _decompose_QAA(cmd): # pylint: disable=invalid-name
"""Decompose the Quantum Amplitude Apmplification algorithm as a gate."""
eng = cmd.engine
# System-qubit is the first qubit/qureg. Ancilla qubit is the second qubit
system_qubits = cmd.qubits[0]
qaa_ancilla = cmd.qubits[1]
# The Oracle and the Algorithm
oracle = cmd.gate.oracle
alg = cmd.gate.algorithm
# Apply the oracle to invert the amplitude of the good states, S_Chi
oracle(eng, system_qubits, qaa_ancilla)
# Apply the inversion of the Algorithm,
# the inversion of the amplitude of |0> and the Algorithm
with Compute(eng):
with Dagger(eng):
alg(eng, system_qubits)
All(X) | system_qubits
with Control(eng, system_qubits[0:-1]):
Z | system_qubits[-1]
with CustomUncompute(eng):
All(X) | system_qubits
alg(eng, system_qubits)
Ph(math.pi) | system_qubits[0] | Decompose the Quantum Amplitude Apmplification algorithm as a gate. | _decompose_QAA | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/amplitudeamplification.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/amplitudeamplification.py | Apache-2.0 |
def _recognize_arb1qubit(cmd):
"""
Recognize an arbitrary one qubit gate which has a matrix property.
It does not allow gates which have control qubits as otherwise the
AutoReplacer might go into an infinite loop. Use
carb1qubit2cnotrzandry instead.
"""
try:
return len(cmd.gate.matrix) == 2 and get_control_count(cmd) == 0
except AttributeError:
return False |
Recognize an arbitrary one qubit gate which has a matrix property.
It does not allow gates which have control qubits as otherwise the
AutoReplacer might go into an infinite loop. Use
carb1qubit2cnotrzandry instead.
| _recognize_arb1qubit | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/arb1qubit2rzandry.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/arb1qubit2rzandry.py | Apache-2.0 |
def _test_parameters(matrix, a, b_half, c_half, d_half): # pylint: disable=invalid-name
"""
Build matrix U with parameters (a, b/2, c/2, d/2) and compares against matrix.
U = [[exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)],
[exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]]
Args:
matrix(list): 2x2 matrix
a: parameter of U
b_half: b/2. parameter of U
c_half: c/2. parameter of U
d_half: d/2. parameter of U
Returns:
True if matrix elements of U and `matrix` are TOLERANCE close.
"""
unitary = [
[
cmath.exp(1j * (a - b_half - d_half)) * math.cos(c_half),
-cmath.exp(1j * (a - b_half + d_half)) * math.sin(c_half),
],
[
cmath.exp(1j * (a + b_half - d_half)) * math.sin(c_half),
cmath.exp(1j * (a + b_half + d_half)) * math.cos(c_half),
],
]
return numpy.allclose(unitary, matrix, rtol=10 * TOLERANCE, atol=TOLERANCE) |
Build matrix U with parameters (a, b/2, c/2, d/2) and compares against matrix.
U = [[exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)],
[exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]]
Args:
matrix(list): 2x2 matrix
a: parameter of U
b_half: b/2. parameter of U
c_half: c/2. parameter of U
d_half: d/2. parameter of U
Returns:
True if matrix elements of U and `matrix` are TOLERANCE close.
| _test_parameters | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/arb1qubit2rzandry.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/arb1qubit2rzandry.py | Apache-2.0 |
def _find_parameters(matrix): # pylint: disable=too-many-branches,too-many-statements
"""
Find decomposition parameters.
Given a 2x2 unitary matrix, find the parameters a, b/2, c/2, and d/2 such that
matrix == [[exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)],
[exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]]
Note:
If the matrix is element of SU(2) (determinant == 1), then we can choose a = 0.
Args:
matrix(list): 2x2 unitary matrix
Returns:
parameters of the matrix: (a, b/2, c/2, d/2)
"""
# Determine a, b/2, c/2 and d/2 (3 different cases).
# Note: everything is modulo 2pi.
# Case 1: sin(c/2) == 0:
if abs(matrix[0][1]) < TOLERANCE:
two_a = cmath.phase(matrix[0][0] * matrix[1][1]) % (2 * math.pi)
if abs(two_a) < TOLERANCE or abs(two_a) > 2 * math.pi - TOLERANCE:
# from 2a==0 (mod 2pi), it follows that a==0 or a==pi,
# w.l.g. we can choose a==0 because (see U above)
# c/2 -> c/2 + pi would have the same effect as as a==0 -> a==pi.
a = 0 # pylint: disable=invalid-name
else:
a = two_a / 2.0 # pylint: disable=invalid-name
d_half = 0 # w.l.g
b = cmath.phase(matrix[1][1]) - cmath.phase(matrix[0][0]) # pylint: disable=invalid-name
possible_b_half = [
(b / 2.0) % (2 * math.pi),
(b / 2.0 + math.pi) % (2 * math.pi),
]
# As we have fixed a, we need to find correct sign for cos(c/2)
possible_c_half = [0.0, math.pi]
found = False
for b_half, c_half in itertools.product(possible_b_half, possible_c_half):
if _test_parameters(matrix, a, b_half, c_half, d_half):
found = True
break
if not found:
raise Exception(
"Couldn't find parameters for matrix ",
matrix,
"This shouldn't happen. Maybe the matrix is not unitary?",
)
# Case 2: cos(c/2) == 0:
elif abs(matrix[0][0]) < TOLERANCE:
two_a = cmath.phase(-matrix[0][1] * matrix[1][0]) % (2 * math.pi)
if abs(two_a) < TOLERANCE or abs(two_a) > 2 * math.pi - TOLERANCE:
# from 2a==0 (mod 2pi), it follows that a==0 or a==pi,
# w.l.g. we can choose a==0 because (see U above)
# c/2 -> c/2 + pi would have the same effect as as a==0 -> a==pi.
a = 0 # pylint: disable=invalid-name
else:
a = two_a / 2.0 # pylint: disable=invalid-name
d_half = 0 # w.l.g
b = cmath.phase(matrix[1][0]) - cmath.phase(matrix[0][1]) + math.pi # pylint: disable=invalid-name
possible_b_half = [
(b / 2.0) % (2 * math.pi),
(b / 2.0 + math.pi) % (2 * math.pi),
]
# As we have fixed a, we need to find correct sign for sin(c/2)
possible_c_half = [math.pi / 2.0, 3.0 / 2.0 * math.pi]
found = False
for b_half, c_half in itertools.product(possible_b_half, possible_c_half):
if _test_parameters(matrix, a, b_half, c_half, d_half):
found = True
break
if not found:
raise Exception(
"Couldn't find parameters for matrix ",
matrix,
"This shouldn't happen. Maybe the matrix is not unitary?",
)
# Case 3: sin(c/2) != 0 and cos(c/2) !=0:
else:
two_a = cmath.phase(matrix[0][0] * matrix[1][1]) % (2 * math.pi)
if abs(two_a) < TOLERANCE or abs(two_a) > 2 * math.pi - TOLERANCE:
# from 2a==0 (mod 2pi), it follows that a==0 or a==pi,
# w.l.g. we can choose a==0 because (see U above)
# c/2 -> c/2 + pi would have the same effect as as a==0 -> a==pi.
a = 0 # pylint: disable=invalid-name
else:
a = two_a / 2.0 # pylint: disable=invalid-name
two_d = 2.0 * cmath.phase(matrix[0][1]) - 2.0 * cmath.phase(matrix[0][0])
possible_d_half = [
two_d / 4.0 % (2 * math.pi),
(two_d / 4.0 + math.pi / 2.0) % (2 * math.pi),
(two_d / 4.0 + math.pi) % (2 * math.pi),
(two_d / 4.0 + 3.0 / 2.0 * math.pi) % (2 * math.pi),
]
two_b = 2.0 * cmath.phase(matrix[1][0]) - 2.0 * cmath.phase(matrix[0][0])
possible_b_half = [
two_b / 4.0 % (2 * math.pi),
(two_b / 4.0 + math.pi / 2.0) % (2 * math.pi),
(two_b / 4.0 + math.pi) % (2 * math.pi),
(two_b / 4.0 + 3.0 / 2.0 * math.pi) % (2 * math.pi),
]
tmp = math.acos(abs(matrix[1][1]))
possible_c_half = [
tmp % (2 * math.pi),
(tmp + math.pi) % (2 * math.pi),
(-1.0 * tmp) % (2 * math.pi),
(-1.0 * tmp + math.pi) % (2 * math.pi),
]
found = False
for b_half, c_half, d_half in itertools.product(possible_b_half, possible_c_half, possible_d_half):
if _test_parameters(matrix, a, b_half, c_half, d_half):
found = True
break
if not found:
raise Exception(
"Couldn't find parameters for matrix ",
matrix,
"This shouldn't happen. Maybe the matrix is not unitary?",
)
return (a, b_half, c_half, d_half) |
Find decomposition parameters.
Given a 2x2 unitary matrix, find the parameters a, b/2, c/2, and d/2 such that
matrix == [[exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)],
[exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]]
Note:
If the matrix is element of SU(2) (determinant == 1), then we can choose a = 0.
Args:
matrix(list): 2x2 unitary matrix
Returns:
parameters of the matrix: (a, b/2, c/2, d/2)
| _find_parameters | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/arb1qubit2rzandry.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/arb1qubit2rzandry.py | Apache-2.0 |
def _decompose_arb1qubit(cmd):
"""
Use Z-Y decomposition of Nielsen and Chuang (Theorem 4.1).
An arbitrary one qubit gate matrix can be written as
U = [[exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)],
[exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]]
where a,b,c,d are real numbers.
Then U = exp(j*a) Rz(b) Ry(c) Rz(d).
If the matrix is element of SU(2) (determinant == 1), then
we can choose a = 0.
"""
matrix = cmd.gate.matrix.tolist()
a, b_half, c_half, d_half = _find_parameters(matrix) # pylint: disable=invalid-name
qb = cmd.qubits
eng = cmd.engine
with Control(eng, cmd.control_qubits):
if Rz(2 * d_half) != Rz(0):
Rz(2 * d_half) | qb
if Ry(2 * c_half) != Ry(0):
Ry(2 * c_half) | qb
if Rz(2 * b_half) != Rz(0):
Rz(2 * b_half) | qb
if a != 0:
Ph(a) | qb |
Use Z-Y decomposition of Nielsen and Chuang (Theorem 4.1).
An arbitrary one qubit gate matrix can be written as
U = [[exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)],
[exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]]
where a,b,c,d are real numbers.
Then U = exp(j*a) Rz(b) Ry(c) Rz(d).
If the matrix is element of SU(2) (determinant == 1), then
we can choose a = 0.
| _decompose_arb1qubit | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/arb1qubit2rzandry.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/arb1qubit2rzandry.py | Apache-2.0 |
def create_unitary_matrix(a, b, c, d):
"""
Creates a unitary 2x2 matrix given parameters.
Any unitary 2x2 matrix can be parametrized by:
U = exp(ia) [[exp(j*b) * cos(d), exp(j*c) * sin(d)],
[-exp(-j*c) * sin(d), exp(-j*b) * cos(d)]]
with 0 <= d <= pi/2 and 0 <= a,b,c < 2pi. If a==0, then
det(U) == 1 and hence U is element of SU(2).
Args:
a,b,c (float): parameters 0 <= a,b,c < 2pi
d (float): parameter 0 <= d <= pi/2
Returns:
2x2 matrix as nested lists
"""
ph = exp(1j * a) # global phase
return [
[ph * exp(1j * b) * math.cos(d), ph * exp(1j * c) * math.sin(d)],
[ph * -exp(-1j * c) * math.sin(d), ph * exp(-1j * b) * math.cos(d)],
] |
Creates a unitary 2x2 matrix given parameters.
Any unitary 2x2 matrix can be parametrized by:
U = exp(ia) [[exp(j*b) * cos(d), exp(j*c) * sin(d)],
[-exp(-j*c) * sin(d), exp(-j*b) * cos(d)]]
with 0 <= d <= pi/2 and 0 <= a,b,c < 2pi. If a==0, then
det(U) == 1 and hence U is element of SU(2).
Args:
a,b,c (float): parameters 0 <= a,b,c < 2pi
d (float): parameter 0 <= d <= pi/2
Returns:
2x2 matrix as nested lists
| create_unitary_matrix | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/arb1qubit2rzandry_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/arb1qubit2rzandry_test.py | Apache-2.0 |
def _recognize_carb1qubit(cmd):
"""Recognize single controlled one qubit gates with a matrix."""
if get_control_count(cmd) == 1:
try:
return len(cmd.gate.matrix) == 2
except AttributeError:
return False
return False | Recognize single controlled one qubit gates with a matrix. | _recognize_carb1qubit | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/carb1qubit2cnotrzandry.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/carb1qubit2cnotrzandry.py | Apache-2.0 |
def _test_parameters(matrix, a, b, c_half): # pylint: disable=invalid-name
"""
Build matrix V with parameters (a, b, c/2) and compares against matrix.
V = [[-sin(c/2) * exp(j*a), exp(j*(a-b)) * cos(c/2)],
[exp(j*(a+b)) * cos(c/2), exp(j*a) * sin(c/2)]]
Args:
matrix(list): 2x2 matrix
a: Parameter of V
b: Parameter of V
c_half: c/2. Parameter of V
Returns:
True if matrix elements of V and `matrix` are TOLERANCE close.
"""
v_matrix = [
[
-math.sin(c_half) * cmath.exp(1j * a),
cmath.exp(1j * (a - b)) * math.cos(c_half),
],
[
cmath.exp(1j * (a + b)) * math.cos(c_half),
cmath.exp(1j * a) * math.sin(c_half),
],
]
return numpy.allclose(v_matrix, matrix, rtol=10 * TOLERANCE, atol=TOLERANCE) |
Build matrix V with parameters (a, b, c/2) and compares against matrix.
V = [[-sin(c/2) * exp(j*a), exp(j*(a-b)) * cos(c/2)],
[exp(j*(a+b)) * cos(c/2), exp(j*a) * sin(c/2)]]
Args:
matrix(list): 2x2 matrix
a: Parameter of V
b: Parameter of V
c_half: c/2. Parameter of V
Returns:
True if matrix elements of V and `matrix` are TOLERANCE close.
| _test_parameters | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/carb1qubit2cnotrzandry.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/carb1qubit2cnotrzandry.py | Apache-2.0 |
def _recognize_v(matrix): # pylint: disable=too-many-branches
"""
Test whether a matrix has the correct form.
Recognize a matrix which can be written in the following form:
V = [[-sin(c/2) * exp(j*a), exp(j*(a-b)) * cos(c/2)],
[exp(j*(a+b)) * cos(c/2), exp(j*a) * sin(c/2)]]
Args:
matrix(list): 2x2 matrix
Returns:
False if it is not possible otherwise (a, b, c/2)
"""
if abs(matrix[0][0]) < TOLERANCE:
two_a = cmath.phase(matrix[0][1] * matrix[1][0]) % (2 * math.pi)
if abs(two_a) < TOLERANCE or abs(two_a) > 2 * math.pi - TOLERANCE:
# from 2a==0 (mod 2pi), it follows that a==0 or a==pi,
# w.l.g. we can choose a==0 because (see U above)
# c/2 -> c/2 + pi would have the same effect as as a==0 -> a==pi.
a = 0 # pylint: disable=invalid-name
else:
a = two_a / 2.0 # pylint: disable=invalid-name
two_b = cmath.phase(matrix[1][0]) - cmath.phase(matrix[0][1])
possible_b = [
(two_b / 2.0) % (2 * math.pi),
(two_b / 2.0 + math.pi) % (2 * math.pi),
]
possible_c_half = [0, math.pi]
for b, c_half in itertools.product(possible_b, possible_c_half): # pylint: disable=invalid-name
if _test_parameters(matrix, a, b, c_half):
return (a, b, c_half)
raise RuntimeError('Case matrix[0][0]==0 should work in all cases, but did not!') # pragma: no cover
if abs(matrix[0][1]) < TOLERANCE:
two_a = cmath.phase(-matrix[0][0] * matrix[1][1]) % (2 * math.pi)
if abs(two_a) < TOLERANCE or abs(two_a) > 2 * math.pi - TOLERANCE:
# from 2a==0 (mod 2pi), it follows that a==0 or a==pi,
# w.l.g. we can choose a==0 because (see U above)
# c/2 -> c/2 + pi would have the same effect as as a==0 -> a==pi.
a = 0 # pylint: disable=invalid-name
else:
a = two_a / 2.0 # pylint: disable=invalid-name
b = 0 # pylint: disable=invalid-name
possible_c_half = [math.pi / 2.0, 3.0 / 2.0 * math.pi]
for c_half in possible_c_half:
if _test_parameters(matrix, a, b, c_half):
return (a, b, c_half)
return False
two_a = cmath.phase(-1.0 * matrix[0][0] * matrix[1][1]) % (2 * math.pi)
if abs(two_a) < TOLERANCE or abs(two_a) > 2 * math.pi - TOLERANCE:
# from 2a==0 (mod 2pi), it follows that a==0 or a==pi,
# w.l.g. we can choose a==0 because (see U above)
# c/2 -> c/2 + pi would have the same effect as as a==0 -> a==pi.
a = 0 # pylint: disable=invalid-name
else:
a = two_a / 2.0 # pylint: disable=invalid-name
two_b = cmath.phase(matrix[1][0]) - cmath.phase(matrix[0][1])
possible_b = [
(two_b / 2.0) % (2 * math.pi),
(two_b / 2.0 + math.pi) % (2 * math.pi),
]
tmp = math.acos(abs(matrix[1][0]))
possible_c_half = [
tmp % (2 * math.pi),
(tmp + math.pi) % (2 * math.pi),
(-1.0 * tmp) % (2 * math.pi),
(-1.0 * tmp + math.pi) % (2 * math.pi),
]
for b, c_half in itertools.product(possible_b, possible_c_half): # pylint: disable=invalid-name
if _test_parameters(matrix, a, b, c_half):
return (a, b, c_half)
return False |
Test whether a matrix has the correct form.
Recognize a matrix which can be written in the following form:
V = [[-sin(c/2) * exp(j*a), exp(j*(a-b)) * cos(c/2)],
[exp(j*(a+b)) * cos(c/2), exp(j*a) * sin(c/2)]]
Args:
matrix(list): 2x2 matrix
Returns:
False if it is not possible otherwise (a, b, c/2)
| _recognize_v | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/carb1qubit2cnotrzandry.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/carb1qubit2cnotrzandry.py | Apache-2.0 |
def _decompose_carb1qubit(cmd): # pylint: disable=too-many-branches
"""
Decompose the single controlled 1 qubit gate into CNOT, Rz, Ry, C(Ph).
See Nielsen and Chuang chapter 4.3.
An arbitrary one qubit gate matrix can be written as
U = [[exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)],
[exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]]
where a,b,c,d are real numbers.
Then U = exp(j*a) Rz(b) Ry(c) Rz(d).
Then C(U) = C(exp(ja)) * A * CNOT * B * CNOT * C with
A = Rz(b) * Ry(c/2)
B = Ry(-c/2) * Rz(-(d+b)/2)
C = Rz((d-b)/2)
Note that a == 0 if U is element of SU(2). Also note that
the controlled phase C(exp(ia)) can be implemented with single
qubit gates.
If the one qubit gate matrix can be written as
V = [[-sin(c/2) * exp(j*a), exp(j*(a-b)) * cos(c/2)],
[exp(j*(a+b)) * cos(c/2), exp(j*a) * sin(c/2)]]
Then C(V) = C(exp(ja))* E * CNOT * D with
E = Rz(b)Ry(c/2)
D = Ry(-c/2)Rz(-b)
This improvement is important for C(Y) or C(Z)
For a proof follow Lemma 5.5 of Barenco et al.
"""
matrix = cmd.gate.matrix.tolist()
qb = cmd.qubits
eng = cmd.engine
# Case 1: Unitary matrix which can be written in the form of V:
parameters_for_v = _recognize_v(matrix)
if parameters_for_v:
a, b, c_half = parameters_for_v # pylint: disable=invalid-name
if Rz(-b) != Rz(0):
Rz(-b) | qb
if Ry(-c_half) != Ry(0):
Ry(-c_half) | qb
with Control(eng, cmd.control_qubits):
X | qb
if Ry(c_half) != Ry(0):
Ry(c_half) | qb
if Rz(b) != Rz(0):
Rz(b) | qb
if a != 0:
with Control(eng, cmd.control_qubits):
Ph(a) | qb
# Case 2: General matrix U:
else:
a, b_half, c_half, d_half = arb1q._find_parameters(matrix) # pylint: disable=invalid-name, protected-access
d = 2 * d_half # pylint: disable=invalid-name
b = 2 * b_half # pylint: disable=invalid-name
if Rz((d - b) / 2.0) != Rz(0):
Rz((d - b) / 2.0) | qb
with Control(eng, cmd.control_qubits):
X | qb
if Rz(-(d + b) / 2.0) != Rz(0):
Rz(-(d + b) / 2.0) | qb
if Ry(-c_half) != Ry(0):
Ry(-c_half) | qb
with Control(eng, cmd.control_qubits):
X | qb
if Ry(c_half) != Ry(0):
Ry(c_half) | qb
if Rz(b) != Rz(0):
Rz(b) | qb
if a != 0:
with Control(eng, cmd.control_qubits):
Ph(a) | qb |
Decompose the single controlled 1 qubit gate into CNOT, Rz, Ry, C(Ph).
See Nielsen and Chuang chapter 4.3.
An arbitrary one qubit gate matrix can be written as
U = [[exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)],
[exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]]
where a,b,c,d are real numbers.
Then U = exp(j*a) Rz(b) Ry(c) Rz(d).
Then C(U) = C(exp(ja)) * A * CNOT * B * CNOT * C with
A = Rz(b) * Ry(c/2)
B = Ry(-c/2) * Rz(-(d+b)/2)
C = Rz((d-b)/2)
Note that a == 0 if U is element of SU(2). Also note that
the controlled phase C(exp(ia)) can be implemented with single
qubit gates.
If the one qubit gate matrix can be written as
V = [[-sin(c/2) * exp(j*a), exp(j*(a-b)) * cos(c/2)],
[exp(j*(a+b)) * cos(c/2), exp(j*a) * sin(c/2)]]
Then C(V) = C(exp(ja))* E * CNOT * D with
E = Rz(b)Ry(c/2)
D = Ry(-c/2)Rz(-b)
This improvement is important for C(Y) or C(Z)
For a proof follow Lemma 5.5 of Barenco et al.
| _decompose_carb1qubit | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/carb1qubit2cnotrzandry.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/carb1qubit2cnotrzandry.py | Apache-2.0 |
def _decompose_cnot2rxx_M(cmd): # pylint: disable=invalid-name
"""Decompose CNOT gate into Rxx gate."""
# Labelled 'M' for 'minus' because decomposition ends with a Ry(-pi/2)
ctrl = cmd.control_qubits
Ry(math.pi / 2) | ctrl[0]
Ph(7 * math.pi / 4) | ctrl[0]
Rx(-math.pi / 2) | ctrl[0]
Rx(-math.pi / 2) | cmd.qubits[0][0]
Rxx(math.pi / 2) | (ctrl[0], cmd.qubits[0][0])
Ry(-1 * math.pi / 2) | ctrl[0] | Decompose CNOT gate into Rxx gate. | _decompose_cnot2rxx_M | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/cnot2rxx.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/cnot2rxx.py | Apache-2.0 |
def _decompose_cnot2rxx_P(cmd): # pylint: disable=invalid-name
"""Decompose CNOT gate into Rxx gate."""
# Labelled 'P' for 'plus' because decomposition ends with a Ry(+pi/2)
ctrl = cmd.control_qubits
Ry(-math.pi / 2) | ctrl[0]
Ph(math.pi / 4) | ctrl[0]
Rx(-math.pi / 2) | ctrl[0]
Rx(math.pi / 2) | cmd.qubits[0][0]
Rxx(math.pi / 2) | (ctrl[0], cmd.qubits[0][0])
Ry(math.pi / 2) | ctrl[0] | Decompose CNOT gate into Rxx gate. | _decompose_cnot2rxx_P | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/cnot2rxx.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/cnot2rxx.py | Apache-2.0 |
def _decomp_gates(eng, cmd):
"""Test that the cmd.gate is a gate of class X"""
if len(cmd.control_qubits) == 1 and isinstance(cmd.gate, X.__class__):
return False
return True | Test that the cmd.gate is a gate of class X | _decomp_gates | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/cnot2rxx_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/cnot2rxx_test.py | Apache-2.0 |
def test_decomposition():
"""Test that this decomposition of CNOT produces correct amplitudes
Function tests each DecompositionRule in
cnot2rxx.all_defined_decomposition_rules
"""
decomposition_rule_list = cnot2rxx.all_defined_decomposition_rules
for rule in decomposition_rule_list:
for basis_state_index in range(0, 4):
basis_state = [0] * 4
basis_state[basis_state_index] = 1.0
correct_dummy_eng = DummyEngine(save_commands=True)
correct_eng = MainEngine(backend=Simulator(), engine_list=[correct_dummy_eng])
rule_set = DecompositionRuleSet(rules=[rule])
test_dummy_eng = DummyEngine(save_commands=True)
test_eng = MainEngine(
backend=Simulator(),
engine_list=[
AutoReplacer(rule_set),
InstructionFilter(_decomp_gates),
test_dummy_eng,
],
)
test_sim = test_eng.backend
correct_sim = correct_eng.backend
correct_qb = correct_eng.allocate_qubit()
correct_ctrl_qb = correct_eng.allocate_qubit()
correct_eng.flush()
test_qb = test_eng.allocate_qubit()
test_ctrl_qb = test_eng.allocate_qubit()
test_eng.flush()
correct_sim.set_wavefunction(basis_state, correct_qb + correct_ctrl_qb)
test_sim.set_wavefunction(basis_state, test_qb + test_ctrl_qb)
CNOT | (test_ctrl_qb, test_qb)
CNOT | (correct_ctrl_qb, correct_qb)
test_eng.flush()
correct_eng.flush()
assert len(correct_dummy_eng.received_commands) == 5
assert len(test_dummy_eng.received_commands) == 10
assert correct_eng.backend.cheat()[1] == pytest.approx(test_eng.backend.cheat()[1], rel=1e-12, abs=1e-12)
All(Measure) | test_qb + test_ctrl_qb
All(Measure) | correct_qb + correct_ctrl_qb
test_eng.flush(deallocate_qubits=True)
correct_eng.flush(deallocate_qubits=True) | Test that this decomposition of CNOT produces correct amplitudes
Function tests each DecompositionRule in
cnot2rxx.all_defined_decomposition_rules
| test_decomposition | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/cnot2rxx_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/cnot2rxx_test.py | Apache-2.0 |
def _recognize_CnU(cmd): # pylint: disable=invalid-name
"""Recognize an arbitrary gate which has n>=2 control qubits, except a Toffoli gate."""
if get_control_count(cmd) == 2:
if not isinstance(cmd.gate, XGate):
return True
elif get_control_count(cmd) > 2:
return True
return False | Recognize an arbitrary gate which has n>=2 control qubits, except a Toffoli gate. | _recognize_CnU | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/cnu2toffoliandcu.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/cnu2toffoliandcu.py | Apache-2.0 |
def _decompose_CnU(cmd): # pylint: disable=invalid-name
"""
Decompose a multi-controlled gate U with n control qubits into a single- controlled U.
It uses (n-1) work qubits and 2 * (n-1) Toffoli gates for general U and (n-2) work qubits and 2n - 3 Toffoli gates
if U is an X-gate.
"""
eng = cmd.engine
qubits = cmd.qubits
ctrl_qureg = cmd.control_qubits
gate = cmd.gate
n_controls = get_control_count(cmd)
# specialized for X-gate
if gate == XGate() and n_controls > 2:
n_controls -= 1
ancilla_qureg = eng.allocate_qureg(n_controls - 1)
with Compute(eng):
Toffoli | (ctrl_qureg[0], ctrl_qureg[1], ancilla_qureg[0])
for ctrl_index in range(2, n_controls):
Toffoli | (
ctrl_qureg[ctrl_index],
ancilla_qureg[ctrl_index - 2],
ancilla_qureg[ctrl_index - 1],
)
ctrls = [ancilla_qureg[-1]]
# specialized for X-gate
if gate == XGate() and get_control_count(cmd) > 2:
ctrls += [ctrl_qureg[-1]]
with Control(eng, ctrls):
gate | qubits
Uncompute(eng) |
Decompose a multi-controlled gate U with n control qubits into a single- controlled U.
It uses (n-1) work qubits and 2 * (n-1) Toffoli gates for general U and (n-2) work qubits and 2n - 3 Toffoli gates
if U is an X-gate.
| _decompose_CnU | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/cnu2toffoliandcu.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/cnu2toffoliandcu.py | Apache-2.0 |
def _decompose_controlstate(cmd):
"""Decompose commands with control qubits in negative state (ie. control qubits with state '0' instead of '1')."""
with Compute(cmd.engine):
for state, ctrl in zip(cmd.control_state, cmd.control_qubits):
if state == '0':
X | ctrl
# Resend the command with the `control_state` cleared
cmd.ctrl_state = '1' * len(cmd.control_state)
orig_engine = cmd.engine
cmd.engine.receive([deepcopy(cmd)]) # NB: deepcopy required here to workaround infinite recursion detection
Uncompute(orig_engine) | Decompose commands with control qubits in negative state (ie. control qubits with state '0' instead of '1'). | _decompose_controlstate | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/controlstate.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/controlstate.py | Apache-2.0 |
def _decompose_CRz(cmd): # pylint: disable=invalid-name
"""Decompose the controlled Rz gate (into CNOT and Rz)."""
qubit = cmd.qubits[0]
ctrl = cmd.control_qubits
gate = cmd.gate
n_controls = get_control_count(cmd)
Rz(0.5 * gate.angle) | qubit
C(NOT, n_controls) | (ctrl, qubit)
Rz(-0.5 * gate.angle) | qubit
C(NOT, n_controls) | (ctrl, qubit) | Decompose the controlled Rz gate (into CNOT and Rz). | _decompose_CRz | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/crz2cxandrz.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/crz2cxandrz.py | Apache-2.0 |
def h_decomp_gates(eng, cmd):
"""Test that cmd.gate is a gate of class HGate"""
g = cmd.gate
if isinstance(g, HGate): # H is just a shortcut to HGate
return False
else:
return True | Test that cmd.gate is a gate of class HGate | h_decomp_gates | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/h2rx_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/h2rx_test.py | Apache-2.0 |
def test_decomposition():
"""Test that this decomposition of H produces correct amplitudes
Function tests each DecompositionRule in
h2rx.all_defined_decomposition_rules
"""
decomposition_rule_list = h2rx.all_defined_decomposition_rules
for rule in decomposition_rule_list:
for basis_state_index in range(2):
basis_state = [0] * 2
basis_state[basis_state_index] = 1.0
correct_dummy_eng = DummyEngine(save_commands=True)
correct_eng = MainEngine(backend=Simulator(), engine_list=[correct_dummy_eng])
rule_set = DecompositionRuleSet(rules=[rule])
test_dummy_eng = DummyEngine(save_commands=True)
test_eng = MainEngine(
backend=Simulator(),
engine_list=[
AutoReplacer(rule_set),
InstructionFilter(h_decomp_gates),
test_dummy_eng,
],
)
correct_qb = correct_eng.allocate_qubit()
correct_eng.flush()
test_qb = test_eng.allocate_qubit()
test_eng.flush()
correct_eng.backend.set_wavefunction(basis_state, correct_qb)
test_eng.backend.set_wavefunction(basis_state, test_qb)
H | correct_qb
H | test_qb
correct_eng.flush()
test_eng.flush()
assert H in (cmd.gate for cmd in correct_dummy_eng.received_commands)
assert H not in (cmd.gate for cmd in test_dummy_eng.received_commands)
assert correct_eng.backend.cheat()[1] == pytest.approx(test_eng.backend.cheat()[1], rel=1e-12, abs=1e-12)
Measure | test_qb
Measure | correct_qb | Test that this decomposition of H produces correct amplitudes
Function tests each DecompositionRule in
h2rx.all_defined_decomposition_rules
| test_decomposition | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/h2rx_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/h2rx_test.py | Apache-2.0 |
def _decompose_Ph(cmd): # pylint: disable=invalid-name
"""Decompose the controlled phase gate (C^nPh(phase))."""
ctrl = cmd.control_qubits
gate = cmd.gate
eng = cmd.engine
with Control(eng, ctrl[1:]):
R(gate.angle) | ctrl[0] | Decompose the controlled phase gate (C^nPh(phase)). | _decompose_Ph | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/ph2r.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/ph2r.py | Apache-2.0 |
def _decompose_QPE(cmd): # pylint: disable=invalid-name
"""Decompose the Quantum Phase Estimation gate."""
eng = cmd.engine
# Ancillas is the first qubit/qureg. System-qubit is the second qubit/qureg
qpe_ancillas = cmd.qubits[0]
system_qubits = cmd.qubits[1]
# Hadamard on the ancillas
Tensor(H) | qpe_ancillas
# The Unitary Operator
unitary = cmd.gate.unitary
# Control U on the system_qubits
if callable(unitary):
# If U is a function
for i, ancilla in enumerate(qpe_ancillas):
with Control(eng, ancilla):
unitary(system_qubits, time=2**i)
else:
for i, ancilla in enumerate(qpe_ancillas):
ipower = int(2**i)
with Loop(eng, ipower):
with Control(eng, ancilla):
unitary | system_qubits
# Inverse QFT on the ancillas
get_inverse(QFT) | qpe_ancillas | Decompose the Quantum Phase Estimation gate. | _decompose_QPE | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/phaseestimation.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/phaseestimation.py | Apache-2.0 |
def _decompose_R(cmd): # pylint: disable=invalid-name
"""Decompose the (controlled) phase-shift gate, denoted by R(phase)."""
ctrl = cmd.control_qubits
eng = cmd.engine
gate = cmd.gate
with Control(eng, ctrl):
Ph(0.5 * gate.angle) | cmd.qubits
Rz(gate.angle) | cmd.qubits | Decompose the (controlled) phase-shift gate, denoted by R(phase). | _decompose_R | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/r2rzandph.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/r2rzandph.py | Apache-2.0 |
def _decompose_rz2rx_P(cmd): # pylint: disable=invalid-name
"""Decompose the Rz using negative angle."""
# Labelled 'P' for 'plus' because decomposition ends with a Ry(+pi/2)
qubit = cmd.qubits[0]
eng = cmd.engine
angle = cmd.gate.angle
with Control(eng, cmd.control_qubits):
with Compute(eng):
Ry(-math.pi / 2.0) | qubit
Rx(-angle) | qubit
Uncompute(eng) | Decompose the Rz using negative angle. | _decompose_rz2rx_P | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/rz2rx.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/rz2rx.py | Apache-2.0 |
def _decompose_rz2rx_M(cmd): # pylint: disable=invalid-name
"""Decompose the Rz using positive angle."""
# Labelled 'M' for 'minus' because decomposition ends with a Ry(-pi/2)
qubit = cmd.qubits[0]
eng = cmd.engine
angle = cmd.gate.angle
with Control(eng, cmd.control_qubits):
with Compute(eng):
Ry(math.pi / 2.0) | qubit
Rx(angle) | qubit
Uncompute(eng) | Decompose the Rz using positive angle. | _decompose_rz2rx_M | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/rz2rx.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/rz2rx.py | Apache-2.0 |
def rz_decomp_gates(eng, cmd):
"""Test that cmd.gate is the gate Rz"""
g = cmd.gate
if isinstance(g, Rz):
return False
else:
return True | Test that cmd.gate is the gate Rz | rz_decomp_gates | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/rz2rx_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/rz2rx_test.py | Apache-2.0 |
def test_decomposition(angle):
"""
Test that this decomposition of Rz produces correct amplitudes
Note that this function tests each DecompositionRule in
rz2rx.all_defined_decomposition_rules
"""
decomposition_rule_list = rz2rx.all_defined_decomposition_rules
for rule in decomposition_rule_list:
for basis_state in ([1, 0], [0, 1]):
correct_dummy_eng = DummyEngine(save_commands=True)
correct_eng = MainEngine(backend=Simulator(), engine_list=[correct_dummy_eng])
rule_set = DecompositionRuleSet(rules=[rule])
test_dummy_eng = DummyEngine(save_commands=True)
test_eng = MainEngine(
backend=Simulator(),
engine_list=[
AutoReplacer(rule_set),
InstructionFilter(rz_decomp_gates),
test_dummy_eng,
],
)
correct_qb = correct_eng.allocate_qubit()
Rz(angle) | correct_qb
correct_eng.flush()
test_qb = test_eng.allocate_qubit()
Rz(angle) | test_qb
test_eng.flush()
# Create empty vectors for the wave vectors for the correct and
# test qubits
correct_vector = np.zeros((2, 1), dtype=np.complex_)
test_vector = np.zeros((2, 1), dtype=np.complex_)
i = 0
for fstate in ['0', '1']:
test = test_eng.backend.get_amplitude(fstate, test_qb)
correct = correct_eng.backend.get_amplitude(fstate, correct_qb)
correct_vector[i] = correct
test_vector[i] = test
i += 1
# Necessary to transpose vector to use matrix dot product
test_vector = test_vector.transpose()
# Remember that transposed vector should come first in product
vector_dot_product = np.dot(test_vector, correct_vector)
assert np.absolute(vector_dot_product) == pytest.approx(1, rel=1e-12, abs=1e-12)
Measure | test_qb
Measure | correct_qb |
Test that this decomposition of Rz produces correct amplitudes
Note that this function tests each DecompositionRule in
rz2rx.all_defined_decomposition_rules
| test_decomposition | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/rz2rx_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/rz2rx_test.py | Apache-2.0 |
def _decompose_state_preparation(cmd): # pylint: disable=too-many-locals
"""Implement state preparation based on arXiv:quant-ph/0407010v1."""
eng = cmd.engine
if len(cmd.qubits) != 1:
raise ValueError('StatePreparation does not support multiple quantum registers!')
num_qubits = len(cmd.qubits[0])
qureg = cmd.qubits[0]
final_state = cmd.gate.final_state
if len(final_state) != 2**num_qubits:
raise ValueError("Length of final_state is invalid.")
norm = 0.0
for amplitude in final_state:
norm += abs(amplitude) ** 2
if norm < 1 - 1e-10 or norm > 1 + 1e-10:
raise ValueError("final_state is not normalized.")
with Control(eng, cmd.control_qubits):
# As in the paper reference, we implement the inverse:
with Dagger(eng):
# Cancel all the relative phases
phase_of_blocks = []
for amplitude in final_state:
phase_of_blocks.append(cmath.phase(amplitude))
for qubit_idx, qubit in enumerate(qureg):
angles = []
phase_of_next_blocks = []
for block in range(2 ** (len(qureg) - qubit_idx - 1)):
phase0 = phase_of_blocks[2 * block]
phase1 = phase_of_blocks[2 * block + 1]
angles.append(phase0 - phase1)
phase_of_next_blocks.append((phase0 + phase1) / 2.0)
UniformlyControlledRz(angles) | (
qureg[(qubit_idx + 1) :], # noqa: E203
qubit,
)
phase_of_blocks = phase_of_next_blocks
# Cancel global phase
Ph(-phase_of_blocks[0]) | qureg[-1]
# Remove amplitudes from states which contain a bit value 1:
abs_of_blocks = []
for amplitude in final_state:
abs_of_blocks.append(abs(amplitude))
for qubit_idx, qubit in enumerate(qureg):
angles = []
abs_of_next_blocks = []
for block in range(2 ** (len(qureg) - qubit_idx - 1)):
a0 = abs_of_blocks[2 * block] # pylint: disable=invalid-name
a1 = abs_of_blocks[2 * block + 1] # pylint: disable=invalid-name
if a0 == 0 and a1 == 0:
angles.append(0)
else:
angles.append(-2.0 * math.acos(a0 / math.sqrt(a0**2 + a1**2)))
abs_of_next_blocks.append(math.sqrt(a0**2 + a1**2))
UniformlyControlledRy(angles) | (
qureg[(qubit_idx + 1) :], # noqa: E203
qubit,
)
abs_of_blocks = abs_of_next_blocks | Implement state preparation based on arXiv:quant-ph/0407010v1. | _decompose_state_preparation | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/stateprep2cnot.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/stateprep2cnot.py | Apache-2.0 |
def _recognize_time_evolution_commuting_terms(cmd):
"""Recognize all TimeEvolution gates with >1 terms but which all commute."""
hamiltonian = cmd.gate.hamiltonian
if len(hamiltonian.terms) == 1:
return False
id_op = QubitOperator((), 0.0)
for term in hamiltonian.terms:
test_op = QubitOperator(term, hamiltonian.terms[term])
for other in hamiltonian.terms:
other_op = QubitOperator(other, hamiltonian.terms[other])
commutator = test_op * other_op - other_op * test_op
if not commutator.isclose(id_op, rel_tol=1e-9, abs_tol=1e-9):
return False
return True | Recognize all TimeEvolution gates with >1 terms but which all commute. | _recognize_time_evolution_commuting_terms | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/time_evolution.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/time_evolution.py | Apache-2.0 |
def _decompose_time_evolution_individual_terms(cmd): # pylint: disable=too-many-branches
"""
Implement a TimeEvolution gate with a hamiltonian having only one term.
To implement exp(-i * t * hamiltonian), where the hamiltonian is only one
term, e.g., hamiltonian = X0 x Y1 X Z2, we first perform local
transformations to in order that all Pauli operators in the hamiltonian
are Z. We then implement exp(-i * t * (Z1 x Z2 x Z3) and transform the
basis back to the original. For more details see, e.g.,
James D. Whitfield, Jacob Biamonte & Aspuru-Guzik
Simulation of electronic structure Hamiltonians using quantum computers,
Molecular Physics, 109:5, 735-750 (2011).
or
Nielsen and Chuang, Quantum Computation and Information.
"""
if len(cmd.qubits) != 1:
raise ValueError('TimeEvolution gate can only accept a single quantum register')
qureg = cmd.qubits[0]
eng = cmd.engine
time = cmd.gate.time
hamiltonian = cmd.gate.hamiltonian
if len(hamiltonian.terms) != 1:
raise ValueError('This decomposition function only accepts single-term hamiltonians!')
term = list(hamiltonian.terms)[0]
coefficient = hamiltonian.terms[term]
check_indices = set()
# Check that hamiltonian is not identity term,
# Previous __or__ operator should have apply a global phase instead:
if term == ():
raise ValueError('This decomposition function cannot accept a hamiltonian with an empty term!')
# hamiltonian has only a single local operator
if len(term) == 1:
with Control(eng, cmd.control_qubits):
if term[0][1] == 'X':
Rx(time * coefficient * 2.0) | qureg[term[0][0]]
elif term[0][1] == 'Y':
Ry(time * coefficient * 2.0) | qureg[term[0][0]]
else:
Rz(time * coefficient * 2.0) | qureg[term[0][0]]
# hamiltonian has more than one local operator
else:
with Control(eng, cmd.control_qubits):
with Compute(eng):
# Apply local basis rotations
for index, action in term:
check_indices.add(index)
if action == 'X':
H | qureg[index]
elif action == 'Y':
Rx(math.pi / 2.0) | qureg[index]
print(check_indices, set(range(len(qureg))))
# Check that qureg had exactly as many qubits as indices:
if check_indices != set(range(len(qureg))):
raise ValueError('Indices mismatch between hamiltonian terms and qubits')
# Compute parity
for i in range(len(qureg) - 1):
CNOT | (qureg[i], qureg[i + 1])
Rz(time * coefficient * 2.0) | qureg[-1]
# Uncompute parity and basis change
Uncompute(eng) |
Implement a TimeEvolution gate with a hamiltonian having only one term.
To implement exp(-i * t * hamiltonian), where the hamiltonian is only one
term, e.g., hamiltonian = X0 x Y1 X Z2, we first perform local
transformations to in order that all Pauli operators in the hamiltonian
are Z. We then implement exp(-i * t * (Z1 x Z2 x Z3) and transform the
basis back to the original. For more details see, e.g.,
James D. Whitfield, Jacob Biamonte & Aspuru-Guzik
Simulation of electronic structure Hamiltonians using quantum computers,
Molecular Physics, 109:5, 735-750 (2011).
or
Nielsen and Chuang, Quantum Computation and Information.
| _decompose_time_evolution_individual_terms | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/time_evolution.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/time_evolution.py | Apache-2.0 |
def _decompose_toffoli(cmd):
"""Decompose the Toffoli gate into CNOT, H, T, and Tdagger gates."""
ctrl = cmd.control_qubits
target = cmd.qubits[0]
H | target
CNOT | (ctrl[0], target)
T | ctrl[0]
Tdag | target
CNOT | (ctrl[1], target)
CNOT | (ctrl[1], ctrl[0])
Tdag | ctrl[0]
T | target
CNOT | (ctrl[1], ctrl[0])
CNOT | (ctrl[0], target)
Tdag | target
CNOT | (ctrl[1], target)
T | target
T | ctrl[1]
H | target | Decompose the Toffoli gate into CNOT, H, T, and Tdagger gates. | _decompose_toffoli | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/toffoli2cnotandtgate.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/toffoli2cnotandtgate.py | Apache-2.0 |
def _decompose_ucr(cmd, gate_class):
"""
Decomposition for an uniformly controlled single qubit rotation gate.
Follows decomposition in arXiv:quant-ph/0407010 section II and
arXiv:quant-ph/0410066v2 Fig. 9a.
For Ry and Rz it uses 2**len(ucontrol_qubits) CNOT and also
2**len(ucontrol_qubits) single qubit rotations.
Args:
cmd: CommandObject to decompose.
gate_class: Ry or Rz
"""
eng = cmd.engine
with Control(eng, cmd.control_qubits):
if not (len(cmd.qubits) == 2 and len(cmd.qubits[1]) == 1):
raise TypeError("Wrong number of qubits ")
ucontrol_qubits = cmd.qubits[0]
target_qubit = cmd.qubits[1]
if not len(cmd.gate.angles) == 2 ** len(ucontrol_qubits):
raise ValueError("Wrong len(angles).")
if len(ucontrol_qubits) == 0:
gate_class(cmd.gate.angles[0]) | target_qubit
return
angles1 = []
angles2 = []
for lower_bits in range(2 ** (len(ucontrol_qubits) - 1)):
leading_0 = cmd.gate.angles[lower_bits]
leading_1 = cmd.gate.angles[lower_bits + 2 ** (len(ucontrol_qubits) - 1)]
angles1.append((leading_0 + leading_1) / 2.0)
angles2.append((leading_0 - leading_1) / 2.0)
rightmost_cnot = {}
for i in range(len(ucontrol_qubits) + 1):
rightmost_cnot[i] = True
_apply_ucr_n(
angles=angles1,
ucontrol_qubits=ucontrol_qubits[:-1],
target_qubit=target_qubit,
eng=eng,
gate_class=gate_class,
rightmost_cnot=rightmost_cnot,
)
# Very custom usage of Compute/CustomUncompute in the following.
with Compute(cmd.engine):
CNOT | (ucontrol_qubits[-1], target_qubit)
_apply_ucr_n(
angles=angles2,
ucontrol_qubits=ucontrol_qubits[:-1],
target_qubit=target_qubit,
eng=eng,
gate_class=gate_class,
rightmost_cnot=rightmost_cnot,
)
with CustomUncompute(eng):
CNOT | (ucontrol_qubits[-1], target_qubit) |
Decomposition for an uniformly controlled single qubit rotation gate.
Follows decomposition in arXiv:quant-ph/0407010 section II and
arXiv:quant-ph/0410066v2 Fig. 9a.
For Ry and Rz it uses 2**len(ucontrol_qubits) CNOT and also
2**len(ucontrol_qubits) single qubit rotations.
Args:
cmd: CommandObject to decompose.
gate_class: Ry or Rz
| _decompose_ucr | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/uniformlycontrolledr2cnot.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/uniformlycontrolledr2cnot.py | Apache-2.0 |
def slow_implementation(angles, control_qubits, target_qubit, eng, gate_class):
"""
Assumption is that control_qubits[0] is lowest order bit
We apply angles[0] to state |0>
"""
assert len(angles) == 2 ** len(control_qubits)
for index in range(2 ** len(control_qubits)):
with Compute(eng):
for bit_pos in range(len(control_qubits)):
if not (index >> bit_pos) & 1:
X | control_qubits[bit_pos]
with Control(eng, control_qubits):
gate_class(angles[index]) | target_qubit
Uncompute(eng) |
Assumption is that control_qubits[0] is lowest order bit
We apply angles[0] to state |0>
| slow_implementation | python | ProjectQ-Framework/ProjectQ | projectq/setups/decompositions/uniformlycontrolledr2cnot_test.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/setups/decompositions/uniformlycontrolledr2cnot_test.py | Apache-2.0 |
def __init__(self, engine, idx):
"""
Initialize a BasicQubit object.
Args:
engine: Owning engine / engine that created the qubit
idx: Unique index of the qubit referenced by this qubit
"""
self.id = idx
self.engine = engine |
Initialize a BasicQubit object.
Args:
engine: Owning engine / engine that created the qubit
idx: Unique index of the qubit referenced by this qubit
| __init__ | python | ProjectQ-Framework/ProjectQ | projectq/types/_qubit.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/types/_qubit.py | Apache-2.0 |
def __eq__(self, other):
"""
Compare with other qubit (Returns True if equal id and engine).
Args:
other (BasicQubit): BasicQubit to which to compare this one
"""
if self.id == -1:
return self is other
return isinstance(other, BasicQubit) and self.id == other.id and self.engine == other.engine |
Compare with other qubit (Returns True if equal id and engine).
Args:
other (BasicQubit): BasicQubit to which to compare this one
| __eq__ | python | ProjectQ-Framework/ProjectQ | projectq/types/_qubit.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/types/_qubit.py | Apache-2.0 |
def __hash__(self):
"""
Return the hash of this qubit.
Hash definition because of custom __eq__. Enables storing a qubit in, e.g., a set.
"""
if self.id == -1:
return object.__hash__(self)
return hash((self.engine, self.id)) |
Return the hash of this qubit.
Hash definition because of custom __eq__. Enables storing a qubit in, e.g., a set.
| __hash__ | python | ProjectQ-Framework/ProjectQ | projectq/types/_qubit.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/types/_qubit.py | Apache-2.0 |
def __del__(self):
"""Destroy the qubit and deallocate it (automatically)."""
if self.id == -1:
return
# If a user directly calls this function, then the qubit gets id == -1 but stays in active_qubits as it is not
# yet deleted, hence remove it manually (if the garbage collector calls this function, then the WeakRef in
# active qubits is already gone):
if self in self.engine.main_engine.active_qubits:
self.engine.main_engine.active_qubits.remove(self)
weak_copy = WeakQubitRef(self.engine, self.id)
self.id = -1
self.engine.deallocate_qubit(weak_copy) | Destroy the qubit and deallocate it (automatically). | __del__ | python | ProjectQ-Framework/ProjectQ | projectq/types/_qubit.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/types/_qubit.py | Apache-2.0 |
def __bool__(self):
"""
Return measured value if Qureg consists of 1 qubit only.
Raises:
Exception if more than 1 qubit resides in this register (then you need to specify which value to get using
qureg[???])
"""
if len(self) == 1:
return bool(self[0])
raise Exception(
"__bool__(qureg): Quantum register contains more than 1 qubit. Use __bool__(qureg[idx]) instead."
) |
Return measured value if Qureg consists of 1 qubit only.
Raises:
Exception if more than 1 qubit resides in this register (then you need to specify which value to get using
qureg[???])
| __bool__ | python | ProjectQ-Framework/ProjectQ | projectq/types/_qubit.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/types/_qubit.py | Apache-2.0 |
def __int__(self):
"""
Return measured value if Qureg consists of 1 qubit only.
Raises:
Exception if more than 1 qubit resides in this register (then you need to specify which value to get using
qureg[???])
"""
if len(self) == 1:
return int(self[0])
raise Exception(
"__int__(qureg): Quantum register contains more than 1 qubit. Use __bool__(qureg[idx]) instead."
) |
Return measured value if Qureg consists of 1 qubit only.
Raises:
Exception if more than 1 qubit resides in this register (then you need to specify which value to get using
qureg[???])
| __int__ | python | ProjectQ-Framework/ProjectQ | projectq/types/_qubit.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/types/_qubit.py | Apache-2.0 |
def __str__(self):
"""Get string representation of a quantum register."""
if len(self) == 0:
return "Qureg[]"
ids = [q.id for q in self[1:]]
ids.append(None) # Forces a flush on last loop iteration.
out_list = []
start_id = self[0].id
count = 1
for qubit_id in ids:
if qubit_id == start_id + count:
count += 1
continue
out_list.append(f'{start_id}-{start_id + count - 1}' if count > 1 else f'{start_id}')
start_id = qubit_id
count = 1
return f"Qureg[{', '.join(out_list)}]" | Get string representation of a quantum register. | __str__ | python | ProjectQ-Framework/ProjectQ | projectq/types/_qubit.py | https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/types/_qubit.py | Apache-2.0 |
def parse_requirements(fname='requirements.txt', with_version=True):
"""Parse the package dependencies listed in a requirements file but strips
specific versioning information.
Args:
fname (str): path to requirements file
with_version (bool, default=False): if True include version specs
Returns:
List[str]: list of requirements items
CommandLine:
python -c "import setup; print(setup.parse_requirements())"
"""
import re
import sys
from os.path import exists
require_fpath = fname
def parse_line(line):
"""Parse information from a line in a requirements text file."""
if line.startswith('-r '):
# Allow specifying requirements in other files
target = line.split(' ')[1]
for info in parse_require_file(target):
yield info
else:
info = {'line': line}
if line.startswith('-e '):
info['package'] = line.split('#egg=')[1]
elif '@git+' in line:
info['package'] = line
else:
# Remove versioning from the package
pat = '(' + '|'.join(['>=', '==', '>']) + ')'
parts = re.split(pat, line, maxsplit=1)
parts = [p.strip() for p in parts]
info['package'] = parts[0]
if len(parts) > 1:
op, rest = parts[1:]
if ';' in rest:
# Handle platform specific dependencies
# http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
version, platform_deps = map(str.strip,
rest.split(';'))
info['platform_deps'] = platform_deps
else:
version = rest # NOQA
info['version'] = (op, version)
yield info
def parse_require_file(fpath):
with open(fpath, 'r') as f:
for line in f.readlines():
line = line.strip()
if line and not line.startswith('#'):
for info in parse_line(line):
yield info
def gen_packages_items():
if exists(require_fpath):
for info in parse_require_file(require_fpath):
parts = [info['package']]
if with_version and 'version' in info:
parts.extend(info['version'])
if not sys.version.startswith('3.4'):
# apparently package_deps are broken in 3.4
platform_deps = info.get('platform_deps')
if platform_deps is not None:
parts.append(';' + platform_deps)
item = ''.join(parts)
yield item
packages = list(gen_packages_items())
return packages | Parse the package dependencies listed in a requirements file but strips
specific versioning information.
Args:
fname (str): path to requirements file
with_version (bool, default=False): if True include version specs
Returns:
List[str]: list of requirements items
CommandLine:
python -c "import setup; print(setup.parse_requirements())"
| parse_requirements | python | open-mmlab/mmaction2 | setup.py | https://github.com/open-mmlab/mmaction2/blob/master/setup.py | Apache-2.0 |
def parse_line(line):
"""Parse information from a line in a requirements text file."""
if line.startswith('-r '):
# Allow specifying requirements in other files
target = line.split(' ')[1]
for info in parse_require_file(target):
yield info
else:
info = {'line': line}
if line.startswith('-e '):
info['package'] = line.split('#egg=')[1]
elif '@git+' in line:
info['package'] = line
else:
# Remove versioning from the package
pat = '(' + '|'.join(['>=', '==', '>']) + ')'
parts = re.split(pat, line, maxsplit=1)
parts = [p.strip() for p in parts]
info['package'] = parts[0]
if len(parts) > 1:
op, rest = parts[1:]
if ';' in rest:
# Handle platform specific dependencies
# http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
version, platform_deps = map(str.strip,
rest.split(';'))
info['platform_deps'] = platform_deps
else:
version = rest # NOQA
info['version'] = (op, version)
yield info | Parse information from a line in a requirements text file. | parse_line | python | open-mmlab/mmaction2 | setup.py | https://github.com/open-mmlab/mmaction2/blob/master/setup.py | Apache-2.0 |
def add_mim_extension():
"""Add extra files that are required to support MIM into the package.
These files will be added by creating a symlink to the originals if the
package is installed in `editable` mode (e.g. pip install -e .), or by
copying from the originals otherwise.
"""
# parse installment mode
if 'develop' in sys.argv:
# installed by `pip install -e .`
mode = 'symlink'
elif 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
# installed by `pip install .`
# or create source distribution by `python setup.py sdist`
mode = 'copy'
else:
return
filenames = ['tools', 'configs', 'model-index.yml', 'dataset-index.yml']
repo_path = osp.dirname(__file__)
mim_path = osp.join(repo_path, 'mmaction', '.mim')
os.makedirs(mim_path, exist_ok=True)
for filename in filenames:
if osp.exists(filename):
src_path = osp.join(repo_path, filename)
tar_path = osp.join(mim_path, filename)
if osp.isfile(tar_path) or osp.islink(tar_path):
os.remove(tar_path)
elif osp.isdir(tar_path):
shutil.rmtree(tar_path)
if mode == 'symlink':
src_relpath = osp.relpath(src_path, osp.dirname(tar_path))
try:
os.symlink(src_relpath, tar_path)
except OSError:
# Creating a symbolic link on windows may raise an
# `OSError: [WinError 1314]` due to privilege. If
# the error happens, the src file will be copied
mode = 'copy'
warnings.warn(
f'Failed to create a symbolic link for {src_relpath}, '
f'and it will be copied to {tar_path}')
else:
continue
elif mode == 'copy':
if osp.isfile(src_path):
shutil.copyfile(src_path, tar_path)
elif osp.isdir(src_path):
shutil.copytree(src_path, tar_path)
else:
warnings.warn(f'Cannot copy file {src_path}.')
else:
raise ValueError(f'Invalid mode {mode}') | Add extra files that are required to support MIM into the package.
These files will be added by creating a symlink to the originals if the
package is installed in `editable` mode (e.g. pip install -e .), or by
copying from the originals otherwise.
| add_mim_extension | python | open-mmlab/mmaction2 | setup.py | https://github.com/open-mmlab/mmaction2/blob/master/setup.py | Apache-2.0 |
def get_output(
video_path: str,
out_filename: str,
data_sample: str,
labels: list,
fps: int = 30,
font_scale: Optional[str] = None,
font_color: str = 'white',
target_resolution: Optional[Tuple[int]] = None,
) -> None:
"""Get demo output using ``moviepy``.
This function will generate video file or gif file from raw video or
frames, by using ``moviepy``. For more information of some parameters,
you can refer to: https://github.com/Zulko/moviepy.
Args:
video_path (str): The video file path.
out_filename (str): Output filename for the generated file.
datasample (str): Predicted label of the generated file.
labels (list): Label list of current dataset.
fps (int): Number of picture frames to read per second. Defaults to 30.
font_scale (float): Font scale of the text. Defaults to None.
font_color (str): Font color of the text. Defaults to ``white``.
target_resolution (Tuple[int], optional): Set to
(desired_width desired_height) to have resized frames. If
either dimension is None, the frames are resized by keeping
the existing aspect ratio. Defaults to None.
"""
if video_path.startswith(('http://', 'https://')):
raise NotImplementedError
# init visualizer
out_type = 'gif' if osp.splitext(out_filename)[1] == '.gif' else 'video'
visualizer = ActionVisualizer()
visualizer.dataset_meta = dict(classes=labels)
text_cfg = {'colors': font_color}
if font_scale is not None:
text_cfg.update({'font_sizes': font_scale})
visualizer.add_datasample(
out_filename,
video_path,
data_sample,
draw_pred=True,
draw_gt=False,
text_cfg=text_cfg,
fps=fps,
out_type=out_type,
out_path=osp.join('demo', out_filename),
target_resolution=target_resolution) | Get demo output using ``moviepy``.
This function will generate video file or gif file from raw video or
frames, by using ``moviepy``. For more information of some parameters,
you can refer to: https://github.com/Zulko/moviepy.
Args:
video_path (str): The video file path.
out_filename (str): Output filename for the generated file.
datasample (str): Predicted label of the generated file.
labels (list): Label list of current dataset.
fps (int): Number of picture frames to read per second. Defaults to 30.
font_scale (float): Font scale of the text. Defaults to None.
font_color (str): Font color of the text. Defaults to ``white``.
target_resolution (Tuple[int], optional): Set to
(desired_width desired_height) to have resized frames. If
either dimension is None, the frames are resized by keeping
the existing aspect ratio. Defaults to None.
| get_output | python | open-mmlab/mmaction2 | demo/demo.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/demo.py | Apache-2.0 |
def visualize(frames, annotations, plate=plate_blue, max_num=5):
"""Visualize frames with predicted annotations.
Args:
frames (list[np.ndarray]): Frames for visualization, note that
len(frames) % len(annotations) should be 0.
annotations (list[list[tuple]]): The predicted results.
plate (str): The plate used for visualization. Default: plate_blue.
max_num (int): Max number of labels to visualize for a person box.
Default: 5.
Returns:
list[np.ndarray]: Visualized frames.
"""
assert max_num + 1 <= len(plate)
plate = [x[::-1] for x in plate]
frames_out = cp.deepcopy(frames)
nf, na = len(frames), len(annotations)
assert nf % na == 0
nfpa = len(frames) // len(annotations)
anno = None
h, w, _ = frames[0].shape
scale_ratio = np.array([w, h, w, h])
for i in range(na):
anno = annotations[i]
if anno is None:
continue
for j in range(nfpa):
ind = i * nfpa + j
frame = frames_out[ind]
for ann in anno:
box = ann[0]
label = ann[1]
if not len(label):
continue
score = ann[2]
box = (box * scale_ratio).astype(np.int64)
st, ed = tuple(box[:2]), tuple(box[2:])
cv2.rectangle(frame, st, ed, plate[0], 2)
for k, lb in enumerate(label):
if k >= max_num:
break
text = abbrev(lb)
text = ': '.join([text, f'{score[k]:>.2f}'])
location = (0 + st[0], 18 + k * 18 + st[1])
textsize = cv2.getTextSize(text, FONTFACE, FONTSCALE,
THICKNESS)[0]
textwidth = textsize[0]
diag0 = (location[0] + textwidth, location[1] - 14)
diag1 = (location[0], location[1] + 2)
cv2.rectangle(frame, diag0, diag1, plate[k + 1], -1)
cv2.putText(frame, text, location, FONTFACE, FONTSCALE,
FONTCOLOR, THICKNESS, LINETYPE)
return frames_out | Visualize frames with predicted annotations.
Args:
frames (list[np.ndarray]): Frames for visualization, note that
len(frames) % len(annotations) should be 0.
annotations (list[list[tuple]]): The predicted results.
plate (str): The plate used for visualization. Default: plate_blue.
max_num (int): Max number of labels to visualize for a person box.
Default: 5.
Returns:
list[np.ndarray]: Visualized frames.
| visualize | python | open-mmlab/mmaction2 | demo/demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/demo_spatiotemporal_det.py | Apache-2.0 |
def load_label_map(file_path):
"""Load Label Map.
Args:
file_path (str): The file path of label map.
Returns:
dict: The label map (int -> label name).
"""
lines = open(file_path).readlines()
lines = [x.strip().split(': ') for x in lines]
return {int(x[0]): x[1] for x in lines} | Load Label Map.
Args:
file_path (str): The file path of label map.
Returns:
dict: The label map (int -> label name).
| load_label_map | python | open-mmlab/mmaction2 | demo/demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/demo_spatiotemporal_det.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.