Skip to content

Commit

Permalink
Merge pull request #2 from GenericP3rson/reformatting_ops
Browse files Browse the repository at this point in the history
Reformatting ops
  • Loading branch information
01110011011101010110010001101111 authored Aug 31, 2023
2 parents 2063965 + 1551eeb commit 9712d44
Show file tree
Hide file tree
Showing 33 changed files with 1,325 additions and 1,105 deletions.
1 change: 1 addition & 0 deletions test/operator/test_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
{"qiskit": qiskit_gate.CRYGate, "tq": tq.CRY},
{"qiskit": qiskit_gate.CRZGate, "tq": tq.CRZ},
# {'qiskit': qiskit_gate.?, 'tq': tq.CRot},
{"qiskit": qiskit_gate.UGate, "tq": tq.U},
{"qiskit": qiskit_gate.U1Gate, "tq": tq.U1},
{"qiskit": qiskit_gate.U2Gate, "tq": tq.U2},
{"qiskit": qiskit_gate.U3Gate, "tq": tq.U3},
Expand Down
23 changes: 23 additions & 0 deletions torchquantum/operator/ecr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from .op_types import Operation
from abc import ABCMeta
from ..macro import C_DTYPE
import torchquantum as tq
import torch
from torchquantum.functional import mat_dict
import torchquantum.functional.functionals as tqf


class ECR(Operation, metaclass=ABCMeta):
"""Class for Echoed Cross Resonance Gate."""

num_params = 0
num_wires = 2
matrix = mat_dict["ecr"]
func = staticmethod(tqf.ecr)

@classmethod
def _matrix(cls, params):
return cls.matrix


EchoedCrossResonance = ECR
19 changes: 19 additions & 0 deletions torchquantum/operator/global_phase.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from .op_types import Operation
from abc import ABCMeta
from ..macro import C_DTYPE
import torchquantum as tq
import torch
from torchquantum.functional import mat_dict
import torchquantum.functional.functionals as tqf


class GlobalPhase(Operation, metaclass=ABCMeta):
"""Class for Global Phase gate."""

num_params = 1
num_wires = 0
func = staticmethod(tqf.globalphase)

@classmethod
def _matrix(cls, params):
return tqf.globalphase_matrix(params)
18 changes: 18 additions & 0 deletions torchquantum/operator/hadamard.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,21 @@ class SHadamard(Operation, metaclass=ABCMeta):
@classmethod
def _matrix(cls, params):
return cls.matrix


class CHadamard(Operation, metaclass=ABCMeta):
"""Class for CHadamard Gate."""

num_params = 0
num_wires = 2
matrix = mat_dict["chadamard"]
func = staticmethod(tqf.chadamard)

@classmethod
def _matrix(cls, params):
return cls.matrix


H = Hadamard
SH = SHadamard
CH = CHadamard
28 changes: 28 additions & 0 deletions torchquantum/operator/i.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from .op_types import Observable
from abc import ABCMeta
from ..macro import C_DTYPE
import torchquantum as tq
import torch
from torchquantum.functional import mat_dict
import torchquantum.functional.functionals as tqf


class I(Observable, metaclass=ABCMeta):
"""Class for Identity Gate."""

num_params = 0
num_wires = 1
eigvals = torch.tensor([1, 1], dtype=C_DTYPE)
matrix = mat_dict["i"]
func = staticmethod(tqf.i)

@classmethod
def _matrix(cls, params):
return cls.matrix

@classmethod
def _eigvals(cls, params):
return cls.eigvals

def diagonalizing_gates(self):
return []
20 changes: 20 additions & 0 deletions torchquantum/operator/iswap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from .op_types import Operation
from abc import ABCMeta
from ..macro import C_DTYPE
import torchquantum as tq
import torch
from torchquantum.functional import mat_dict
import torchquantum.functional.functionals as tqf


class ISWAP(Operation, metaclass=ABCMeta):
"""Class for ISWAP Gate."""

num_params = 0
num_wires = 2
matrix = mat_dict["iswap"]
func = staticmethod(tqf.iswap)

@classmethod
def _matrix(cls, params):
return cls.matrix
66 changes: 33 additions & 33 deletions torchquantum/operator/op_hamil_exp.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,40 +32,38 @@
import numpy as np

__all__ = [
'OpHamilExp',
'OpPauliExp',
]
"OpHamilExp",
"OpPauliExp",
]


class OpHamilExp(QuantumModule):
"""Matrix exponential operation.
exp(-i * theta * H / 2)
the default theta is 0.0
"""
def __init__(self,
hamil: Hamiltonian,
trainable: bool = True,
theta: float = 0.0):

def __init__(self, hamil: Hamiltonian, trainable: bool = True, theta: float = 0.0):
"""Initialize the OpHamilExp module.
Args:
hamil: The Hamiltonian.
has_params: Whether the module has parameters.
trainable: Whether the parameters are trainable.
theta: The initial value of theta.
"""
super().__init__()
if trainable:
self.theta = torch.nn.parameter.Parameter(torch.tensor(theta))
else:
self.theta = torch.tensor(theta)
self.hamil = hamil

def get_exponent_matrix(self):
"""Get the matrix on exponent."""
return self.hamil.matrix * -1j * self.theta / 2

@property
def exponent_matrix(self):
"""Get the matrix on exponent."""
Expand All @@ -74,12 +72,12 @@ def exponent_matrix(self):
def get_matrix(self):
"""Get the overall matrix."""
return torch.matrix_exp(self.exponent_matrix)

@property
def matrix(self):
"""Get the overall matrix."""
return self.get_matrix()

def forward(self, qdev, wires):
"""Forward the OpHamilExp module.
Args:
Expand All @@ -96,21 +94,23 @@ def forward(self, qdev, wires):


class OpPauliExp(OpHamilExp):
def __init__(self,
coeffs: List[float],
paulis: List[str],
endianness: str = "big",
trainable: bool = True,
theta: float = 0.0):
def __init__(
self,
coeffs: List[float],
paulis: List[str],
endianness: str = "big",
trainable: bool = True,
theta: float = 0.0,
):
"""Initialize the OpPauliExp module.
Args:
coeffs: The coefficients of the Hamiltonian.
paulis: The operators of the Hamiltonian, described in strings.
endianness: The endianness of the operators. Default is big. Qubit 0 is the most significant bit.
trainable: Whether the parameters are trainable.
theta: The initial value of theta.
"""
self.hamil = Hamiltonian(coeffs, paulis, endianness)
super().__init__(
Expand All @@ -121,7 +121,7 @@ def __init__(self,
self.coeffs = coeffs
self.paulis = paulis
self.trainable = trainable

def forward(self, qdev, wires):
"""Forward the OpHamilExp module.
Args:
Expand All @@ -132,17 +132,17 @@ def forward(self, qdev, wires):
matrix = self.matrix.to(qdev.device)
if qdev.record_op:
qdev.op_history.append(
{
"name": self.__class__.__name__, # type: ignore
"wires": np.array(wires).squeeze().tolist(),
"coeffs": self.coeffs,
"paulis": self.paulis,
"inverse": False,
"trainable": self.trainable,
"params": self.theta.item(),
}
)
{
"name": self.__class__.__name__, # type: ignore
"wires": np.array(wires).squeeze().tolist(),
"coeffs": self.coeffs,
"paulis": self.paulis,
"inverse": False,
"trainable": self.trainable,
"params": self.theta.item(),
}
)

tqf.qubitunitaryfast(
q_device=qdev,
wires=wires,
Expand Down
30 changes: 30 additions & 0 deletions torchquantum/operator/op_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,36 @@
from abc import ABCMeta
from ..macro import C_DTYPE, F_DTYPE
from typing import Iterable, Union, List
from enum import IntEnum


class WiresEnum(IntEnum):
"""Integer enumeration class
to represent the number of wires
an operation acts on."""

AnyWires = -1
AllWires = 0


class NParamsEnum(IntEnum):
"""Integer enumeration class
to represent the number of wires
an operation acts on"""

AnyNParams = -1


AnyNParams = NParamsEnum.AnyNParams


AllWires = WiresEnum.AllWires
"""IntEnum: An enumeration which represents all wires in the
subsystem. It is equivalent to an integer with value 0."""

AnyWires = WiresEnum.AnyWires
"""IntEnum: An enumeration which represents any wires in the
subsystem. It is equivalent to an integer with value -1."""


class Operator(tq.QuantumModule):
Expand Down
Loading

0 comments on commit 9712d44

Please sign in to comment.