Esempio n. 1
0
def period_finder(n: int, x: int) -> int:
    """
    Solves the period finding problem.

    :param n: (int) the integer to be factoring
    :param x: (int) the random number used to solve the period finding problem

    :return: (int) the period of the function f: a -> x^a mod n
    """

    # Create the job using the above function
    job = build_quantum_program(n, x)

    # Initialize the quantum simulator
    qpu = PyLinalg()

    # The probability to find the right period with Shor's algorithm is greater than 1/2, so we execute the quantum
    # program until to find a consistent period
    while True:
        # If the period found by Shor's quantum algorithm is wrong then an exception is raised
        try:
            # Submit the job and retrieve the result
            measure = qpu.submit(job)

            # Extract the period from the measurement
            r = continued_fraction_expansion(n, measure.raw_data[0].state.int,
                                             int(np.trunc(np.log2(n**2))) + 1)

            # Check the period is valid
            if x**r % n == 1:
                return r

        # A ValueError exception has been caught which means the period is not extractable from the previous measurement
        except ValueError:
            continue
def main():
    # _a is for Alice, _b is for Bob, _c is for classical
    pr = Program()
    to_teleport = pr.qalloc()
    epr_pair_a = pr.qalloc()
    epr_pair_a_c = pr.calloc()
    to_teleport_c = pr.calloc()
    epr_pair_b = pr.qalloc()

    # Prepare EPR pair
    pr.apply(H, *epr_pair_a)
    pr.apply(CNOT, *epr_pair_a, *epr_pair_b)
    # Now Alice has her half of the EPR pair (epr_pair_a) and Bob the other one
    # (epr_pair_b qubit)

    # Prepare random state on the qubit(s) to teleport
    pr.apply(RY(random() * pi), *to_teleport)
    pr.apply(RX(random() * pi), *to_teleport)
    pr.apply(RZ(random() * pi), *to_teleport)

    # At this point we make a copy of the original program. The idea is to show
    # the state we would obtain if we would stop at this stage, before the
    # teleportation.
    pr2 = deepcopy(pr)

    # We continue with the teleportation circuit

    # Alice interact her to_teleport_qubit with her half of the EPR pair
    pr.apply(CNOT, *to_teleport, *epr_pair_a)
    pr.apply(H, *to_teleport)
    # ... and then she measures her 2 qubits
    pr.measure(to_teleport, to_teleport_c)
    pr.measure(epr_pair_a, epr_pair_a_c)

    # She then sends her measured qubits to Bob which, depending on their value
    # being 0 or 1, performs the classically controlled X and Z on his own half of the EPR pair
    pr.cc_apply(epr_pair_a_c[0], X, epr_pair_b[0])
    pr.cc_apply(to_teleport_c[0], Z, epr_pair_b[0])

    #
    circ = pr.to_circ()
    circ2 = pr2.to_circ()

    # simulation
    qpu = PyLinalg()
    res = qpu.submit(circ.to_job(qubits=[epr_pair_b]))
    res2 = qpu.submit(circ2.to_job(qubits=[to_teleport]))

    print("Original state, measured on to_teleport qubit")
    for sample in res2:
        # print(f"state {sample.state} with amplitude {sample.amplitude} and probability {sample.probability}")
        print(f"state {sample.state} with amplitude {sample.probability}")
    print("Teleported state, measured on ")
    for sample in res:
        print(f"state {sample.state} with probability {sample.probability}")
def test_teleportation():
    """
    Checks the output of the teleportation
    """
    # Generate two circuits
    for circ in [generate_teleportation(True),
                 generate_teleportation(False)] * 10:
        # Submit teleportation circuit to PyLinalg
        result = PyLinalg().submit(circ.to_job())

        # Init expected result
        amplitude_zero = -0.5319070945531361 - 0.6198336118074692j
        amplitude_one = 0.4378426919829602 + 0.3757325026063933j

        # Check result
        assert len(result) == 2

        for sample in result:
            # If last qubit is 1
            if sample.state.int & 1:
                assert sample.amplitude == pytest.approx(amplitude_one)

            # If last qubit is 0
            else:
                assert sample.amplitude == pytest.approx(amplitude_zero)
def test_multiple_measurements():
    """
    Submit a circuit composed to 2 intermediate measurements
    """
    # Build a program
    prog = Program()
    qbits = prog.qalloc(2)
    cbits = prog.calloc(2)
    prog.apply(X, qbits[0])
    prog.measure(qbits, cbits)
    prog.apply(CNOT, qbits)
    prog.measure(qbits, cbits)

    circ = prog.to_circ()

    # Submit circuit
    result = PyLinalg().submit(circ.to_job())

    # Check result
    assert len(result) == 1
    sample = result.raw_data[0]
    assert sample.state.int == 3

    # Check intermediate measurements
    assert len(sample.intermediate_measurements) == 2
    assert sample.intermediate_measurements[0].cbits == [True, False]
    assert sample.intermediate_measurements[1].cbits == [True, True]
class OracleDeutschJozsaTest(unittest.TestCase):
    qpu = PyLinalg()

    def test_balanced(self):
        max_qubit = 6
        for n in range(1, max_qubit + 1):
            with self.subTest(n=n):
                # It also creates an additional qubit for output
                oracle = BalancedOracle(n)

                count1 = 0
                for i in range(2**n):
                    pr = Program()
                    qreg = pr.qalloc(n)
                    qout = pr.qalloc(1)

                    qr_init = initialize_qureg_given_int(i, qreg, False)
                    pr.apply(qr_init, qreg)
                    pr.apply(oracle.generate(), [*qreg, *qout])
                    # display(pr.to_circ())

                    # res = self.qpu.submit(pr.to_circ().to_job())
                    # for sample in res:
                    #     print(sample.state, sample.probability)

                    res = self.qpu.submit(pr.to_circ().to_job(qubits=[qout]))
                    self.assertEqual(len(res.raw_data), 1)
                    sample = res.raw_data[0]
                    if sample.state.state == 1:
                        count1 += 1

                self.assertEqual(count1, 2**(n - 1))
Esempio n. 6
0
def main():
    qpu = PyLinalg()
    namespace = parse_arguments()
    print(namespace)
    alg = TeleportationAlgorithm
    pr, meas_qbits = alg.generate_program(namespace.n)
    ress = alg.simulate_program(pr, qpu)
    for res in ress:
        print(res.state, res.probability)
    print("***")
Esempio n. 7
0
def main():
    qpu = PyLinalg()
    namespace = parse_arguments()
    print(namespace)

    if not namespace.bitstring:
        namespace.bitstring = bin(random.getrandbits(namespace.n))[2:].zfill(
            namespace.n)
    print(f"String {namespace.bitstring} ")

    algs_oracles = [
        (DeutschJozsaAlgorithm, COra(namespace.n), {}),
        (DeutschJozsaAlgorithm, BOra(namespace.n), {}),
        (BernsteinVaziraniAlgorithm, BPOra(namespace.n), {
            "s": namespace.bitstring
        }),
        (GroverAlgorithm, FSOra(namespace.n), {
            "s": namespace.bitstring
        }),
    ]

    for alg, oracle, kwargs in algs_oracles:
        print(alg)
        print(oracle)
        print(kwargs)
        oracle_rout = oracle.generate(**kwargs)
        pr, meas_qbits = alg.generate_program(namespace.n, oracle_rout)
        cr = pr.to_circ()
        if namespace.display:
            display(cr)
        # High amp_threshold, but it's fine for our oracles
        ress = alg.simulate_program(pr,
                                    qpu,
                                    job_args={
                                        'qubits': meas_qbits,
                                        'amp_threshold': 1e-1
                                    })
        for res in ress:
            print(res.state, res.probability)
        print("***")
def test_reset():
    """
    Check the reset gate
    """
    # Define a program
    prog = Program()
    qbits = prog.qalloc(2)
    prog.apply(X, qbits[0])
    prog.reset(qbits)
    circ = prog.to_circ()

    # Submit circuit
    result = PyLinalg().submit(circ.to_job())

    # Check result
    assert len(result) == 1
    sample = result.raw_data[0]
    assert sample.state.int == 0

    # Check intermediate measurements
    assert len(sample.intermediate_measurements) == 1
    print(sample.intermediate_measurements)
    assert sample.intermediate_measurements[0].cbits == [True, False]
Esempio n. 9
0
from qat.qpus import PyLinalg

# Create a Program
qprog = Program()
# Number of qbits
nbqbits = 2
# Allocate some qbits
qbits = qprog.qalloc(nbqbits)

# Apply some quantum Gates
qprog.apply(H, qbits[0])
qprog.apply(CNOT, qbits[0], qbits[1])

print(qprog)

# Export this program into a quantum circuit
circuit = qprog.to_circ()

# Create a Quantum Processor Unit
linalgqpu = PyLinalg()

# Create a job
job = circuit.to_job()

# Submit the job to the QPU
result = linalgqpu.submit(job)

# Iterate over the final state vector to get all final components
for sample in result:
    print("State %s amplitude %s" % (sample.state, sample.amplitude))
Esempio n. 10
0
def mean_op(op, circuit):
    qpu = LinAlg()
    job = circuit.to_job("OBS", observable=op)
    res = qpu.submit(job).value
    return res