Quantum Computing Asked on May 6, 2021
Is it possible to implement a quantum gate from a matrix in Q#, the equivalent of unitary function in Qiskit ? My final goal is to implement cirq CZPowGate in Q#.
Thank you.
There's a feature request for a Q# operation to apply an arbitrary unitary operation given its representation as a matrix; if you're interested, please go on and leave a comment on that request!
In the meantime, though, it's actually really straightforward to implement the same unitary operation as cirq.CZPowGate
in Q#.
open Microsoft.Quantum.Math as Math;
operation ApplyCZPow(t : Double, control : Qubit, target : Qubit) : Unit is Adj + Ctl {
Controlled R1([control], (t * Math.PI(), target));
}
This uses the R1
operation provided with the Microsoft.Quantum.Intrinsic namespace together with the Controlled
keyword to apply the same rotation as cirq.CZPowGate
.
To see how this works, note that as per the Cirq documentation for CZPowGate, that instruction is represented by the unitary matrix
$$
U_{text{CZPowGate}}(t) = left(begin{matrix}
1 & 0 & 0 & 0
0 & 1 & 0 & 0
0 & 0 & 1 & 0
0 & 0 & 0 & e^{i pi t}
end{matrix}right).
$$
This is a special case of a controlled operation with a single control qubit, as it has the pattern
$$
Lambda(U) = left(begin{matrix}
? & 0
0 & U
end{matrix}right) = |0ranglelangle0| otimes ? + |1ranglelangle1| otimes U
$$
for some unitary matrix $U$. In particular, $U$ in this case represents a rotation that leaves the $|0rangle$ state alone but that applies a phase to the $|1rangle$ state; precisely the action of the R1
operation.
In Q#, the Controlled
keyword can be used to get the controlled version of any controllable operation (that is, an operation with is Ctl
in its signature). Each Controlled
operation takes as its first input an array of controls, and takes all of the original inputs to the uncontrolled operation as the second input. For example, CNOT(control, target)
in Q# is shorthand for Controlled X([control], target)
.
Similarly, a Toffoli in Q# can be written as Controlled X([control1, control2], target)
and the Fredkin operation can be written as Controlled SWAP([control], (target1, target2))
.
Using the same pattern here works since R1
is a controllable operation. We can check that we get what we expect by using the Microsoft.Quantum.Diagnostics.DumpOperation
operation to check the unitary representation of our new ApplyCZPow
operation (run online without installing):
open Microsoft.Quantum.Diagnostics as Diag;
operation DumpApplyCZPow(t : Double) : Unit {
Diag.DumpOperation(2, ApplyToFirstTwoQubitsCA(ApplyCZPow(t, _, _), _));
}
Correct answer by Chris Granade on May 6, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP