Ejemplo n.º 1
0
def test_measure_bitstrings(forest):
    device = NxDevice(nx.complete_graph(2))
    qc_pyqvm = QuantumComputer(name="testy!",
                               qam=PyQVM(n_qubits=2),
                               device=device,
                               compiler=DummyCompiler())
    qc_forest = QuantumComputer(
        name="testy!",
        qam=QVM(connection=forest, gate_noise=[0.00] * 3),
        device=device,
        compiler=DummyCompiler(),
    )
    prog = Program(I(0), I(1))
    meas_qubits = [0, 1]
    sym_progs, flip_array = _symmetrization(prog, meas_qubits, symm_type=-1)
    results = _measure_bitstrings(qc_pyqvm,
                                  sym_progs,
                                  meas_qubits,
                                  num_shots=1)
    # test with pyQVM
    answer = [
        np.array([[0, 0]]),
        np.array([[0, 1]]),
        np.array([[1, 0]]),
        np.array([[1, 1]])
    ]
    assert all([np.allclose(x, y) for x, y in zip(results, answer)])
    # test with regular QVM
    results = _measure_bitstrings(qc_forest,
                                  sym_progs,
                                  meas_qubits,
                                  num_shots=1)
    assert all([np.allclose(x, y) for x, y in zip(results, answer)])
Ejemplo n.º 2
0
def test_pyquil_program():
    """Tests if the Dynamic Decoupling Sequence gives rise to Identity
    operation in PyQuil
    """
    _duration = 5e-6
    _offsets = [0, 1e-6, 2.5e-6, 4e-6, 5e-6]
    _rabi_rotations = [np.pi / 2, np.pi / 2, np.pi, 0, np.pi / 2]
    _azimuthal_angles = [0, 0, np.pi / 2, 0, 0]
    _detuning_rotations = [0, 0, 0, np.pi, 0]

    sequence = DynamicDecouplingSequence(
        duration=_duration,
        offsets=_offsets,
        rabi_rotations=_rabi_rotations,
        azimuthal_angles=_azimuthal_angles,
        detuning_rotations=_detuning_rotations)

    program = convert_dds_to_pyquil_program(sequence, [0], gate_time=1e-6)

    assert len(program) == 13
    assert program[0] == Pragma("PRESERVE_BLOCK")
    assert program[-1] == Pragma("END_PRESERVE_BLOCK")
    assert program[1] == RX(np.pi / 2, 0)
    assert program[2] == I(0)
    assert program[3] == RX(np.pi / 2, 0)
    assert program[4] == I(0)
    assert program[5] == RY(np.pi, 0)
    assert program[6] == I(0)
    assert program[7] == RZ(np.pi, 0)
    assert program[8] == I(0)
    assert program[9] == RX(np.pi / 2, 0)
Ejemplo n.º 3
0
def test_readout_symmetrization(client_configuration: QCSClientConfiguration):
    quantum_processor = NxQuantumProcessor(nx.complete_graph(3))
    noise_model = decoherence_noise_with_asymmetric_ro(quantum_processor.to_compiler_isa())
    qc = QuantumComputer(
        name="testy!",
        qam=QVM(client_configuration=client_configuration, noise_model=noise_model),
        compiler=DummyCompiler(quantum_processor=quantum_processor, client_configuration=client_configuration),
    )

    prog = Program(
        Declare("ro", "BIT", 2),
        I(0),
        X(1),
        MEASURE(0, MemoryReference("ro", 0)),
        MEASURE(1, MemoryReference("ro", 1)),
    )
    prog.wrap_in_numshots_loop(1000)

    bs1 = qc.run(prog)
    avg0_us = np.mean(bs1[:, 0])
    avg1_us = 1 - np.mean(bs1[:, 1])
    diff_us = avg1_us - avg0_us
    assert diff_us > 0.03

    prog = Program(
        I(0),
        X(1),
    )
    bs2 = qc.run_symmetrized_readout(prog, 1000)
    avg0_s = np.mean(bs2[:, 0])
    avg1_s = 1 - np.mean(bs2[:, 1])
    diff_s = avg1_s - avg0_s
    assert diff_s < 0.05
Ejemplo n.º 4
0
def getFile(f):
    del states[:]
    del rhythm[:]
    file = open(askopenfilename(), "r")
    for line in file:
        p = Program()
        p.inst(I(0)) if line[2] == "0" else p.inst(X(0))
        p.inst(I(1)) if line[1] == "0" else p.inst(X(1))
        p.inst(I(2)) if line[0] == "0" else p.inst(X(2))
        rhythm.append(float(line[4:])) if len(line) >= 5 else rhythm.append(1)
        states.append(p)
    for i in range(0, len(states)):
        backup.append(copy.deepcopy(states[i]))
Ejemplo n.º 5
0
def meyer_penny_program():
    """
    Returns the program to simulate the Meyer-Penny Game

    :return: pyQuil Program
    """

    picard_register = 1
    answer_register = 0

    then_branch = pq.Program(X(0))
    else_branch = pq.Program(I(0))

    return (pq.Program()
            # Prepare Qubits in Heads state or superposition, respectively
            .inst(X(0), H(1))
            # Q puts the coin into a superposition
            .inst(H(0))
            # Picard makes a decision and acts accordingly
            .measure(1, picard_register)
            .if_then(picard_register, then_branch, else_branch)
            # Q undoes his superposition operation
            .inst(H(0))
            # The outcome is recorded into the answer register
            .measure(0, answer_register))
Ejemplo n.º 6
0
def estimate_assignment_probs(
    q: int,
    trials: int,
    cxn: Union["QVMConnection", "QPUConnection"],
    p0: Optional["Program"] = None,
) -> np.ndarray:
    """
    Estimate the readout assignment probabilities for a given qubit ``q``.
    The returned matrix is of the form::

            [[p00 p01]
             [p10 p11]]

    :param q: The index of the qubit.
    :param trials: The number of samples for each state preparation.
    :param cxn: The quantum abstract machine to sample from.
    :param p0: A header program to prepend to the state preparation programs.
    :return: The assignment probability matrix
    """
    from pyquil.quil import Program

    if p0 is None:  # pragma no coverage
        p0 = Program()
    results_i = np.sum(
        cxn.run(p0 + Program(I(q), MEASURE(q, MemoryReference("ro", 0))), [0],
                trials))
    results_x = np.sum(
        cxn.run(p0 + Program(X(q), MEASURE(q, MemoryReference("ro", 0))), [0],
                trials))

    p00 = 1.0 - results_i / float(trials)
    p11 = results_x / float(trials)
    return np.array([[p00, 1 - p11], [1 - p00, p11]])
Ejemplo n.º 7
0
    def reset(self, problem_id=None):
        """Reset the state of the environment.

        This clears out whatever program you may have assembled so far, and
        updates the active problem.

        Args:
            problem_id: The numeric index of the problem (relative to the problem set).
                        If None, a random problem will be chosen.
        """
        if problem_id is None:
            problem_id = np.random.randint(0, self.pset.num_problems())

        self.problem_id = problem_id
        self._prob_vec = self.pset.problem(self.problem_id)
        # the scoring function (for reward computation)
        self._prob_score = self.pset.bitstrings_score(self.problem_id)

        # we put some trivial gates on each relevant qubit, so that we can
        # always recover the problem variables from the program itself
        self.program = Program([I(q) for q in range(self.num_qubits)])
        self.current_step = 0
        self.running_episode_reward = 0

        self.bitstrings, info = self._run_program(self.program)
        return self.observation
Ejemplo n.º 8
0
def benchmarker():
    try:
        bm = get_benchmarker()
        bm.apply_clifford_to_pauli(Program(I(0)), sI(0))
    except RequestException as e:
        return pytest.skip("This test requires a running local benchmarker endpoint (ie quilc): {}"
                           .format(e))
Ejemplo n.º 9
0
def test_readout_symmetrization(forest):
    device = NxDevice(nx.complete_graph(3))
    noise_model = decoherence_noise_with_asymmetric_ro(
        gates=gates_in_isa(device.get_isa()))
    qc = QuantumComputer(
        name="testy!",
        qam=QVM(connection=forest, noise_model=noise_model),
        device=device,
        compiler=DummyCompiler(),
    )

    prog = Program(I(0), X(1), MEASURE(0, MemoryReference("ro", 0)),
                   MEASURE(1, MemoryReference("ro", 1)))
    prog.wrap_in_numshots_loop(1000)

    bs1 = qc.run(prog)
    avg0_us = np.mean(bs1[:, 0])
    avg1_us = 1 - np.mean(bs1[:, 1])
    diff_us = avg1_us - avg0_us
    assert diff_us > 0.03

    bs2 = qc.run_symmetrized_readout(prog, 1000)
    avg0_s = np.mean(bs2[:, 0])
    avg1_s = 1 - np.mean(bs2[:, 1])
    diff_s = avg1_s - avg0_s
    assert diff_s < 0.05
def test_for_negative_probabilities():
    # trivial program to do state tomography on
    prog = Program(I(0))

    # make TomographyExperiment
    expt_settings = [ExperimentSetting(zeros_state([0]), pt) for pt in [sI(0), sX(0), sY(0), sZ(0)]]
    experiment_1q = TomographyExperiment(settings=expt_settings, program=prog)

    # make a quantum computer object
    device = NxDevice(nx.complete_graph(1))
    qc_density = QuantumComputer(
        name="testy!",
        qam=PyQVM(n_qubits=1, quantum_simulator_type=ReferenceDensitySimulator),
        device=device,
        compiler=DummyCompiler(),
    )

    # initialize with a pure state
    initial_density = np.array([[1.0, 0.0], [0.0, 0.0]])
    qc_density.qam.wf_simulator.density = initial_density

    try:
        list(measure_observables(qc=qc_density, tomo_experiment=experiment_1q, n_shots=3000))
    except ValueError as e:
        # the error is from np.random.choice by way of self.rs.choice in ReferenceDensitySimulator
        assert str(e) != "probabilities are not non-negative"

    # initialize with a mixed state
    initial_density = np.array([[0.9, 0.0], [0.0, 0.1]])
    qc_density.qam.wf_simulator.density = initial_density

    try:
        list(measure_observables(qc=qc_density, tomo_experiment=experiment_1q, n_shots=3000))
    except ValueError as e:
        assert str(e) != "probabilities are not non-negative"
Ejemplo n.º 11
0
def orig_decode(qubits, indices=None, measure=True):

    ## indices are qubits you recover secret from, need 3
    ## measure asks whether or not to measure result at end
    if indices is None:
        indices = np.random.choice(len(qubits), 3, replace=False)
    new_qubits = [qubits[index] for index in indices]
    pq = Program()
    ro = pq.declare('ro', 'BIT', 3)

    # first hadamard qubit 0
    pq += H(new_qubits[0])

    # bell state measurement on 1,2
    pq += X(new_qubits[2])
    pq += CNOT(new_qubits[2], new_qubits[1])
    pq += H(new_qubits[2])
    pq += MEASURE(new_qubits[1], ro[0])
    pq += MEASURE(new_qubits[2], ro[1])
    case1 = Program()
    case2 = Program()
    case1.if_then(ro[1], Program(Z(new_qubits[0]), X(new_qubits[0])),
                  Z(new_qubits[0]))
    case2.if_then(ro[1], X(new_qubits[0]), I(new_qubits[0]))
    pq.if_then(ro[0], case1, case2)
    if measure:
        pq += MEASURE(new_qubits[0], ro[2])
    return pq, new_qubits
Ejemplo n.º 12
0
def cxn():
    # DEPRECATED
    try:
        cxn = QVMConnection(endpoint='http://localhost:5000')
        cxn.run(Program(I(0), MEASURE(0, 0)), [0])
        return cxn
    except RequestException as e:
        return pytest.skip("This test requires a running local QVM: {}".format(e))
Ejemplo n.º 13
0
def qvm():
    try:
        qc = get_qc('9q-square-qvm')
        qc.compiler.client.timeout = 1
        qc.run_and_measure(Program(I(0)), trials=1)
        return qc
    except (RequestException, TimeoutError) as e:
        return pytest.skip("This test requires a running local QVM and quilc: {}".format(e))
Ejemplo n.º 14
0
def compiler():
    try:
        compiler = CompilerConnection(isa_source=ISA.from_dict(isa_dict()))
        compiler.compile(Program(I(0)))
        return compiler
    except (RequestException, UnknownApiError) as e:
        return pytest.skip(
            "This test requires compiler connection: {}".format(e))
Ejemplo n.º 15
0
def qpu_compiler(test_device):
    try:
        config = PyquilConfig()
        compiler = QPUCompiler(endpoint=config.compiler_url, device=test_device, timeout=0.5)
        compiler.quil_to_native_quil(Program(I(0)))
        return compiler
    except Exception as e:
        return pytest.skip(f"This test requires compiler connection: {e}")
Ejemplo n.º 16
0
def compiler(test_device):
    try:
        config = PyquilConfig()
        compiler = LocalQVMCompiler(endpoint=config.compiler_url, device=test_device)
        compiler.quil_to_native_quil(Program(I(0)))
        return compiler
    except (RequestException, UnknownApiError) as e:
        return pytest.skip("This test requires compiler connection: {}".format(e))