|
| 1 | +# Copyright 2023 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import itertools |
| 15 | + |
| 16 | +import cirq |
| 17 | + |
| 18 | +from qualtran import BloqBuilder |
| 19 | +from qualtran.bloqs.basic_gates import TGate, Toffoli, ZeroState |
| 20 | +from qualtran.resource_counting import get_bloq_counts_graph |
| 21 | + |
| 22 | + |
| 23 | +def _make_Toffoli(): |
| 24 | + from qualtran.bloqs.basic_gates import Toffoli |
| 25 | + |
| 26 | + return Toffoli() |
| 27 | + |
| 28 | + |
| 29 | +def test_toffoli_t_count(): |
| 30 | + counts = Toffoli().bloq_counts() |
| 31 | + assert counts == {(4, TGate())} |
| 32 | + |
| 33 | + _, sigma = get_bloq_counts_graph(Toffoli()) |
| 34 | + assert sigma == {TGate(): 4} |
| 35 | + |
| 36 | + |
| 37 | +def test_toffoli_cirq(): |
| 38 | + bb = BloqBuilder() |
| 39 | + c0, c1, trg = [bb.add(ZeroState()) for _ in range(3)] |
| 40 | + ctrl, target = bb.add(Toffoli(), ctrl=[c0, c1], target=trg) |
| 41 | + ctrl, target = bb.add(Toffoli(), ctrl=ctrl, target=target) |
| 42 | + cbloq = bb.finalize(q0=ctrl[0], q1=ctrl[1], q2=target) |
| 43 | + |
| 44 | + circuit, qubits = cbloq.to_cirq_circuit() |
| 45 | + cirq.testing.assert_has_diagram( |
| 46 | + circuit, |
| 47 | + """\ |
| 48 | +_c(0): ───@───@─── |
| 49 | + │ │ |
| 50 | +_c(1): ───@───@─── |
| 51 | + │ │ |
| 52 | +_c(2): ───X───X───""", |
| 53 | + ) |
| 54 | + |
| 55 | + |
| 56 | +def test_classical_sim(): |
| 57 | + tof = Toffoli() |
| 58 | + |
| 59 | + for c0, c1 in itertools.product([0, 1], repeat=2): |
| 60 | + ctrl, target = tof.call_classically(ctrl=[c0, c1], target=0) |
| 61 | + assert ctrl.tolist() == [c0, c1] |
| 62 | + if c0 == 1 and c1 == 1: |
| 63 | + assert target == 1 |
| 64 | + else: |
| 65 | + assert target == 0 |
| 66 | + |
| 67 | + |
| 68 | +def test_classical_sim_2(): |
| 69 | + bb = BloqBuilder() |
| 70 | + c0, c1, trg = [bb.add(ZeroState()) for _ in range(3)] |
| 71 | + ctrl, target = bb.add(Toffoli(), ctrl=[c0, c1], target=trg) |
| 72 | + ctrl, target = bb.add(Toffoli(), ctrl=ctrl, target=target) |
| 73 | + cbloq = bb.finalize(q0=ctrl[0], q1=ctrl[1], q2=target) |
| 74 | + |
| 75 | + b0, b1, b2 = cbloq.call_classically() |
| 76 | + assert b0 == 0 |
| 77 | + assert b1 == 0 |
| 78 | + assert b2 == 0 |
0 commit comments