本文整理汇总了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]])
示例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
示例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)
示例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)
示例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)
示例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
示例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
示例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])
示例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
示例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
示例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
示例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
示例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
示例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
示例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