Exemple #1
0
def test_get_unitary(gate: Gate) -> None:
    size = gate.get_size()
    circ = Circ(size, radixes=gate.get_radixes())
    circ.append_gate(gate, list(range(size)))
    num_params = circ.get_num_params()
    x = np.random.random((num_params, ))
    circuit = Circuit(circ)
    assert np.allclose(circ.get_unitary(x).get_numpy(), circuit.get_unitary(x))
Exemple #2
0
def test_minimize_bfgs_multiqubit(r3_qubit_circuit: Circuit) -> None:
    num_params = r3_qubit_circuit.get_num_params()
    x0 = np.random.random((num_params,))
    cost = HilbertSchmidtResidualsGenerator().gen_cost(
        r3_qubit_circuit, r3_qubit_circuit.get_unitary(x0),
    )
    minimizer = CeresMinimizer()
    x = minimizer.minimize(cost, np.random.random((num_params,)))
    assert cost.get_cost(x) < 1e-6, x
Exemple #3
0
def test_minimize_ceres() -> None:
    circ = Circuit(1)
    circ.append_gate(RXGate(), location=[0], params=[0.0])
    xgate = XGate()
    xutry = xgate.get_unitary()
    cost = HilbertSchmidtResidualsGenerator().gen_cost(
        circ, UnitaryMatrix(-1j * xutry.get_numpy()),
    )
    minimizer = CeresMinimizer()
    x = minimizer.minimize(cost, np.array([np.pi / 2]))
    assert cost.get_cost(x) < 1e-6, x
Exemple #4
0
def test_get_grad(gate: Gate) -> None:
    size = gate.get_size()
    circ = Circ(size, radixes=gate.get_radixes())
    circ.append_gate(gate, list(range(size)))
    num_params = circ.get_num_params()
    x = np.random.random((num_params, ))
    circuit = Circuit(circ)
    grad_python = circ.get_grad(x)
    grad_rust = circuit.get_grad(x)
    for py, rs in zip(grad_python, grad_rust):
        assert np.allclose(py, rs)
Exemple #5
0
def test_get_unitary_and_grad(gate: Gate) -> None:
    size = gate.get_size()
    circ = Circ(size, radixes=gate.get_radixes())
    circ.append_gate(gate, list(range(size)))
    num_params = circ.get_num_params()
    x = np.random.random((num_params, ))
    circuit = Circuit(circ)
    utry_python, grad_python = circ.get_unitary_and_grad(x)
    utry_rust, grad_rust = circuit.get_unitary_and_grad(x)
    assert np.allclose(utry_python.get_numpy(), utry_rust)
    for i, (py, rs) in enumerate(zip(grad_python, grad_rust)):
        assert np.allclose(py, rs)
Exemple #6
0
def test_random_circuit_qubit_gates(qubit_gate: Gate) -> None:
    circ = Circ(qubit_gate.get_size())
    circ.append_gate(qubit_gate, location=list(range(qubit_gate.get_size())))
    num_params = circ.get_num_params()
    if qubit_gate.is_constant():
        assert num_params == 0
    x = np.random.random((num_params, ))
    circuit = Circuit(circ)
    py = circ.get_unitary(x).get_numpy()
    rs = circuit.get_unitary(x)
    assert py.shape == rs.shape
    assert py.dtype is rs.dtype
    np.testing.assert_allclose(py, rs, verbose=True)
from __future__ import annotations

from bqskit.compiler.passes.greedypartitioner import GreedyPartitioner
from bqskit.ir import Circuit
from bqskit.ir.gates.constant.cx import CNOTGate

num_q = 5
coup_map = {(0, 1), (1, 2), (2, 3), (3, 4)}
circ = Circuit(num_q)
circ.append_gate(CNOTGate(), [0, 1])
circ.append_gate(CNOTGate(), [3, 4])
circ.append_gate(CNOTGate(), [1, 2])
circ.append_gate(CNOTGate(), [0, 1])
circ.append_gate(CNOTGate(), [2, 3])
circ.append_gate(CNOTGate(), [1, 2])
circ.append_gate(CNOTGate(), [2, 3])
circ.append_gate(CNOTGate(), [3, 2])
circ.append_gate(CNOTGate(), [2, 1])
part = GreedyPartitioner()

print('Num Cycles Before:', circ.get_num_cycles())
print('Num Ops Before:', circ.get_num_operations())

data = {'multi_gate_score': 1, 'single_gate_score': 1}
part.run(circ, data)

# for point, op in circ.operations_with_points():
#     print(op, point)

print('Num Cycles After:', circ.get_num_cycles())
print('Num Ops After:', circ.get_num_operations())
Exemple #8
0
"""This script is contains a simple use case of the QFAST synthesis method."""
from __future__ import annotations

import logging

from scipy.stats import unitary_group

from bqskit.compiler import CompilationTask
from bqskit.compiler import Compiler
from bqskit.compiler.passes.synthesis import QFASTDecompositionPass
from bqskit.ir import Circuit

if __name__ == '__main__':
    # Enable logging
    logging.getLogger('bqskit').setLevel(logging.DEBUG)

    # Let's create a random 3-qubit unitary to synthesize and add it to a
    # circuit.
    circuit = Circuit.from_unitary(unitary_group.rvs(8))

    # We will now define the CompilationTask we want to run.
    task = CompilationTask(circuit, [QFASTDecompositionPass()])

    # Finally let's create create the compiler and execute the CompilationTask.
    with Compiler() as compiler:
        compiled_circuit = compiler.compile(task)
        for op in compiled_circuit:
            print(op)
Exemple #9
0
logging.getLogger('bqskit.compiler').setLevel(logging.DEBUG)

# Let's create a 3-qubit toffoi unitary to synthesize and add it to a circuit.
toffoli = np.array(
    [
        [1, 0, 0, 0, 0, 0, 0, 0],
        [0, 1, 0, 0, 0, 0, 0, 0],
        [0, 0, 1, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0, 0],
        [0, 0, 0, 0, 1, 0, 0, 0],
        [0, 0, 0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 1],
        [0, 0, 0, 0, 0, 0, 1, 0],
    ],
    dtype='complex128',
)

circuit = Circuit.from_unitary(toffoli)

# We will now define the CompilationTask we want to run.
task = CompilationTask(circuit, [QSearchSynthesisPass(success_threshold=1e-9)])

# Finally let's create create the compiler and execute the CompilationTask.
compiler = Compiler()
compiled_circuit = compiler.compile(task)
for op in compiled_circuit:
    print(op)

# Close our connection to the compiler backend
del compiler
Exemple #10
0
"""This script is contains a simple use case of the QFAST synthesis method."""
from __future__ import annotations

import logging

from bqskit.compiler import CompilationTask
from bqskit.compiler import Compiler
from bqskit.compiler.passes.synthesis.qpredict import QPredictDecompositionPass
from bqskit.ir import Circuit
from bqskit.qis.unitary.unitarymatrix import UnitaryMatrix

# Enable logging
logging.getLogger('bqskit').setLevel(logging.DEBUG)

# Let's create a random 3-qubit unitary to synthesize and add it to a circuit.
circuit = Circuit.from_unitary(UnitaryMatrix.random(3))

# We will now define the CompilationTask we want to run.
task = CompilationTask(circuit, [QPredictDecompositionPass()])

# Finally let's create create the compiler and execute the CompilationTask.
compiler = Compiler()
compiled_circuit = compiler.compile(task)
for op in compiled_circuit:
    print(op)

# Close our connection to the compiler backend
del compiler
            circ.append_gate(
                ControlledGate(U1Gate()),
                [
                    k,
                    j,
                ],
                [np.pi / float(2**(k - j))],
            )
    for j in range(int(np.floor(n / 2))):
        circ.append_gate(SwapGate(), [j, n - j - 1])


# QFT 5
num_q = 5
coup_map = make_line(num_q)
circ = Circuit(num_q)
# input_state(circ, num_q)
# qft(circ, num_q)

# Make QFT circuit
circ.append_gate(CNOTGate(), [1, 0])
circ.append_gate(U3Gate(), [0], [0, 0, 7 * pi / 4])
circ.append_gate(CNOTGate(), [1, 0])
circ.append_gate(U3Gate(), [0], [pi / 2, pi / 4, 5 * pi / 4])
circ.append_gate(U3Gate(), [1], [0, 0, pi / 8])
circ.append_gate(CNOTGate(), [1, 2])
circ.append_gate(U3Gate(), [2], [0, 0, 15 * pi / 8])
circ.append_gate(CNOTGate(), [1, 2])
circ.append_gate(U3Gate(), [1], [0, 0, pi / 16])
circ.append_gate(U3Gate(), [2], [0, 0, pi / 8])
circ.append_gate(CNOTGate(), [1, 2])
Exemple #12
0
 def test_one_gate_4(self) -> None:
     circuit = Circuit(3)
     circuit.append_gate(CNOTGate(), (1, 2))
     ops = [op for op in CircuitIterator(circuit)]
     assert len(ops) == 1
     assert ops[0].gate == CNOTGate()  # type: ignore
Exemple #13
0
 def test_one_gate_1(self) -> None:
     circuit = Circuit(1)
     circuit.append_gate(HGate(), 0)
     ops = [op for op in CircuitIterator(circuit)]
     assert len(ops) == 1
     assert ops[0].gate == HGate()  # type: ignore
Exemple #14
0
 def test_empty(self) -> None:
     circuit = Circuit(1)
     ops = [op for op in CircuitIterator(circuit)]
     assert len(ops) == 0
Exemple #15
0
from numpy import pi

from bqskit.compiler.passes.partitioning.scan import ScanPartitioner
from bqskit.compiler.passes.synthesis import LEAPSynthesisPass
from bqskit.compiler.passes.util.variabletou3 import VariableToU3Pass
from bqskit.compiler.search.generators.simple import SimpleLayerGenerator
from bqskit.ir import Circuit
from bqskit.ir.gates import CNOTGate
from bqskit.ir.gates.parameterized.u3 import U3Gate
from bqskit.ir.gates.parameterized.unitary import VariableUnitaryGate

# Enable logging
logging.getLogger('bqskit.compiler').setLevel(logging.DEBUG)

circuit = Circuit(3)
circuit.append_gate(U3Gate(), [0], [pi, pi / 2, pi / 2])
circuit.append_gate(U3Gate(), [1], [pi, pi / 2, pi / 2])
circuit.append_gate(CNOTGate(), [0, 1])
circuit.append_gate(U3Gate(), [2], [pi, pi / 2, pi / 2])
circuit.append_gate(U3Gate(), [0], [pi, pi / 2, pi / 2])
instantiate_options = {
    'min_iters': 0,
    'diff_tol_r': 1e-5,
    'dist_tol': 1e-11,
    'max_iters': 2500,
}
layer_generator = SimpleLayerGenerator(
    single_qudit_gate_1=VariableUnitaryGate(1),
)
synthesizer = LEAPSynthesisPass(
from __future__ import annotations

from bqskit.compiler.machine import MachineModel
from bqskit.compiler.passes.simplepartitioner import SimplePartitioner
from bqskit.ir import Circuit
from bqskit.ir.gates.constant.cx import CNOTGate

#     0  1  2  3           #########
# 0 --o-----o--------    --#-o---o-#-----#######--
# 1 --x--o--x--o-----    --#-x-o-x-#######-o---#--
# 2 -----x--o--x--o-- => --#---x---#---o-#-x-o-#--
# 3 --o-----x-----x--    --#########-o-x-#---x-#--
# 4 --x--------------    ----------#-x---#######--
#                                  #######
num_q = 5
coup_map = {(0, 1), (1, 2), (2, 3), (3, 4)}
circ = Circuit(num_q)
circ.append_gate(CNOTGate(), [0, 1])
circ.append_gate(CNOTGate(), [3, 4])
circ.append_gate(CNOTGate(), [1, 2])
circ.append_gate(CNOTGate(), [0, 1])
circ.append_gate(CNOTGate(), [2, 3])
circ.append_gate(CNOTGate(), [1, 2])
circ.append_gate(CNOTGate(), [2, 3])
mach = MachineModel(num_q, coup_map)
part = SimplePartitioner(mach, 3)

part.run(circ, {})