-
Notifications
You must be signed in to change notification settings - Fork 1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adds tools for appending randomized measurement bases and processing renyi entropy from bitstring #6664
Merged
senecameeks
merged 15 commits into
quantumlib:main
from
senecameeks:u/smeeks/entropy_and_rand_meas
Jul 18, 2024
Merged
Adds tools for appending randomized measurement bases and processing renyi entropy from bitstring #6664
Changes from 3 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
158d953
add utilities for processing renyi entropy and appending randomized m…
senecameeks 9f7f6f8
nit: update test comments
senecameeks f873938
Merge branch 'main' into u/smeeks/entropy_and_rand_meas
senecameeks 3073ea5
address comments
senecameeks 641f96f
fix np array shape which changes test solution
senecameeks 50741c1
Address comments and fix bug
senecameeks 30de8c3
address comments
senecameeks 94b1fa1
Merge branch 'main' into u/smeeks/entropy_and_rand_meas
senecameeks d170e8d
use zip and itertools and update to transformer
senecameeks c92e7c9
rm print
senecameeks 5c6bf1c
type check
senecameeks 408123a
Update cirq-core/cirq/qis/entropy.py
senecameeks 5966bcb
Update cirq-core/cirq/transformers/randomized_measurements.py
senecameeks ba04f00
comments
senecameeks 0a64591
line too long
senecameeks File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
# Copyright 2024 The Cirq Developers | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from collections.abc import Mapping, Sequence | ||
from typing import Any, Literal | ||
|
||
import cirq | ||
import numpy as np | ||
import numpy.typing as npt | ||
|
||
|
||
class RandomizedMeasurements: | ||
def __init__( | ||
self, | ||
num_qubits: int, | ||
num_unitaries: int, | ||
subsystem: Sequence[str | int] | None = None, | ||
qubit_mapping: Mapping[int, str | int] | None = None, | ||
rng: np.random.Generator | None = None, | ||
): | ||
"""Class structure for performing and analyzing a general randomized measurement protocol. | ||
For more details on the randomized measurement toolbox see https://arxiv.org/abs/2203.11374 | ||
Args: | ||
num_qubits: Number of qubits in the circuit | ||
num_unitaries: Number of random pre-measurement unitaries | ||
subsystem: The specific subsystem measured in random basis | ||
qubit_mapping: The mapping between the measurement bitstring index and qubit specifier | ||
rng: Random generator | ||
""" | ||
self.num_qubits = num_qubits | ||
self.num_unitaries = num_unitaries | ||
self.subsystem = subsystem | ||
|
||
self.qubit_mapping = ( | ||
qubit_mapping if qubit_mapping else {i: i for i in range(self.num_qubits)} | ||
) | ||
|
||
self.rng = rng if rng else np.random.default_rng() | ||
|
||
self.pre_measurement_unitaries_list = self._generate_unitaries_list() | ||
|
||
def _generate_unitaries_list(self) -> npt.NDArray[Any]: | ||
"""Generates a list of pre-measurement unitaries.""" | ||
|
||
pauli_strings = self.rng.choice(["X", "Y", "Z"], size=(self.num_unitaries, self.num_qubits)) | ||
|
||
if self.subsystem is not None: | ||
for i in range(pauli_strings.shape[1]): | ||
if self.qubit_mapping[i] not in self.subsystem: | ||
pauli_strings[:, i] = np.array(["Z"] * self.num_unitaries) | ||
|
||
return pauli_strings | ||
|
||
def unitaries_to_moment( | ||
self, unitaries: Sequence[Literal["X", "Y", "Z"]], qubits: Sequence[Any] | ||
) -> 'cirq.Moment': | ||
"""Outputs the cirq moment associated with the pre-measurement rotations. | ||
Args: | ||
unitaries: List of pre-measurement unitaries | ||
qubits: List of qubits | ||
Returns: The cirq moment associated with the pre-measurement rotations | ||
""" | ||
op_list: list[cirq.Operation] = [] | ||
for idx, pauli in enumerate(unitaries): | ||
op_list.append(_pauli_basis_rotation(pauli).on(qubits[idx])) | ||
|
||
return cirq.Moment.from_ops(*op_list) | ||
|
||
|
||
def _pauli_basis_rotation(basis: Literal["X", "Y", "Z"]) -> 'cirq.Gate': | ||
"""Given a measurement basis returns the associated rotation. | ||
Args: | ||
basis: Measurement basis | ||
Returns: The cirq gate for associated with measurement basis | ||
""" | ||
if basis == "X": | ||
return cirq.Ry(rads=-np.pi / 2) | ||
elif basis == "Y": | ||
return cirq.Rx(rads=np.pi / 2) | ||
elif basis == "Z": | ||
return cirq.I | ||
|
||
|
||
def append_randomized_measurements( | ||
circuit: 'cirq.AbstractCircuit', | ||
*, | ||
subsystem: tuple[int] | None = None, | ||
qubits: Sequence | None = None, | ||
num_unitaries: int | None = None, | ||
) -> Sequence['cirq.Circuit']: | ||
"""Given an input circuit returns a list of circuits with the pre-measurement unitaries. | ||
Args: | ||
circuit: The input circuit | ||
subsystem: The specific subsystem measured in random basis. | ||
qubits: A sequence of qubits to measure in random basis. | ||
num_unitaries: The number of random pre-measurement unitaries to append. | ||
Returns: | ||
List of circuits with pre-measurement unitaries and measurements added | ||
""" | ||
qubits = qubits or list(circuit.all_qubits()) | ||
|
||
randomized_measurement_circuits = RandomizedMeasurements( | ||
len(qubits), num_unitaries if num_unitaries else len(qubits), subsystem=subsystem | ||
) | ||
|
||
circuit_list = [] | ||
|
||
for unitaries in randomized_measurement_circuits.pre_measurement_unitaries_list: | ||
pre_measurement_moment = randomized_measurement_circuits.unitaries_to_moment( | ||
unitaries, qubits | ||
) | ||
|
||
temp_circuit = cirq.Circuit.from_moments( | ||
*circuit.moments, pre_measurement_moment, cirq.measure_each(*qubits) | ||
) | ||
|
||
circuit_list.append(temp_circuit) | ||
|
||
return circuit_list |
119 changes: 119 additions & 0 deletions
119
cirq-core/cirq/experiments/measure_in_random_bases_test.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
# Copyright 2024 The Cirq Developers | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import cirq | ||
import cirq.experiments.measure_in_random_bases as mrb | ||
|
||
|
||
def test_append_randomized_measurements_generates_n_circuits(): | ||
# Create a 4-qubit circuit | ||
q0, q1, q2, q3 = cirq.LineQubit.range(4) | ||
circuit = cirq.Circuit([cirq.H(q0), cirq.CNOT(q0, q1), cirq.CNOT(q1, q2), cirq.CNOT(q2, q3)]) | ||
|
||
# Append randomized measurements | ||
circuits = mrb.append_randomized_measurements(circuit) | ||
|
||
assert len(circuits) == 4 # num of qubits | ||
|
||
|
||
def test_append_randomized_measurements_appends_two_moments_to_end_of_circuit(): | ||
# Create a 4-qubit circuit | ||
q0, q1, q2, q3 = cirq.LineQubit.range(4) | ||
circuit = cirq.Circuit([cirq.H(q0), cirq.CNOT(q0, q1), cirq.CNOT(q1, q2), cirq.CNOT(q2, q3)]) | ||
|
||
num_moments_pre = len(circuit.moments) | ||
|
||
# Append randomized measurements | ||
circuits = mrb.append_randomized_measurements(circuit) | ||
|
||
for circuit in circuits: | ||
num_moments_post = len(circuit.moments) | ||
assert num_moments_post == num_moments_pre + 2 # 1 random gate and 1 measurement gate | ||
|
||
|
||
def test_append_randomized_measurements_generates_n_circuits_when_passed_subystem_arg(): | ||
# Create a 4-qubit circuit | ||
q0, q1, q2, q3 = cirq.LineQubit.range(4) | ||
circuit = cirq.Circuit([cirq.H(q0), cirq.CNOT(q0, q1), cirq.CNOT(q1, q2), cirq.CNOT(q2, q3)]) | ||
|
||
# Append randomized measurements to subsystem | ||
circuits = mrb.append_randomized_measurements(circuit, subsystem=(0, 1)) | ||
|
||
assert len(circuits) == 4 | ||
|
||
|
||
def test_append_randomized_measurements_leaves_qubits_not_in_specified_subsystem_unchanged(): | ||
# Create a 4-qubit circuit | ||
q0, q1, q2, q3 = cirq.LineQubit.range(4) | ||
circuit = cirq.Circuit([cirq.H(q0), cirq.CNOT(q0, q1), cirq.CNOT(q1, q2), cirq.CNOT(q2, q3)]) | ||
|
||
# Append randomized measurements to subsystem | ||
circuits = mrb.append_randomized_measurements(circuit, subsystem=(0, 1)) | ||
|
||
for circuit in circuits: | ||
# assert latter subsystems were not changed. | ||
assert circuit.operation_at(q2, 4) == cirq.I(q2) | ||
assert circuit.operation_at(q3, 4) == cirq.I(q3) | ||
|
||
|
||
def test_append_randomized_measurements_generates_circuits_only_for_passed_qubit_mapping(): | ||
# Create a 4-qubit circuit | ||
q0, q1, q2, q3 = cirq.LineQubit.range(4) | ||
circuit = cirq.Circuit([cirq.H(q0), cirq.CNOT(q0, q1), cirq.CNOT(q1, q2), cirq.CNOT(q2, q3)]) | ||
|
||
# Append randomized measurements to subsystem | ||
circuits = mrb.append_randomized_measurements(circuit, qubits=[q0, q1]) | ||
|
||
assert len(circuits) == 2 | ||
|
||
|
||
def test_append_randomized_measurements_appends_two_moments_to_specified_qubits(): | ||
# Create a 4-qubit circuit | ||
q0, q1, q2, q3 = cirq.LineQubit.range(4) | ||
circuit = cirq.Circuit([cirq.H(q0), cirq.CNOT(q0, q1), cirq.CNOT(q1, q2), cirq.CNOT(q2, q3)]) | ||
num_moments_pre = len(circuit.moments) | ||
|
||
# Append randomized measurements to subsystem | ||
circuits = mrb.append_randomized_measurements(circuit, qubits=[q0, q1]) | ||
|
||
for circuit in circuits: | ||
num_moments_post = len(circuit.moments) | ||
assert num_moments_post == num_moments_pre + 2 # 1 random gate and 1 measurement gate | ||
|
||
|
||
def test_append_randomized_measurements_with_num_unitaries_generates_k_circuits(): | ||
# Create a 4-qubit circuit | ||
q0, q1, q2, q3 = cirq.LineQubit.range(4) | ||
circuit = cirq.Circuit([cirq.H(q0), cirq.CNOT(q0, q1), cirq.CNOT(q1, q2), cirq.CNOT(q2, q3)]) | ||
num_unitaries = 3 | ||
|
||
# Append randomized measurements to subsystem | ||
circuits = mrb.append_randomized_measurements(circuit, num_unitaries=num_unitaries) | ||
|
||
assert len(circuits) == num_unitaries | ||
|
||
|
||
def test_append_randomized_measurements_with_num_unitaries_appends_two_moments_on_each_circuit(): | ||
# Create a 4-qubit circuit | ||
q0, q1, q2, q3 = cirq.LineQubit.range(4) | ||
circuit = cirq.Circuit([cirq.H(q0), cirq.CNOT(q0, q1), cirq.CNOT(q1, q2), cirq.CNOT(q2, q3)]) | ||
num_moments_pre = len(circuit.moments) | ||
num_unitaries = 3 | ||
|
||
# Append randomized measurements to subsystem | ||
circuits = mrb.append_randomized_measurements(circuit, num_unitaries=num_unitaries) | ||
|
||
for circuit in circuits: | ||
num_moments_post = len(circuit.moments) | ||
assert num_moments_post == num_moments_pre + 2 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
104 changes: 104 additions & 0 deletions
104
cirq-core/cirq/qis/process_renyi_entropy_from_bitstrings.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
# Copyright 2024 The Cirq Developers | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import concurrent.futures | ||
from collections.abc import Mapping, Sequence | ||
|
||
import numpy as np | ||
import numpy.typing as npt | ||
|
||
|
||
def _get_hamming_distance(bitstring_1: Sequence[int], bitstring_2: Sequence[int]) -> int: | ||
"""Calculates the Hamming distance between two bitstrings. | ||
Args: | ||
bitstring_1: Bitstring 1 | ||
bitstring_2: Bitstring 2 | ||
Returns: The Hamming distance | ||
""" | ||
return int(np.sum(~(np.array(bitstring_1) == np.array(bitstring_2)))) | ||
senecameeks marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
|
||
def _bitstrings_to_probs(bitstrings: npt.NDArray[np.int8]) -> Mapping[tuple, float]: | ||
senecameeks marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""Given a list of bitstrings from different measurements returns a probability distribution. | ||
Args: | ||
bitstrings: The bitstring | ||
Returns: | ||
""" | ||
probs_dict: dict[tuple, float] = {} | ||
|
||
num_shots = bitstrings.shape[0] | ||
for bits in bitstrings: | ||
bits_tuple = tuple(bits) | ||
if bits_tuple in probs_dict: | ||
probs_dict[bits_tuple] += 1 / num_shots | ||
else: | ||
probs_dict[bits_tuple] = 1 / num_shots | ||
|
||
return probs_dict | ||
|
||
|
||
def _bitstring_format_helper( | ||
measured_bitstrings: npt.NDArray[np.int8], subsystem: Sequence[int] | None = None | ||
) -> npt.NDArray[np.int8]: | ||
"""Formats the bitstring for analysis based on the selected subsystem. | ||
Args: | ||
measured_bitstrings: Measured bitstring | ||
subsystem: Subsystem of interest | ||
Returns: The bitstring string for the subsystem | ||
""" | ||
if subsystem is None: | ||
return measured_bitstrings | ||
|
||
return measured_bitstrings[:, :, subsystem] | ||
|
||
|
||
def _compute_bitstring_purity(bitstrings: npt.NDArray[np.int8]) -> float: | ||
"""Computes the purity of a bitstring. | ||
senecameeks marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Args: | ||
bitstrings: The bitstrings measured using the same unitary operators | ||
Returns: The purity of the bitstring | ||
""" | ||
|
||
probs = _bitstrings_to_probs(bitstrings) | ||
purity = 0 | ||
for s, p in probs.items(): | ||
for s_prime, p_prime in probs.items(): | ||
purity += (-2.0) ** float(-_get_hamming_distance(s, s_prime)) * p * p_prime | ||
|
||
return purity * 2 ** (bitstrings.shape[-1]) | ||
|
||
|
||
def process_entropy_from_bitstrings( | ||
senecameeks marked this conversation as resolved.
Show resolved
Hide resolved
senecameeks marked this conversation as resolved.
Show resolved
Hide resolved
|
||
measured_bitstrings: npt.NDArray[np.int8], | ||
subsystem: tuple[int] | None = None, | ||
parallelize: bool = False, | ||
senecameeks marked this conversation as resolved.
Show resolved
Hide resolved
|
||
): | ||
bitstrings = _bitstring_format_helper(measured_bitstrings, subsystem) | ||
num_shots = bitstrings.shape[1] | ||
num_qubits = bitstrings.shape[-1] | ||
|
||
if num_shots == 1: | ||
return 0 | ||
|
||
if parallelize: | ||
with concurrent.futures.ThreadPoolExecutor() as executor: | ||
purities = list(executor.map(_compute_bitstring_purity, list(bitstrings))) | ||
purity = np.mean(purities) | ||
|
||
else: | ||
purity = np.mean([_compute_bitstring_purity(bitstring) for bitstring in bitstrings]) | ||
|
||
purity_unbiased = purity * num_shots / (num_shots - 1) - (2**num_qubits) / (num_shots - 1) | ||
|
||
return purity_unbiased |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I know it's a common code pattern in Cirq but it's a harmful practice. please pass
rng
tounitaries_to_moment
instead