def test_simulator_cheat(sim):
    # cheat function should return a tuple
    assert isinstance(sim.cheat(), tuple)
    # first entry is the qubit mapping.
    # should be empty:
    assert len(sim.cheat()[0]) == 0

    np = MPI.COMM_WORLD.Get_size()
    # state vector should only have np entries:
    assert len(sim.cheat()[1]) == np

    eng = HiQMainEngine(sim, [GreedyScheduler()])
    qubit = eng.allocate_qubit()

    # one qubit has been allocated
    assert len(sim.cheat()[0]) == 1
    assert sim.cheat()[0][0] == 0
    assert len(sim.cheat()[1]) == 2 * np
    assert 1. == pytest.approx(abs(sim.cheat()[1][0]))

    qubit[0].__del__()
    eng.flush()

    # should be empty:
    assert len(sim.cheat()[0]) == 0
    # state vector should only have np entries:
    assert len(sim.cheat()[1]) == np
def test_simulator_no_uncompute_exception(sim):
    eng = HiQMainEngine(sim, [GreedyScheduler()])
    qubit = eng.allocate_qubit()
    H | qubit
    with pytest.raises(RuntimeError):
        qubit[0].__del__()
        eng.flush()
    # If you wanted to keep using the qubit, you shouldn't have deleted it.
    assert qubit[0].id == -1
def test_simulator_kqubit_exception(sim):
    m1 = Rx(0.3).matrix
    m2 = Rx(0.8).matrix
    m3 = Ry(0.1).matrix
    m4 = Rz(0.9).matrix.dot(Ry(-0.1).matrix)
    m = numpy.kron(m4, numpy.kron(m3, numpy.kron(m2, m1)))

    class KQubitGate(BasicGate):
        @property
        def matrix(self):
            return m

    eng = HiQMainEngine(sim, [GreedyScheduler()])
    qureg = eng.allocate_qureg(3)
    with pytest.raises(Exception):
        KQubitGate() | qureg
        eng.flush()
    with pytest.raises(Exception):
        H | qureg
        eng.flush()
def test_simulator_measure_mapped_qubit(sim):
    eng = HiQMainEngine(sim, [GreedyScheduler()])
    qb1 = WeakQubitRef(engine=eng, idx=1)
    qb2 = WeakQubitRef(engine=eng, idx=2)
    cmd0 = Command(engine=eng, gate=Allocate, qubits=([qb1], ))
    cmd1 = Command(engine=eng, gate=X, qubits=([qb1], ))
    cmd2 = Command(engine=eng,
                   gate=Measure,
                   qubits=([qb1], ),
                   controls=[],
                   tags=[LogicalQubitIDTag(2)])
    with pytest.raises(NotYetMeasuredError):
        int(qb1)
    with pytest.raises(NotYetMeasuredError):
        int(qb2)
    eng.send([cmd0, cmd1, cmd2])
    eng.flush()
    with pytest.raises(NotYetMeasuredError):
        int(qb1)
    assert int(qb2) == 1
def test_simulator_collapse_wavefunction(sim, mapper):
    engine_list = [LocalOptimizer()]
    if mapper is not None:
        engine_list.append(mapper)

    engine_list.append(GreedyScheduler())
    eng = HiQMainEngine(sim, engine_list=engine_list)
    qubits = eng.allocate_qureg(4)
    # unknown qubits: raises
    with pytest.raises(RuntimeError):
        eng.backend.collapse_wavefunction(qubits, [0] * 4)
    eng.flush()
    eng.backend.collapse_wavefunction(qubits, [0] * 4)
    assert pytest.approx(eng.backend.get_probability([0] * 4, qubits)) == 1.
    All(H) | qubits[1:]
    eng.flush()
    assert pytest.approx(eng.backend.get_probability([0] * 4, qubits)) == .125
    # impossible outcome: raises
    with pytest.raises(RuntimeError):
        eng.backend.collapse_wavefunction(qubits, [1] + [0] * 3)
    eng.backend.collapse_wavefunction(qubits[:-1], [0, 1, 0])
    probability = eng.backend.get_probability([0, 1, 0, 1], qubits)
    assert probability == pytest.approx(.5)

    # reinitialize qubits
    All(Measure) | qubits
    del qubits
    qubits = eng.allocate_qureg(4)

    H | qubits[0]
    CNOT | (qubits[0], qubits[1])
    eng.flush()
    eng.backend.collapse_wavefunction([qubits[0]], [1])
    probability = eng.backend.get_probability([1, 1], qubits[0:2])
    assert probability == pytest.approx(1.)
def test_simulator_probability(sim, mapper):
    engine_list = [LocalOptimizer()]
    if mapper is not None:
        engine_list.append(mapper)

    engine_list.append(GreedyScheduler())
    eng = HiQMainEngine(sim, engine_list=engine_list)
    qubits = eng.allocate_qureg(6)
    All(H) | qubits
    eng.flush()
    bits = [0, 0, 1, 0, 1, 0]
    for i in range(6):
        assert (eng.backend.get_probability(
            bits[:i], qubits[:i]) == pytest.approx(0.5**i))
    extra_qubit = eng.allocate_qubit()
    with pytest.raises(RuntimeError):
        eng.backend.get_probability([0], extra_qubit)
    del extra_qubit
    All(H) | qubits
    Ry(2 * math.acos(math.sqrt(0.3))) | qubits[0]
    eng.flush()
    assert eng.backend.get_probability([0], [qubits[0]]) == pytest.approx(0.3)
    Ry(2 * math.acos(math.sqrt(0.4))) | qubits[2]
    eng.flush()
    assert eng.backend.get_probability([0], [qubits[2]]) == pytest.approx(0.4)
    assert (eng.backend.get_probability([0, 0],
                                        qubits[:3:2]) == pytest.approx(0.12))
    assert (eng.backend.get_probability([0, 1],
                                        qubits[:3:2]) == pytest.approx(0.18))
    assert (eng.backend.get_probability([1, 0],
                                        qubits[:3:2]) == pytest.approx(0.28))
    All(Measure) | qubits
def test_simulator_kqubit_gate(sim):
    m1 = Rx(0.3).matrix
    m2 = Rx(0.8).matrix
    m3 = Ry(0.1).matrix
    m4 = Rz(0.9).matrix.dot(Ry(-0.1).matrix)
    m = numpy.kron(m4, numpy.kron(m3, numpy.kron(m2, m1)))

    class KQubitGate(BasicGate):
        @property
        def matrix(self):
            return m

    eng = HiQMainEngine(sim, [GreedyScheduler()])
    qureg = eng.allocate_qureg(4)
    qubit = eng.allocate_qubit()
    Rx(-0.3) | qureg[0]
    Rx(-0.8) | qureg[1]
    Ry(-0.1) | qureg[2]
    Rz(-0.9) | qureg[3]
    Ry(0.1) | qureg[3]
    X | qubit
    with Control(eng, qubit):
        KQubitGate() | qureg
    X | qubit
    with Control(eng, qubit):
        with Dagger(eng):
            KQubitGate() | qureg
    assert sim.get_amplitude('0' * 5, qubit + qureg) == pytest.approx(1.)

    class LargerGate(BasicGate):
        @property
        def matrix(self):
            return numpy.eye(2**6)

    with pytest.raises(Exception):
        LargerGate() | (qureg + qubit)
        eng.flush()
def test_simulator_functional_entangle(sim):
    eng = HiQMainEngine(sim, [GreedyScheduler()])
    qubits = eng.allocate_qureg(5)
    # entangle all qubits:
    H | qubits[0]
    for qb in qubits[1:]:
        CNOT | (qubits[0], qb)

    eng.flush()

    id2pos, vec = sim.cheat()

    # check the state vector:
    assert .5 == pytest.approx(abs(vec[0])**2)  # amplitudes 00000 and 11111
    assert .5 == pytest.approx(abs(
        vec[31])**2)  # are never moved even if qubit reordering made
    for i in range(1, 31):
        assert 0. == pytest.approx(abs(vec[i]))

    # unentangle all except the first 2
    for qb in qubits[2:]:
        CNOT | (qubits[0], qb)

    # entangle using Toffolis
    for qb in qubits[2:]:
        Toffoli | (qubits[0], qubits[1], qb)

    eng.flush()

    # check the state vector:
    id2pos, vec = sim.cheat()
    assert .5 == pytest.approx(abs(vec[0])**2)
    assert .5 == pytest.approx(abs(vec[31])**2)
    for i in range(1, 31):
        assert 0. == pytest.approx(abs(vec[i]))

    # uncompute using multi-controlled NOTs
    with Control(eng, qubits[0:-1]):
        X | qubits[-1]
    with Control(eng, qubits[0:-2]):
        X | qubits[-2]
    with Control(eng, qubits[0:-3]):
        X | qubits[-3]
    CNOT | (qubits[0], qubits[1])
    H | qubits[0]

    eng.flush()

    id2pos, vec = sim.cheat()

    # check the state vector:
    assert 1. == pytest.approx(abs(vec[0])**2)
    for i in range(1, 32):
        assert 0. == pytest.approx(abs(vec[i]))

    All(Measure) | qubits
def test_simulator_amplitude(sim, mapper):
    engine_list = [LocalOptimizer()]
    if mapper is not None:
        engine_list.append(mapper)

    engine_list.append(GreedyScheduler())
    eng = HiQMainEngine(sim, engine_list=engine_list)
    qubits = eng.allocate_qureg(6)
    All(X) | qubits
    All(H) | qubits
    eng.flush()
    bits = [0, 0, 1, 0, 1, 0]
    assert eng.backend.get_amplitude(bits, qubits) == pytest.approx(1. / 8.)
    bits = [0, 0, 0, 0, 1, 0]
    assert eng.backend.get_amplitude(bits, qubits) == pytest.approx(-1. / 8.)
    bits = [0, 1, 1, 0, 1, 0]
    assert eng.backend.get_amplitude(bits, qubits) == pytest.approx(-1. / 8.)
    All(H) | qubits
    All(X) | qubits
    Ry(2 * math.acos(0.3)) | qubits[0]
    eng.flush()
    bits = [0] * 6
    assert eng.backend.get_amplitude(bits, qubits) == pytest.approx(0.3)
    bits[0] = 1
    assert (eng.backend.get_amplitude(bits, qubits) == pytest.approx(
        math.sqrt(0.91)))
    All(Measure) | qubits
    # raises if not all qubits are in the list:
    with pytest.raises(RuntimeError):
        eng.backend.get_amplitude(bits, qubits[:-1])
    # doesn't just check for length:
    with pytest.raises(RuntimeError):
        eng.backend.get_amplitude(bits, qubits[:-1] + [qubits[0]])
    extra_qubit = eng.allocate_qubit()
    eng.flush()
    # there is a new qubit now!
    with pytest.raises(RuntimeError):
        eng.backend.get_amplitude(bits, qubits)
Esempio n. 10
0
        phase_reg = eng.allocate_qureg(3)

        #initialize the ancilla and weight qubits
        X | ancilla_qubit
        H | ancilla_qubit

        All(H) | layer1_weight_reg
        All(H) | layer2_weight_reg

        #run the training cycle, one should adjust the number of loops and run the whole program again to get results for different iterations
        with Loop(eng, 2):
            run_qbnn(eng)

        H | ancilla_qubit
        X | ancilla_qubit

        All(Measure) | layer1_weight_reg
        All(Measure) | layer2_weight_reg

        eng.flush()

        print(
            "==========================================================================="
        )
        print("This is the QBNN demo")
        print("The measured weight string is")
print(int(layer1_weight_reg[0]), int(layer1_weight_reg[1]),
      int(layer1_weight_reg[2]), int(layer1_weight_reg[3]),
      int(layer1_weight_reg[4]), int(layer1_weight_reg[5]),
      int(layer2_weight_reg[0]), int(layer2_weight_reg[1]))
Esempio n. 11
0
def run_qecc9():

    #init simulator
    simulator = StabilizerSimulator(12)
    eng = HiQMainEngine(simulator, [])

    #allocate
    qubits = eng.allocate_qureg(12)

    #start
    print("= Encoded the qubit, state is: |0>")
    #circuit
    CNOT | (qubits[0], qubits[3])
    CNOT | (qubits[3], qubits[0])

    CNOT | (qubits[3], qubits[6])
    CNOT | (qubits[3], qubits[9])
    H | qubits[3]
    CNOT | (qubits[3], qubits[4])
    CNOT | (qubits[3], qubits[5])
    H | qubits[6]
    CNOT | (qubits[6], qubits[7])
    CNOT | (qubits[6], qubits[8])
    H | qubits[9]
    CNOT | (qubits[9], qubits[10])
    CNOT | (qubits[9], qubits[11])

    H | qubits[3]
    H | qubits[4]
    H | qubits[5]
    H | qubits[6]
    H | qubits[7]
    H | qubits[8]
    H | qubits[9]
    H | qubits[10]
    H | qubits[11]
    CNOT | (qubits[1], qubits[3])
    CNOT | (qubits[1], qubits[4])
    CNOT | (qubits[1], qubits[5])
    CNOT | (qubits[1], qubits[6])
    CNOT | (qubits[1], qubits[7])
    CNOT | (qubits[1], qubits[8])
    CNOT | (qubits[1], qubits[9])
    CNOT | (qubits[1], qubits[10])
    CNOT | (qubits[1], qubits[11])
    H | qubits[3]
    H | qubits[4]
    H | qubits[5]
    H | qubits[6]
    H | qubits[7]
    H | qubits[8]
    H | qubits[9]
    H | qubits[10]
    H | qubits[11]

    CNOT | (qubits[2], qubits[3])
    CNOT | (qubits[2], qubits[4])
    CNOT | (qubits[2], qubits[5])
    CNOT | (qubits[2], qubits[6])
    CNOT | (qubits[2], qubits[7])
    CNOT | (qubits[2], qubits[8])
    CNOT | (qubits[2], qubits[9])
    CNOT | (qubits[2], qubits[10])
    CNOT | (qubits[2], qubits[11])

    CNOT | (qubits[9], qubits[11])
    CNOT | (qubits[9], qubits[10])
    H | qubits[9]
    CNOT | (qubits[6], qubits[8])
    CNOT | (qubits[6], qubits[7])
    H | qubits[6]
    CNOT | (qubits[3], qubits[5])
    CNOT | (qubits[3], qubits[4])
    H | qubits[3]
    CNOT | (qubits[3], qubits[9])
    CNOT | (qubits[3], qubits[6])

    Measure | qubits[3]
    #flush
    eng.flush()

    print("= Decoded the qubit, state is: |{}>".format(int(qubits[3])))
Esempio n. 12
0
rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
engines = [
    TagRemover(),
    LocalOptimizer(cache_depth),
    AutoReplacer(rule_set),
    TagRemover(),
    LocalOptimizer(cache_depth),
    GreedyScheduler()
]

# create a list of restriction engines
restric_engine = restrictedgateset.get_engine_list(one_qubit_gates=(X, Y, Z, H,
                                                                    S, T, Rx,
                                                                    Ry, Rz),
                                                   two_qubit_gates=(CZ, CX))

eng = HiQMainEngine(backend,
                    engine_list=restric_engine + engines + [CommandPrinter()])
qureg = eng.allocate_qureg(2)

H | qureg[0]
with Control(eng, qureg[0]):
    Rx(np.pi / 2) | qureg[1]
eng.flush(
)  # In order to have all the above gates sent to the simulator and executed
mapping, wavefunc = copy.deepcopy(eng.backend.cheat())

All(Measure) | qureg

print(wavefunc)
print(mapping)