當前位置: 首頁>>代碼示例>>Python>>正文


Python gates.MEASURE屬性代碼示例

本文整理匯總了Python中pyquil.gates.MEASURE屬性的典型用法代碼示例。如果您正苦於以下問題:Python gates.MEASURE屬性的具體用法?Python gates.MEASURE怎麽用?Python gates.MEASURE使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在pyquil.gates的用法示例。


在下文中一共展示了gates.MEASURE屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: find_bitstring

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def find_bitstring(self, qc: QuantumComputer, bitstring_map: Dict[str, int]) -> str:
        """
        Runs Grover's Algorithm to find the bitstring that is designated by ``bistring_map``.

        In particular, this will prepare an initial state in the uniform superposition over all bit-
        strings, an then use Grover's Algorithm to pick out the desired bitstring.

        :param qc: the connection to the Rigetti cloud to run pyQuil programs.
        :param bitstring_map: a mapping from bitstrings to the phases that the oracle should impart
            on them. If the oracle should "look" for a bitstring, it should have a ``-1``, otherwise
            it should have a ``1``.
        :return: Returns the bitstring resulting from measurement after Grover's Algorithm.
        """

        self._init_attr(bitstring_map)

        ro = self.grover_circuit.declare('ro', 'BIT', len(self.qubits))
        self.grover_circuit += [MEASURE(qubit, ro[idx]) for idx, qubit in enumerate(self.qubits)]
        executable = qc.compile(self.grover_circuit)
        sampled_bitstring = qc.run(executable)

        return "".join([str(bit) for bit in sampled_bitstring[0]]) 
開發者ID:rigetti,項目名稱:grove,代碼行數:24,代碼來源:grover.py

示例2: is_constant

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def is_constant(self, qc: QuantumComputer, bitstring_map: Dict[str, str]) -> bool:
        """Computes whether bitstring_map represents a constant function, given that it is constant
         or balanced. Constant means all inputs map to the same value, balanced means half of the
         inputs maps to one value, and half to the other.

        :param QVMConnection cxn: The connection object to the Rigetti cloud to run pyQuil programs.
        :param bitstring_map: A dictionary whose keys are bitstrings, and whose values are bits
         represented as strings.
        :type bistring_map: Dict[String, String]
        :return: True if the bitstring_map represented a constant function, false otherwise.
        :rtype: bool
        """
        self._init_attr(bitstring_map)

        prog = Program()
        dj_ro = prog.declare('ro', 'BIT', len(self.computational_qubits))
        prog += self.deutsch_jozsa_circuit
        prog += [MEASURE(qubit, ro) for qubit, ro in zip(self.computational_qubits, dj_ro)]
        executable = qc.compile(prog)
        returned_bitstring = qc.run(executable)
        # We are only running a single shot, so we are only interested in the first element.
        bitstring = np.array(returned_bitstring, dtype=int)
        constant = all([bit == 0 for bit in bitstring])
        return constant 
開發者ID:rigetti,項目名稱:grove,代碼行數:26,代碼來源:deutsch_jozsa.py

示例3: test_gradient_program

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def test_gradient_program():
    f_h = 0.25
    precision = 2
    
    trial_prog = gradient_program(f_h, precision)
    
    result_prog = Program([H(0), H(1)])

    phase_factor = np.exp(1.0j * 2 * np.pi * abs(f_h))
    U = np.array([[phase_factor, 0],
                  [0, phase_factor]])
    q_out = range(precision, precision+1)
    for i in range(precision):
        if i > 0:
            U = np.dot(U, U)
        cU = controlled(U)
        name = "CONTROLLED-U{0}".format(2 ** i)
        result_prog.defgate(name, cU)
        result_prog.inst((name, i) + tuple(q_out))

    result_prog.inst([SWAP(0, 1), H(0), CPHASE(-1.5707963267948966, 0, 1),
                      H(1), MEASURE(0, 0), MEASURE(1, 1)])

    assert(trial_prog == result_prog) 
開發者ID:rigetti,項目名稱:grove,代碼行數:26,代碼來源:test_jordan_gradient.py

示例4: _sample_independent_bit_vectors

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def _sample_independent_bit_vectors(self, qc: QuantumComputer) -> None:
        """
        This method samples :math:`n-1` linearly independent vectors using the Simon Circuit.
        It attempts to put the sampled bitstring into a dictionary and only terminates once the
        dictionary contains :math:`n-1` samples

        :param qc: Connection object to a QuantumComputer.
        :return: None
        """
        while len(self._dict_of_linearly_indep_bit_vectors) < self.n_qubits - 1:

            prog = Program()
            simon_ro = prog.declare('ro', 'BIT', len(self.computational_qubits))
            prog += self.simon_circuit
            prog += [MEASURE(qubit, ro) for qubit, ro in zip(self.computational_qubits, simon_ro)]
            executable = qc.compile(prog)
            sampled_bit_string = np.array(qc.run(executable)[0], dtype=int)

            self._add_to_dict_of_indep_bit_vectors(sampled_bit_string) 
開發者ID:rigetti,項目名稱:grove,代碼行數:21,代碼來源:simon.py

示例5: apply

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def apply(self, operations, **kwargs):
        """Run the QVM"""
        # pylint: disable=attribute-defined-outside-init
        if self.parametric_compilation and "pyqvm" not in self.qc.name:
            self.apply_parametric_program(operations, **kwargs)
        else:
            super().apply(operations, **kwargs)

        prag = Program(Pragma("INITIAL_REWIRING", ['"PARTIAL"']))

        if self.active_reset:
            prag += RESET()

        self.prog = prag + self.prog

        qubits = sorted(self.wiring.values())
        ro = self.prog.declare("ro", "BIT", len(qubits))
        for i, q in enumerate(qubits):
            self.prog.inst(MEASURE(q, ro[i]))

        self.prog.wrap_in_numshots_loop(self.shots) 
開發者ID:rigetti,項目名稱:pennylane-forest,代碼行數:23,代碼來源:qvm.py

示例6: test_run

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def test_run(forest):
    device = NxDevice(nx.complete_graph(3))
    qc = QuantumComputer(
        name="testy!",
        qam=QVM(connection=forest, gate_noise=[0.01] * 3),
        device=device,
        compiler=DummyCompiler(),
    )
    bitstrings = qc.run(
        Program(
            Declare("ro", "BIT", 3),
            H(0),
            CNOT(0, 1),
            CNOT(1, 2),
            MEASURE(0, MemoryReference("ro", 0)),
            MEASURE(1, MemoryReference("ro", 1)),
            MEASURE(2, MemoryReference("ro", 2)),
        ).wrap_in_numshots_loop(1000)
    )

    assert bitstrings.shape == (1000, 3)
    parity = np.sum(bitstrings, axis=1) % 3
    assert 0 < np.mean(parity) < 0.15 
開發者ID:rigetti,項目名稱:pyquil,代碼行數:25,代碼來源:test_quantum_computer.py

示例7: test_run_pyqvm_noisy

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def test_run_pyqvm_noisy():
    device = NxDevice(nx.complete_graph(3))
    qc = QuantumComputer(
        name="testy!",
        qam=PyQVM(n_qubits=3, post_gate_noise_probabilities={"relaxation": 0.01}),
        device=device,
        compiler=DummyCompiler(),
    )
    prog = Program(H(0), CNOT(0, 1), CNOT(1, 2))
    ro = prog.declare("ro", "BIT", 3)
    for q in range(3):
        prog += MEASURE(q, ro[q])
    bitstrings = qc.run(prog.wrap_in_numshots_loop(1000))

    assert bitstrings.shape == (1000, 3)
    parity = np.sum(bitstrings, axis=1) % 3
    assert 0 < np.mean(parity) < 0.15 
開發者ID:rigetti,項目名稱:pyquil,代碼行數:19,代碼來源:test_quantum_computer.py

示例8: test_run_with_parameters

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def test_run_with_parameters(forest):
    device = NxDevice(nx.complete_graph(3))
    qc = QuantumComputer(
        name="testy!", qam=QVM(connection=forest), device=device, compiler=DummyCompiler()
    )
    bitstrings = qc.run(
        executable=Program(
            Declare(name="theta", memory_type="REAL"),
            Declare(name="ro", memory_type="BIT"),
            RX(MemoryReference("theta"), 0),
            MEASURE(0, MemoryReference("ro")),
        ).wrap_in_numshots_loop(1000),
        memory_map={"theta": [np.pi]},
    )

    assert bitstrings.shape == (1000, 1)
    assert all([bit == 1 for bit in bitstrings]) 
開發者ID:rigetti,項目名稱:pyquil,代碼行數:19,代碼來源:test_quantum_computer.py

示例9: test_qvm_run_only_pqer

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def test_qvm_run_only_pqer(forest: ForestConnection):
    qvm = QVM(connection=forest, gate_noise=[0.01] * 3, requires_executable=True)
    p = Program(Declare("ro", "BIT"), X(0), MEASURE(0, MemoryReference("ro")))
    p.wrap_in_numshots_loop(1000)

    with pytest.raises(TypeError) as e:
        qvm.load(p)
        qvm.run()
        qvm.wait()
    assert e.match(r".*Make sure you have explicitly compiled your program.*")

    nq = PyQuilExecutableResponse(program=p.out(), attributes={"num_shots": 1000})
    qvm.load(nq)
    qvm.run()
    qvm.wait()
    bitstrings = qvm.read_memory(region_name="ro")
    assert bitstrings.shape == (1000, 1)
    assert np.mean(bitstrings) > 0.8 
開發者ID:rigetti,項目名稱:pyquil,代碼行數:20,代碼來源:test_qvm.py

示例10: get_classical_addresses_from_program

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def get_classical_addresses_from_program(program: Program) -> Dict[str, List[int]]:
    """
    Returns a sorted list of classical addresses found in the MEASURE instructions in the program.

    :param program: The program from which to get the classical addresses.
    :return: A mapping from memory region names to lists of offsets appearing in the program.
    """
    addresses: Dict[str, List[int]] = defaultdict(list)
    flattened_addresses = {}

    # Required to use the `classical_reg.address` int attribute.
    # See https://github.com/rigetti/pyquil/issues/388.
    for instr in program:
        if isinstance(instr, Measurement) and instr.classical_reg:
            addresses[instr.classical_reg.name].append(instr.classical_reg.offset)

    # flatten duplicates
    for k, v in addresses.items():
        reduced_list = list(set(v))
        reduced_list.sort()
        flattened_addresses[k] = reduced_list

    return flattened_addresses 
開發者ID:rigetti,項目名稱:pyquil,代碼行數:25,代碼來源:quil.py

示例11: test_get_flipped_program

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def test_get_flipped_program():
    program = Program()
    ro = program.declare('ro', memory_type='BIT', memory_size=2)
    program += Program([
        I(0),
        RX(2.3, 1),
        CNOT(0, 1),
        MEASURE(0, ro[0]),
        MEASURE(1, ro[1]),
    ])

    flipped_program = get_flipped_program(program)

    lines = flipped_program.out().splitlines()
    matched = 0
    for l1, l2 in zip(lines, lines[1:]):
        ma = re.match(r'MEASURE (\d) ro\[(\d)\]', l2)
        if ma is not None:
            matched += 1
            assert int(ma.group(1)) == int(ma.group(2))
            assert l1 == 'RX(pi) {}'.format(int(ma.group(1)))

    assert matched == 2 
開發者ID:rigetti,項目名稱:forest-benchmarking,代碼行數:25,代碼來源:test_readout.py

示例12: create_ghz_program

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def create_ghz_program(tree: nx.DiGraph):
    """
    Create a Bell/GHZ state with CNOTs described by tree.

    :param tree: A tree that describes the CNOTs to perform to create a bell/GHZ state.
    :return: the program
    """
    assert nx.is_tree(tree), 'Needs to be a tree'
    nodes = list(nx.topological_sort(tree))
    n_qubits = len(nodes)
    program = Program(H(nodes[0]))

    for node in nodes:
        for child in tree.successors(node):
            program += CNOT(node, child)

    ro = program.declare('ro', 'BIT', n_qubits)
    for i, q in enumerate(nodes):
        program += MEASURE(q, ro[i])

    return program 
開發者ID:rigetti,項目名稱:forest-benchmarking,代碼行數:23,代碼來源:entangled_states.py

示例13: get_string

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def get_string(self, betas: List[float], gammas: List[float], samples: int = 100):
        """
        Compute the most probable string.

        The method assumes you have passed init_betas and init_gammas with your
        pre-computed angles or you have run the VQE loop to determine the
        angles.  If you have not done this you will be returning the output for
        a random set of angles.

        :param betas: List of beta angles
        :param gammas: List of gamma angles
        :param samples: (Optional) number of samples to get back from the QuantumComputer.
        :returns: tuple representing the bitstring, Counter object from
                  collections holding all output bitstrings and their frequency.
        """
        if samples <= 0 and not isinstance(samples, int):
            raise ValueError("samples variable must be positive integer")
        param_prog = self.get_parameterized_program()
        stacked_params = np.hstack((betas, gammas))

        sampling_prog = Program()
        ro = sampling_prog.declare('ro', 'BIT', len(self.qubits))
        sampling_prog += param_prog(stacked_params)
        sampling_prog += [MEASURE(qubit, r) for qubit, r in zip(self.qubits, ro)]
        sampling_prog.wrap_in_numshots_loop(samples)
        executable = self.qc.compile(sampling_prog)
        bitstring_samples = self.qc.run(executable)
        bitstring_tuples = list(map(tuple, bitstring_samples))
        freq = Counter(bitstring_tuples)
        most_frequent_bit_string = max(freq, key=lambda x: freq[x])
        return most_frequent_bit_string, freq 
開發者ID:rigetti,項目名稱:grove,代碼行數:33,代碼來源:qaoa.py

示例14: run_swap_test

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def run_swap_test(program_a: Program, program_b: Program,
                  number_of_measurements: int,
                  quantum_resource: QuantumComputer,
                  ancilla: int = None) -> float:
    """
    Run a swap test and return the calculated overlap.

    :param program_a: state preparation for the 'A' register
    :param program_b: state preparation for the 'B' register
    :param number_of_measurements: number of times to measure
    :param quantum_resource: connection to QuantumComputer.
    :param ancilla: Index of ancilla
    :return: overlap of states prepared by program_a and program_b
    """
    register_a = list(program_a.get_qubits())
    register_b = list(program_b.get_qubits())
    if ancilla is None:
        ancilla = max(register_a + register_b) + 1

    swap_test_program = Program()
    # instantiate ancilla readout register
    ro = swap_test_program.declare('ro', 'BIT', 1)
    swap_test_program += program_a + program_b
    swap_test_program += swap_circuit_generator(register_a, register_b, ancilla)
    swap_test_program += MEASURE(ancilla, ro[0])

    # TODO: instead of number of measurements have user set precision of overlap
    # estimate and calculate number of shots to be within this precision
    swap_test_program.wrap_in_numshots_loop(number_of_measurements)
    executable = quantum_resource.compiler.native_quil_to_executable(swap_test_program)
    results = quantum_resource.run(executable)

    probability_of_one = np.mean(results)
    if probability_of_one > 0.5:
        raise ValueError("measurements indicate overlap is negative")

    estimated_overlap = np.sqrt(1 - 2 * probability_of_one)
    return estimated_overlap 
開發者ID:rigetti,項目名稱:grove,代碼行數:40,代碼來源:swap.py

示例15: expectation_from_sampling

# 需要導入模塊: from pyquil import gates [as 別名]
# 或者: from pyquil.gates import MEASURE [as 別名]
def expectation_from_sampling(pyquil_program: Program,
                              marked_qubits: List[int],
                              qc: QuantumComputer,
                              samples: int) -> float:
    """
    Calculation of Z_{i} at marked_qubits

    Given a wavefunctions, this calculates the expectation value of the Zi
    operator where i ranges over all the qubits given in marked_qubits.

    :param pyquil_program: pyQuil program generating some state
    :param marked_qubits: The qubits within the support of the Z pauli
                          operator whose expectation value is being calculated
    :param qc: A QuantumComputer object.
    :param samples: Number of bitstrings collected to calculate expectation
                    from sampling.
    :returns: The expectation value as a float.
    """
    program = Program()
    ro = program.declare('ro', 'BIT', max(marked_qubits) + 1)
    program += pyquil_program
    program += [MEASURE(qubit, r) for qubit, r in zip(list(range(max(marked_qubits) + 1)), ro)]
    program.wrap_in_numshots_loop(samples)
    executable = qc.compile(program)
    bitstring_samples = qc.run(executable)
    bitstring_tuples = list(map(tuple, bitstring_samples))

    freq = Counter(bitstring_tuples)

    # perform weighted average
    expectation = 0
    for bitstring, count in freq.items():
        bitstring_int = int("".join([str(x) for x in bitstring[::-1]]), 2)
        if parity_even_p(bitstring_int, marked_qubits):
            expectation += float(count) / samples
        else:
            expectation -= float(count) / samples
    return expectation 
開發者ID:rigetti,項目名稱:grove,代碼行數:40,代碼來源:vqe.py


注:本文中的pyquil.gates.MEASURE屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。