#
# Copyright © 2022-2023 University of Strasbourg. All Rights Reserved.
# Copyright © 2023-2025 QPerfect. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Pauli rotation gate (RPauli)."""
import numpy as np
from mimiqcircuits.operations.gates.gate import Gate
from mimiqcircuits.circuit import Circuit
from mimiqcircuits.operations.gates.generalized.rnz import GateRNZ
from mimiqcircuits.operations.gates.standard.hadamard import GateH, GateHYZ
from mimiqcircuits.operations.gates.standard.id import GateID
from mimiqcircuits.operations.gates.standard.u import GateU
import symengine as se
from mimiqcircuits._sympycheck import _is_basic
from mimiqcircuits.operations.gates.generalized.paulistring import PauliString
[docs]
class RPauli(Gate):
r"""Rotation generated by a Pauli string.
Implements
.. math::
e^{-i \frac{\theta}{2} (P_1 \otimes P_2 \otimes \dots \otimes P_N)}
where each :math:`P_i` is ``"I"``, ``"X"``, ``"Y"`` or ``"Z"`` and acts on
the :math:`i`-th target qubit. The gate acts on all :math:`N` qubits of
the string, including those with ``"I"``. It is used for time evolution
under a Pauli term, such as Trotter steps and variational ansätze.
The decomposition changes the basis of each ``"X"`` qubit with
:class:`GateH` and of each ``"Y"`` qubit with :class:`GateHYZ`, then
applies one :class:`GateRNZ` on the non-identity qubits. A string of only
``"I"`` decomposes into the global phase :math:`e^{-i\theta/2}`.
Args:
pauli (PauliString): The Pauli string. A plain ``str`` is not
accepted.
theta: Rotation angle in radians, numeric or symbolic.
Examples:
>>> from mimiqcircuits import *
>>> from symengine import pi
>>> RPauli(PauliString("X"), pi/2)
R("X", (1/2)*pi)
>>> RPauli(PauliString("ZIZ"), 2.0)
R("ZIZ", 2.0)
>>> c = Circuit()
>>> c.push(RPauli(PauliString("YXI"), 2.0), 1, 2, 3)
4-qubit circuit with 1 instruction:
└── R("YXI", 2.0) @ q[1:3]
<BLANKLINE>
>>> c.push(RPauli(PauliString("IXY"), pi), 1, 2, 3)
4-qubit circuit with 2 instructions:
├── R("YXI", 2.0) @ q[1:3]
└── R("IXY", pi) @ q[1:3]
<BLANKLINE>
>>> RPauli(PauliString("XZ"), 0.3).decompose()
2-qubit circuit with 3 instructions:
├── H @ q[0]
├── RNZ(0.3) @ q[0:1]
└── H @ q[0]
<BLANKLINE>
See Also:
:class:`PauliString`, :class:`GateRNZ`
"""
_name = "RPauli"
_num_bits = 0
_num_cregs = 0
_num_zregs = 0
_num_zvars = 0
_zregsizes = []
_cregsizes = []
_parnames = ("theta",)
def __init__(self, pauli: PauliString, theta):
self.pauli = pauli
self.theta = theta
super().__init__()
self._num_qregs = 1
self._num_qubits = len(pauli.pauli)
self._qregsizes = [len(pauli.pauli)]
[docs]
def isidentity(self):
"""Return ``True`` if the string is all ``"I"`` or ``theta`` is zero.
An all-``"I"`` string with a non-zero angle is a global phase, which
this check ignores.
"""
if all(p == "I" for p in str(self.pauli)):
return True
theta = self.theta
if isinstance(theta, (int, float, complex)):
return theta == 0
elif hasattr(theta, "evalf") and theta == 0:
return True
return False
[docs]
def isunitary(self):
return True
[docs]
def iswrapper(self):
# Not a wrapper: it holds a Pauli string and an angle, no operation.
return False
def _decompose(self, circ: Circuit, qtargets, ctargets=None, ztargets=None):
s = str(self.pauli)
if len(s) != len(qtargets):
raise ValueError("Length of Pauli string and qubit list must match.")
active = [(p, q) for p, q in zip(s, qtargets) if p != "I"]
active_qubits = [q for _, q in active]
if not active:
circ.push(GateU(0, 0, 0, -self.theta / 2), max(qtargets))
return circ
if max(qtargets) not in active_qubits:
circ.push(GateID(), max(qtargets))
for p, q in active:
if p == "X":
circ.push(GateH(), q)
elif p == "Y":
circ.push(GateHYZ(), q)
# Apply RNZ on active qubits
circ.push(GateRNZ(len(active_qubits), self.theta), *active_qubits)
for p, q in reversed(active):
if p == "X":
circ.push(GateH(), q)
elif p == "Y":
circ.push(GateHYZ(), q)
return circ
def __str__(self):
return f'R("{str(self.pauli)}", {self.theta})'
def _matrix(self):
from mimiqcircuits.matrices import symbolic_matrix_exponential
theta = self.theta
mat_sym = self.pauli.matrix()
# Use symbolic exponential if theta is symbolic
if _is_basic(theta):
return symbolic_matrix_exponential(mat_sym, theta)
# Use numerical exponential otherwise
mat_np = np.array(mat_sym.tolist(), dtype=complex)
from scipy.linalg import expm
mat_exp = expm(-1j * theta / 2 * mat_np)
return se.Matrix(mat_exp.tolist())
[docs]
def evaluate(self, d):
"""Substitute symbols in ``theta`` and return a new gate.
Args:
d (dict): Map from symbols to the values to substitute.
Returns:
RPauli: A new gate with the same Pauli string and the substituted
angle.
"""
theta = self.theta
if hasattr(theta, "subs"):
theta = theta.subs(d)
return type(self)(self.pauli, theta)
__all__ = ["RPauli"]