-
Notifications
You must be signed in to change notification settings - Fork 0
/
gate.go
137 lines (116 loc) · 2.16 KB
/
gate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package qsim
import (
"math"
"math/cmplx"
"github.com/sp301415/qsim/math/mat"
"github.com/sp301415/qsim/math/number"
)
type Gate struct {
data mat.Mat
size int
}
// NewGate allocates new gate of given matrix.
func NewGate(m mat.Mat) Gate {
if !m.IsUnitary() {
panic("Matrix not unitary.")
}
if (m.NRows()&(m.NRows()-1) != 0) && (m.NRows() <= 0) {
panic("Matrix size should be a power of two.")
}
return Gate{data: m, size: number.BitLen(m.NRows()) - 1}
}
// ToMat copies the underlying mat and returns.
func (g Gate) ToMat() mat.Mat {
return g.data.Copy()
}
// Copy copies g.
func (g Gate) Copy() Gate {
return Gate{data: g.data.Copy()}
}
// Size returns the size of the gate. Here, size means the qubit length of a gate.
// For example, a 4*4 gate has size 2.
func (g Gate) Size() int {
return g.size
}
// At returns the (i, j)th element.
func (g Gate) At(i, j int) complex128 {
return g.data[i][j]
}
// Tensor returns the tensor product of g and given gate.
func (g Gate) Tensor(o Gate) Gate {
return Gate{
data: g.data.Tensor(o.data),
size: g.size + o.size,
}
}
// Famous Gates.
// I returns the Identity Gate.
func I() Gate {
return Gate{
data: [][]complex128{
{1, 0},
{0, 1},
},
size: 1,
}
}
// X returns the NOT Gate (X Gate).
func X() Gate {
return Gate{
data: [][]complex128{
{0, 1},
{1, 0},
},
size: 1,
}
}
// Y returns the Y Gate.
func Y() Gate {
return Gate{data: [][]complex128{
{0, -1i},
{1i, 0},
},
size: 1,
}
}
// Z returns the Z gate.
func Z() Gate {
return Gate{data: [][]complex128{
{1, 0},
{0, -1},
},
size: 1,
}
}
// H returns the Hadamard Gate.
func H() Gate {
h := complex(math.Sqrt2/2.0, 0)
return Gate{
data: [][]complex128{
{h, h},
{h, -h},
},
size: 1,
}
}
// P returns the P(phi) Gate.
func P(phi float64) Gate {
return Gate{data: [][]complex128{
{1, 0},
{0, cmplx.Rect(1, phi)},
},
size: 1,
}
}
// S returns the S Gate. Same as P(pi/2).
func S() Gate {
return P(math.Pi / 2.0)
}
// T returns the T gate. Same as P(pi/4).
func T() Gate {
return P(math.Pi / 4.0)
}
// String implements Stringer interface.
func (g Gate) String() string {
return g.ToMat().String()
}