Skip to content

Commit

Permalink
[Bugfix] Fix mean when empty tensor for readout (#308)
Browse files Browse the repository at this point in the history
Solving the edge case when mean of an empty tensor returns nan

---------
  • Loading branch information
chMoussa authored Jan 8, 2025
1 parent eeb2eb8 commit 54293af
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
6 changes: 5 additions & 1 deletion pyqtorch/noise/readout.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,11 @@ def create_confusion_matrices(noise_matrix: Tensor, error_probability: float) ->
confusion_matrices = []
for i in range(noise_matrix.size()[1]):
column_tensor = noise_matrix[:, i]
flip_proba = column_tensor[column_tensor < error_probability].mean().item()
flip_proba = (
flip_proba.mean().item()
if len(flip_proba := column_tensor[column_tensor < error_probability]) > 0
else 0.0
)
confusion_matrix = torch.tensor(
[[1.0 - flip_proba, flip_proba], [flip_proba, 1.0 - flip_proba]],
dtype=torch.float64,
Expand Down
12 changes: 12 additions & 0 deletions tests/test_readout.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from pyqtorch.noise.readout import (
WhiteNoise,
bs_bitflip_corruption,
create_confusion_matrices,
create_noise_matrix,
sample_to_matrix,
)
Expand All @@ -19,6 +20,17 @@
from pyqtorch.utils_distributions import js_divergence, js_divergence_counters


def test_noise_matrix():
noise_mat = torch.tensor([[0.5679, 0.7676]])
zero_prob_mat = torch.tensor(
[[1.0, 0.0], [0.0, 1.0]],
dtype=torch.float64,
)
assert torch.allclose(
create_confusion_matrices(noise_mat, 0.1), torch.stack([zero_prob_mat] * 2)
)


@pytest.mark.parametrize(
"error_probability, counters, exp_corrupted_counters, n_qubits",
[
Expand Down

0 comments on commit 54293af

Please sign in to comment.