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 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 = en... |
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)
""... |
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:
qst... | 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 __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:
... |
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... | __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/... |
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
... | __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, "
... | 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 inv... |
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 obj... |
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... |
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.
... |
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 (tupl... | __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 __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:
... |
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) +... | __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... |
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 ... |
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... | 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,)
Q... |
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,)
... | __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.
... |
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 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, (... |
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 QubitOpe... |
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 multipl... |
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... | __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: Can... |
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 typ... | __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:
... |
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):
... |
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 __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 ampl... |
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... | __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
... |
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 ... | 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
... |
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,)
... | __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_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_set... | 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(crede... | 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` ... |
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 whic... | 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_... | 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 DeviceOfflineE... | 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
`NoGateDecomposition... |
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 ... | 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 wh... |
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 whi... | 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:
... |
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:
... | 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 d... |
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
... | 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... |
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 whic... | 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 ... | 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.matr... |
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)]]
... |
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. param... | _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... |
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... | _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... |
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) R... | _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... |
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 ... | 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
... |
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 ... | _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:
... |
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 pos... | _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)],... |
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)]]
wh... | _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(-mat... | 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 _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... | 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... | 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... |
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
# Resen... | 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... | 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_stat... | 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
Ten... | 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 Compu... | 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 Comp... | 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_... |
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... | 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 = Qub... | 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
... |
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 im... | _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]
... | 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) si... |
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... | _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):... |
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... |
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 collec... | 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(... |
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 __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
... | 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 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 gen... | 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 (... | 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.
... | 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_blu... | 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 line... | 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 |
def abbrev(name):
"""Get the abbreviation of label name:
'take (an object) from (a person)' -> 'take ... from ...'
"""
while name.find('(') != -1:
st, ed = name.find('('), name.find(')')
name = name[:st] + '...' + name[ed + 1:]
return name | Get the abbreviation of label name:
'take (an object) from (a person)' -> 'take ... from ...'
| abbrev | 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 pack_result(human_detection, result, img_h, img_w):
"""Short summary.
Args:
human_detection (np.ndarray): Human detection result.
result (type): The predicted label of each human proposal.
img_h (int): The image height.
img_w (int): The image width.
Returns:
tupl... | Short summary.
Args:
human_detection (np.ndarray): Human detection result.
result (type): The predicted label of each human proposal.
img_h (int): The image height.
img_w (int): The image width.
Returns:
tuple: Tuple of human proposal, label name and label score.
| pack_result | 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 visualize(args,
frames,
annotations,
pose_data_samples,
action_result,
plate=PLATEBLUE,
max_num=5):
"""Visualize frames with predicted annotations.
Args:
frames (list[np.ndarray]): Frames for visualization, note tha... | 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 spatio-temporal
detection results.
pose_data_samples (list[lis... | visualize | python | open-mmlab/mmaction2 | demo/demo_video_structuralize.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/demo_video_structuralize.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 lin... | 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_video_structuralize.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/demo_video_structuralize.py | Apache-2.0 |
def pack_result(human_detection, result, img_h, img_w):
"""Short summary.
Args:
human_detection (np.ndarray): Human detection result.
result (type): The predicted label of each human proposal.
img_h (int): The image height.
img_w (int): The image width.
Returns:
tup... | Short summary.
Args:
human_detection (np.ndarray): Human detection result.
result (type): The predicted label of each human proposal.
img_h (int): The image height.
img_w (int): The image width.
Returns:
tuple: Tuple of human proposal, label name and label score.
| pack_result | python | open-mmlab/mmaction2 | demo/demo_video_structuralize.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/demo_video_structuralize.py | Apache-2.0 |
def add_frames(self, idx, frames, processed_frames):
"""Add the clip and corresponding id.
Args:
idx (int): the current index of the clip.
frames (list[ndarray]): list of images in "BGR" format.
processed_frames (list[ndarray]): list of resize and normed images
... | Add the clip and corresponding id.
Args:
idx (int): the current index of the clip.
frames (list[ndarray]): list of images in "BGR" format.
processed_frames (list[ndarray]): list of resize and normed images
in "BGR" format.
| add_frames | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py | Apache-2.0 |
def get_model_inputs(self, device):
"""Convert preprocessed images to MMAction2 STDet model inputs."""
cur_frames = [self.processed_frames[idx] for idx in self.frames_inds]
input_array = np.stack(cur_frames).transpose((3, 0, 1, 2))[np.newaxis]
input_tensor = torch.from_numpy(input_array)... | Convert preprocessed images to MMAction2 STDet model inputs. | get_model_inputs | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py | Apache-2.0 |
def _do_detect(self, image):
"""Get human bboxes with shape [n, 4].
The format of bboxes is (xmin, ymin, xmax, ymax) in pixels.
""" | Get human bboxes with shape [n, 4].
The format of bboxes is (xmin, ymin, xmax, ymax) in pixels.
| _do_detect | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py | Apache-2.0 |
def _do_detect(self, image):
"""Get bboxes in shape [n, 4] and values in pixels."""
det_data_sample = inference_detector(self.model, image)
pred_instance = det_data_sample.pred_instances.cpu().numpy()
# We only keep human detection bboxs with score larger
# than `det_score_thr` a... | Get bboxes in shape [n, 4] and values in pixels. | _do_detect | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py | Apache-2.0 |
def predict(self, task):
"""Spatio-temporval Action Detection model inference."""
# No need to do inference if no one in keyframe
if len(task.stdet_bboxes) == 0:
return task
with torch.no_grad():
result = self.model(**task.get_model_inputs(self.device))
s... | Spatio-temporval Action Detection model inference. | predict | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py | Apache-2.0 |
def read_fn(self):
"""Main function for read thread.
Contains three steps:
1) Read and preprocess (resize + norm) frames from source.
2) Create task by frames from previous step and buffer.
3) Put task into read queue.
"""
was_read = True
start_time = ti... | Main function for read thread.
Contains three steps:
1) Read and preprocess (resize + norm) frames from source.
2) Create task by frames from previous step and buffer.
3) Put task into read queue.
| read_fn | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py | Apache-2.0 |
def display_fn(self):
"""Main function for display thread.
Read data from display queue and display predictions.
"""
start_time = time.time()
while not self.stopped:
# get the state of the read thread
with self.read_id_lock:
read_id = self... | Main function for display thread.
Read data from display queue and display predictions.
| display_fn | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py | Apache-2.0 |
def __next__(self):
"""Get data from read queue.
This function is part of the main thread.
"""
if self.read_queue.qsize() == 0:
time.sleep(0.02)
return not self.stopped, None
was_read, task = self.read_queue.get()
if not was_read:
# I... | Get data from read queue.
This function is part of the main thread.
| __next__ | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py | Apache-2.0 |
def start(self):
"""Start read thread and display thread."""
self.read_thread = threading.Thread(
target=self.read_fn, args=(), name='VidRead-Thread', daemon=True)
self.read_thread.start()
self.display_thread = threading.Thread(
target=self.display_fn,
... | Start read thread and display thread. | start | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py | Apache-2.0 |
def clean(self):
"""Close all threads and release all resources."""
self.stopped = True
self.read_lock.acquire()
self.cap.release()
self.read_lock.release()
self.output_lock.acquire()
cv2.destroyAllWindows()
if self.video_writer:
self.video_wri... | Close all threads and release all resources. | clean | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py | Apache-2.0 |
def display(self, task):
"""Add the visualized task to the display queue.
Args:
task (TaskInfo object): task object that contain the necessary
information for prediction visualization.
"""
with self.display_lock:
self.display_queue[task.id] = (True, t... | Add the visualized task to the display queue.
Args:
task (TaskInfo object): task object that contain the necessary
information for prediction visualization.
| display | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py | Apache-2.0 |
def get_output_video_writer(self, path):
"""Return a video writer object.
Args:
path (str): path to the output video file.
"""
return cv2.VideoWriter(
filename=path,
fourcc=cv2.VideoWriter_fourcc(*'mp4v'),
fps=float(self.output_fps),
... | Return a video writer object.
Args:
path (str): path to the output video file.
| get_output_video_writer | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_demo_spatiotemporal_det.py | Apache-2.0 |
def draw_predictions(self, task):
"""Visualize stdet predictions on raw frames."""
# read bboxes from task
bboxes = task.display_bboxes.cpu().numpy()
# draw predictions and update task
keyframe_idx = len(task.frames) // 2
draw_range = [
keyframe_idx - task.cl... | Visualize stdet predictions on raw frames. | draw_predictions | python | open-mmlab/mmaction2 | demo/webcam_demo_spatiotemporal_det.py | https://github.com/open-mmlab/mmaction2/blob/master/demo/webcam_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.