def run_single_algorithm(algorithm, num_qubits, num_samples=8000):
    """
    Create a quantum circuit, run the algorithm, return the resulting
    probability distribution.
    
    algorithm: algorithm (list of strings), 
               each string is a gate, ie "cx(0, 1)" or "rx(pi/2, 0)"
    num_qubits: int, number of qubits to run each algorithm on. Can be None,
                     in which case the algorithm will be run on the minimum
                     number of qubits required.
    num_samples: int, number of samples to take from the quantum computer in
                      in order to determine the probabilities for each state.
                  
    returns: dict (common.Result), keys are states, values are probabilities 
                                   found to be in that state.
    """

    eng = MainEngine()
    qureg = eng.allocate_qureg(num_qubits)
    measure = []
    for gate in algorithm:
        if "measure" not in gate.lower(): apply_gate(gate, qureg)
        else:
            _, gate_args = get_gate_info(gate)
            measure.append(gate_args[0])
    if not measure: measure = list(range(num_qubits))
    eng.flush()

    to_measure = [qureg[i] for i in measure]

    #TODO: find supported projectq way to do this with out iterating O(2^n)!
    res = {}
    for x in range(2**len(measure)):
        state = ("{0:0%db}" % len(to_measure)).format(x)
        res[state] = eng.backend.get_probability(state, to_measure)

    # so projectq doesn't throw an error
    ops.All(ops.Measure) | qureg

    # To have a realistic simulator, we need to sample, not just return the
    # probabilities.
    samples = {}

    for _ in range(num_samples):
        r = random.random()
        for state, prob in res.items():
            r -= prob
            if r <= 0:
                if state in samples: samples[state] += 1
                else: samples[state] = 1
                break

    return Result(
        {state: counts / num_samples
         for state, counts in samples.items()})
def createProgram(qubits, inputValue, errorIdxs):
    PrepareState(qubits, inputValue)

    PhaseFlipEncode(qubits, [0, 3, 6])
    BitFlipEncode(qubits, [0, 1, 2])
    BitFlipEncode(qubits, [3, 4, 5])
    BitFlipEncode(qubits, [6, 7, 8])

    ErrorIntroduction(qubits, errorIdxs)

    BitFlipDecode(qubits, [0, 1, 2])
    BitFlipDecode(qubits, [3, 4, 5])
    BitFlipDecode(qubits, [6, 7, 8])
    PhaseFlipDecode(qubits, [0, 3, 6])

    ops.Measure | qubits[
        0]  # Only the first bit is of importance. All others are to encode the state
    ops.All(ops.Measure) | qubits[1:]  # All other qubits should be zero

    return qubits
Exemple #3
0
def test_Measure(benchmark, nqubits):
    benchmark.group = "Measure"
    run_bench(benchmark, ops.All(ops.Measure), None, nqubits)