Skip to content

Commit f5f05bf

Browse files
add any and exp rotation gate
1 parent a24bd0d commit f5f05bf

File tree

4 files changed

+50
-3
lines changed

4 files changed

+50
-3
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ c.CNOT(0,1)
1414
print(c.perfect_sampling())
1515
print(c.wavefunction())
1616
print(c.measure(1))
17-
print(c.expectation((tc.gates.z(), 1)))
17+
print(c.expectation((tc.gates.z(), [1])))
1818
```
1919

2020
Runtime behavior changing:

tensorcircuit/circuit.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ class Circuit:
1919
sgates = (
2020
["i", "x", "y", "z", "h", "t", "s", "rs"] + ["cnot", "cz", "swap"] + ["toffoli"]
2121
)
22-
vgates = ["r", "cr", "rx", "ry", "rz"]
22+
vgates = ["r", "cr", "rx", "ry", "rz", "any", "exp"]
2323

2424
def __init__(self, nqubits: int) -> None:
2525
_prefix = "qb-"

tensorcircuit/gates.py

+29-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
import sys
66
from copy import deepcopy
77
from typing import Optional, Any
8-
from functools import partial
8+
from functools import partial, reduce
9+
from operator import mul
910

1011
import numpy as np
1112
from scipy.stats import unitary_group
@@ -242,3 +243,30 @@ def random_two_qubit_gate() -> Gate:
242243
unitary = unitary_group.rvs(dim=4)
243244
unitary = np.reshape(unitary, newshape=(2, 2, 2, 2))
244245
return Gate(deepcopy(unitary), name="R2Q")
246+
247+
248+
def any_gate(unitary: Tensor) -> Gate:
249+
"""
250+
Note one should provide the gate with properly reshaped
251+
252+
:param unitary: corresponding gate
253+
"""
254+
return Gate(deepcopy(unitary), name="any")
255+
256+
257+
any = any_gate
258+
259+
260+
def exponential_gate(unitary: Tensor, theta: float, name: str = "none") -> Gate:
261+
"""
262+
$\exp{-i\theta unitary}$
263+
"""
264+
theta = num_to_tensor(theta)
265+
mat = backend.expm(-backend.i() * theta * unitary)
266+
dimension = reduce(mul, mat.shape)
267+
nolegs = int(np.log(dimension) / np.log(2))
268+
mat = backend.reshape(mat, shape=[2 for _ in range(nolegs)])
269+
return Gate(mat, name="exp-" + name)
270+
271+
272+
exp = exponential_gate

tests/test_gates.py

+19
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,22 @@ def test_rgate(highp):
1515
tc.gates.rgate(1, 2, 3).tensor, tc.gates.rgate_theoretical(1, 2, 3).tensor
1616
)
1717
# tc.set_dtype("complex64")
18+
19+
20+
def test_exp_gate():
21+
c = tc.Circuit(2)
22+
c.exp(
23+
0,
24+
1,
25+
unitary=tc.gates.array_to_tensor(
26+
np.array([[1.0, 0, 0, 0], [0, -1.0, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
27+
),
28+
theta=tc.gates.num_to_tensor(np.pi / 2),
29+
)
30+
assert np.allclose(c.wavefunction()[0, 0], -1j)
31+
32+
33+
def test_any_gate():
34+
c = tc.Circuit(2)
35+
c.any(0, unitary=np.eye(2))
36+
assert np.allclose(c.expectation((tc.gates.z(), [0])), 1.0)

0 commit comments

Comments
 (0)