当前位置: 首页>>代码示例>>Python>>正文


Python gates.X属性代码示例

本文整理汇总了Python中pyquil.gates.X属性的典型用法代码示例。如果您正苦于以下问题:Python gates.X属性的具体用法?Python gates.X怎么用?Python gates.X使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在pyquil.gates的用法示例。


在下文中一共展示了gates.X属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: basis_state_preps

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def basis_state_preps(*qubits):
    """
    Generate a sequence of programs that prepares the measurement
    basis states of some set of qubits in the order such that the qubit
    with highest index is iterated over the most quickly:
    E.g., for ``qubits=(0, 1)``, it returns the circuits::

        I_0 I_1
        I_0 X_1
        X_0 I_1
        X_0 X_1

    :param list qubits: Each qubit to include in the basis state preparation.
    :return: Yields programs for each basis state preparation.
    :rtype: Program
    """
    for prep in cartesian_product([I, X], repeat=len(qubits)):
        basis_prep = Program(Pragma("PRESERVE_BLOCK"))
        for gate, qubit in zip(prep, qubits):
            basis_prep.inst(gate(qubit))
        basis_prep.inst(Pragma("END_PRESERVE_BLOCK"))
        yield basis_prep 
开发者ID:rigetti,项目名称:grove,代码行数:24,代码来源:utils.py

示例2: _create_bv_circuit

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def _create_bv_circuit(self, bit_map: Dict[str, str]) -> Program:
        """
        Implementation of the Bernstein-Vazirani Algorithm.

        Given a list of input qubits and an ancilla bit, all initially in the
        :math:`\\vert 0\\rangle` state, create a program that can find :math:`\\vec{a}` with one
        query to the given oracle.

        :param Dict[String, String] bit_map: truth-table of a function for Bernstein-Vazirani with
            the keys being all possible bit vectors strings and the values being the function values
        :rtype: Program
        """
        unitary, _ = self._compute_unitary_oracle_matrix(bit_map)
        full_bv_circuit = Program()

        full_bv_circuit.defgate("BV-ORACLE", unitary)

        # Put ancilla bit into minus state
        full_bv_circuit.inst(X(self.ancilla), H(self.ancilla))

        full_bv_circuit.inst([H(i) for i in self.computational_qubits])
        full_bv_circuit.inst(
            tuple(["BV-ORACLE"] + sorted(self.computational_qubits + [self.ancilla], reverse=True)))
        full_bv_circuit.inst([H(i) for i in self.computational_qubits])
        return full_bv_circuit 
开发者ID:rigetti,项目名称:grove,代码行数:27,代码来源:bernstein_vazirani.py

示例3: test_x_oracle_two_grover

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def test_x_oracle_two_grover(x_oracle):
    """Testing that Grover's algorithm with an oracle that applies an X gate to the query bit works,
     with two iterations."""
    qubits = [0]
    oracle, _ = x_oracle
    generated_x_oracle_grover = Grover().oracle_grover(oracle, qubits, num_iter=2)
    # First we put the input into uniform superposition.
    gates = [H]
    for _ in range(2):
        # Now an oracle is applied.
        gates.append(X)
        # We apply the diffusion operator.
        gates.append(H)
        gates.append(HADAMARD_DIFFUSION_LABEL)
        gates.append(H)
    check_instructions(gates, generated_x_oracle_grover) 
开发者ID:rigetti,项目名称:grove,代码行数:18,代码来源:test_grover.py

示例4: test_pass_hamiltonians

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def test_pass_hamiltonians():
    ref_ham = [PauliSum([PauliTerm("X", 0, -1.0)]), PauliSum([PauliTerm("X", 1, -1.0)])]
    cost_ham = [PauliTerm("I", 0, 0.5) + PauliTerm("Z", 0, -0.5) * PauliTerm("Z", 1, 1.0)]
    fake_qc = Mock()
    inst = QAOA(fake_qc, list(range(2)), steps=1,
                cost_ham=cost_ham, ref_ham=ref_ham)

    c = inst.cost_ham
    r = inst.ref_ham
    assert isinstance(c, list)
    assert isinstance(r, list)
    assert isinstance(c[0], PauliSum)
    assert isinstance(r[0], PauliSum)
    assert len(c) == 1
    assert len(r) == 2

    with pytest.raises(TypeError):
        QAOA(fake_qc, 2, steps=1,
             cost_ham=PauliTerm("X", 0, 1.0), ref_ham=ref_ham,
             rand_seed=42) 
开发者ID:rigetti,项目名称:grove,代码行数:22,代码来源:test_maxcut.py

示例5: test_psiref_bar_p2

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def test_psiref_bar_p2():
    bar = [(0, 1)]
    p = 2
    with patch('pyquil.api.get_qc', spec=qc_mod):
        inst = maxcut_qaoa(bar, steps=p)

    param_prog = inst.get_parameterized_program()

    # returns are the rotations correct?
    prog = param_prog([1.2, 3.4, 2.1, 4.5])
    result_prog = Program().inst([H(0), H(1),
                                  CNOT(0, 1), RZ(2.1, 1), CNOT(0, 1),
                                  X(0), PHASE(1.05, 0), X(0), PHASE(1.05, 0),
                                  H(0), RZ(-2.4, 0), H(0),
                                  H(1), RZ(-2.4, 1), H(1),
                                  CNOT(0, 1), RZ(4.5, 1), CNOT(0, 1),
                                  X(0), PHASE(2.25, 0), X(0), PHASE(2.25, 0),
                                  H(0), RZ(-6.8, 0), H(0),
                                  H(1), RZ(-6.8, 1), H(1),
                                  ])
    assert prog == result_prog 
开发者ID:rigetti,项目名称:grove,代码行数:23,代码来源:test_maxcut.py

示例6: _ops_bool_to_prog

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def _ops_bool_to_prog(ops_bool: Tuple[bool], qubits: List[int]) -> Program:
    """
    :param ops_bool: tuple of booleans specifying the operation to be carried out on `qubits`
    :param qubits: list specifying the qubits to be carried operations on
    :return: Program with the operations specified in `ops_bool` on the qubits specified in
        `qubits`
    """
    assert len(ops_bool) == len(qubits), "Mismatch of qubits and operations"
    prog = Program()
    for i, op_bool in enumerate(ops_bool):
        if op_bool == 0:
            continue
        elif op_bool == 1:
            prog += Program(X(qubits[i]))
        else:
            raise ValueError("ops_bool should only consist of 0s and/or 1s")
    return prog 
开发者ID:rigetti,项目名称:pyquil,代码行数:19,代码来源:operator_estimation.py

示例7: test_to_latex

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def test_to_latex():
    """A test to give full coverage of latex_generation."""
    p = Program()
    p.inst(
        X(0),
        RX(1.0, 5),
        Y(0),
        CZ(0, 2),
        SWAP(0, 1),
        MEASURE(0, None),
        CNOT(2, 0),
        X(0).controlled(1),
        Y(0).dagger(),
    )
    _ = to_latex(p)

    # Modify settings to access non-standard control paths.
    settings = DiagramSettings(impute_missing_qubits=True)
    _ = to_latex(p, settings)

    settings = DiagramSettings(abbreviate_controlled_rotations=True)
    _ = to_latex(p, settings)

    settings = DiagramSettings(label_qubit_lines=False)
    _ = to_latex(p, settings) 
开发者ID:rigetti,项目名称:pyquil,代码行数:27,代码来源:test_latex.py

示例8: test_qpu_run

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def test_qpu_run():
    config = PyquilConfig()
    if config.qpu_url and config.qpu_compiler_url:
        g = nx.Graph()
        g.add_node(0)
        device = NxDevice(g)

        qc = QuantumComputer(
            name="pyQuil test QC",
            qam=QPU(endpoint=config.qpu_url, user="pyQuil test suite"),
            device=device,
            compiler=QPUCompiler(
                quilc_endpoint=config.quilc_url,
                qpu_compiler_endpoint=config.qpu_compiler_url,
                device=device,
            ),
        )
        bitstrings = qc.run_and_measure(program=Program(X(0)), trials=1000)
        assert bitstrings[0].shape == (1000,)
        assert np.mean(bitstrings[0]) > 0.8
        bitstrings = qc.run(qc.compile(Program(X(0))))
        assert bitstrings.shape == (0, 0)
    else:
        pytest.skip("QPU or compiler-server not available; skipping QPU run test.") 
开发者ID:rigetti,项目名称:pyquil,代码行数:26,代码来源:test_qpu.py

示例9: test_measure_observables_symmetrize

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def test_measure_observables_symmetrize(forest):
    """
    Symmetrization alone should not change the outcome on the QVM
    """
    expts = [
        ExperimentSetting(TensorProductState(), o1 * o2)
        for o1, o2 in itertools.product([sI(0), sX(0), sY(0), sZ(0)], [sI(1), sX(1), sY(1), sZ(1)])
    ]
    suite = Experiment(expts, program=Program(X(0), CNOT(0, 1)))
    assert len(suite) == 4 * 4
    gsuite = group_experiments(suite)
    assert len(gsuite) == 3 * 3  # can get all the terms with I for free in this case

    qc = get_qc("2q-qvm")
    for res in measure_observables(qc, gsuite, calibrate_readout=None):
        if res.setting.out_operator in [sI(), sZ(0), sZ(1), sZ(0) * sZ(1)]:
            assert np.abs(res.expectation) > 0.9
        else:
            assert np.abs(res.expectation) < 0.1 
开发者ID:rigetti,项目名称:pyquil,代码行数:21,代码来源:test_operator_estimation.py

示例10: test_ops_bool_to_prog

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def test_ops_bool_to_prog():
    qubits = [0, 2, 3]
    ops_strings = list(itertools.product([0, 1], repeat=len(qubits)))
    d_expected = {
        (0, 0, 0): "",
        (0, 0, 1): "X 3\n",
        (0, 1, 0): "X 2\n",
        (0, 1, 1): "X 2\nX 3\n",
        (1, 0, 0): "X 0\n",
        (1, 0, 1): "X 0\nX 3\n",
        (1, 1, 0): "X 0\nX 2\n",
        (1, 1, 1): "X 0\nX 2\nX 3\n",
    }
    for op_str in ops_strings:
        p = _ops_bool_to_prog(op_str, qubits)
        assert str(p) == d_expected[op_str] 
开发者ID:rigetti,项目名称:pyquil,代码行数:18,代码来源:test_operator_estimation.py

示例11: test_qvm_compile_pickiness

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def test_qvm_compile_pickiness(forest):
    p = Program(Declare("ro", "BIT"), X(0), MEASURE(0, MemoryReference("ro")))
    p.wrap_in_numshots_loop(1000)
    nq = PyQuilExecutableResponse(program=p.out(), attributes={"num_shots": 1000})

    # Ok, non-realistic
    qc = get_qc("9q-qvm")
    qc.run(p)

    # Also ok
    qc.run(nq)

    # Not ok
    qc = get_qc("9q-square-qvm")
    with pytest.raises(TypeError):
        qc.run(p)

    # Yot ok
    qc.run(nq) 
开发者ID:rigetti,项目名称:pyquil,代码行数:21,代码来源:test_quantum_computer.py

示例12: test_copy

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def test_copy():
    q0, q1 = QubitPlaceholder.register(2)
    term = PauliTerm("X", q0, 0.5) * PauliTerm("X", q1, 0.5)
    new_term = term.copy()

    q2 = QubitPlaceholder()
    term = term * PauliTerm("X", q2, 0.5)
    new_term = new_term * PauliTerm("X", q2, 0.5)

    assert term == new_term  # value equality
    assert term is not new_term  # ref inequality
    assert term._ops is not new_term._ops

    term = PauliTerm("X", q0, 0.5) * PauliTerm("X", q1, 0.5)
    new_term = term * PauliTerm("X", q2, 0.5)
    assert term != new_term
    assert term is not new_term
    assert term._ops is not new_term._ops 
开发者ID:rigetti,项目名称:pyquil,代码行数:20,代码来源:test_paulis_with_placeholders.py

示例13: basis_selector_oracle

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def basis_selector_oracle(qubits: List[int], bitstring: str) -> Program:
    """
    Defines an oracle that selects the ith element of the computational basis.

    Flips the sign of the state :math:`\\vert x\\rangle>`
    if and only if x==bitstring and does nothing otherwise.

    :param qubits: The qubits the oracle is called on. The qubits are assumed to be ordered from
     most significant qubit to least significant qubit.
    :param bitstring: The desired bitstring, given as a string of ones and zeros. e.g. "101"
    :return: A program representing this oracle.
    """
    if len(qubits) != len(bitstring):
        raise ValueError("The bitstring should be the same length as the number of qubits.")
    oracle_prog = Program()

    # In the case of one qubit, we just want to flip the phase of state relative to the other.
    if len(bitstring) == 1:
        oracle_prog.inst(Z(qubits[0]))
        return oracle_prog
    else:
        bitflip_prog = Program()
        for i, qubit in enumerate(qubits):
            if bitstring[i] == '0':
                bitflip_prog.inst(X(qubit))
        oracle_prog += bitflip_prog
        controls = qubits[:-1]
        target = qubits[-1]
        operation = np.array([[1, 0], [0, -1]])
        gate_name = 'Z'
        n_qubit_controlled_z = (ControlledProgramBuilder()
                                .with_controls(controls)
                                .with_target(target)
                                .with_operation(operation)
                                .with_gate_name(gate_name)
                                .build())
        oracle_prog += n_qubit_controlled_z
        oracle_prog += bitflip_prog
    return oracle_prog 
开发者ID:rigetti,项目名称:grove,代码行数:41,代码来源:oracles.py

示例14: decomposed_diffusion_program

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def decomposed_diffusion_program(qubits: List[int]) -> Program:
    """
    Constructs the diffusion operator used in Grover's Algorithm, acted on both sides by an
    a Hadamard gate on each qubit. Note that this means that the matrix representation of this
    operator is diag(1, -1, ..., -1). In particular, this decomposes the diffusion operator, which
    is a :math:`2**{len(qubits)}\times2**{len(qubits)}` sparse matrix, into
     :math:`\mathcal{O}(len(qubits)**2) single and two qubit gates.

    See C. Lavor, L.R.U. Manssur, and R. Portugal (2003) `Grover's Algorithm: Quantum Database
    Search`_ for more information.

    .. _`Grover's Algorithm: Quantum Database Search`: https://arxiv.org/abs/quant-ph/0301079

    :param qubits: A list of ints corresponding to the qubits to operate on.
                   The operator operates on bistrings of the form
                   ``|qubits[0], ..., qubits[-1]>``.
    """
    program = Program()
    if len(qubits) == 1:
        program.inst(Z(qubits[0]))
    else:
        program.inst([X(q) for q in qubits])
        program.inst(H(qubits[-1]))
        program.inst(RZ(-np.pi, qubits[0]))
        program += (ControlledProgramBuilder()
                              .with_controls(qubits[:-1])
                              .with_target(qubits[-1])
                              .with_operation(X_GATE)
                              .with_gate_name(X_GATE_LABEL).build())
        program.inst(RZ(-np.pi, qubits[0]))
        program.inst(H(qubits[-1]))
        program.inst([X(q) for q in qubits])
    return program 
开发者ID:rigetti,项目名称:grove,代码行数:35,代码来源:amplification.py

示例15: _construct_deutsch_jozsa_circuit

# 需要导入模块: from pyquil import gates [as 别名]
# 或者: from pyquil.gates import X [as 别名]
def _construct_deutsch_jozsa_circuit(self):
        """
        Builds the Deutsch-Jozsa circuit. Which can determine whether a function f mapping
        :math:`\{0,1\}^n \to \{0,1\}` is constant or balanced, provided that it is one of them.

        :return: A program corresponding to the desired instance of Deutsch Jozsa's Algorithm.
        :rtype: Program
        """
        dj_prog = Program()

        # Put the first ancilla qubit (query qubit) into minus state
        dj_prog.inst(X(self.ancillas[0]), H(self.ancillas[0]))

        # Apply Hadamard, Oracle, and Hadamard again
        dj_prog.inst([H(qubit) for qubit in self.computational_qubits])

        # Build the oracle
        oracle_prog = Program()
        oracle_prog.defgate(ORACLE_GATE_NAME, self.unitary_matrix)

        scratch_bit = self.ancillas[1]
        qubits_for_funct = [scratch_bit] + self.computational_qubits
        oracle_prog.inst(tuple([ORACLE_GATE_NAME] + qubits_for_funct))
        dj_prog += oracle_prog

        # Here the oracle does not leave the computational qubits unchanged, so we use a CNOT to
        # to move the result to the query qubit, and then we uncompute with the dagger.
        dj_prog.inst(CNOT(self._qubits[0], self.ancillas[0]))
        dj_prog += oracle_prog.dagger()
        dj_prog.inst([H(qubit) for qubit in self.computational_qubits])
        return dj_prog 
开发者ID:rigetti,项目名称:grove,代码行数:33,代码来源:deutsch_jozsa.py


注:本文中的pyquil.gates.X属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。