Skip to content
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

Add stim.FlipSimulator.broadcast_pauli_errors #678

Merged
merged 7 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions doc/python_api_reference_vDev.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ API references for stable versions are kept on the [stim github wiki](https://gi
- [`stim.FlipSimulator`](#stim.FlipSimulator)
- [`stim.FlipSimulator.__init__`](#stim.FlipSimulator.__init__)
- [`stim.FlipSimulator.batch_size`](#stim.FlipSimulator.batch_size)
- [`stim.FlipSimulator.broadcast_pauli_errors`](#stim.FlipSimulator.broadcast_pauli_errors)
- [`stim.FlipSimulator.do`](#stim.FlipSimulator.do)
- [`stim.FlipSimulator.get_detector_flips`](#stim.FlipSimulator.get_detector_flips)
- [`stim.FlipSimulator.get_measurement_flips`](#stim.FlipSimulator.get_measurement_flips)
Expand Down Expand Up @@ -6153,6 +6154,51 @@ def batch_size(
"""
```

<a name="stim.FlipSimulator.broadcast_pauli_errors"></a>
```python
# stim.FlipSimulator.broadcast_pauli_errors

# (in class stim.FlipSimulator)
def broadcast_pauli_errors(
self,
*,
pauli: Union[str, int],
mask: np.ndarray,
) -> None:
"""Applies a pauli over all qubits in all simulation indices, filtered by mask.
This conversation was marked as resolved.
Show resolved Hide resolved

Args:
pauli: The pauli, specified as an integer or string.
Uses the convention 0=I, 1=X, 2=Y, 3=Z.
Any value from [0, 1, 2, 3, 'X', 'Y', 'Z', 'I', '_'] is allowed.
mask: a np.bool_ array with shape (qubit, simulation_instance)
This conversation was marked as resolved.
Show resolved Hide resolved
The pauli error is only applied to qubits q and simulation indices k
where mask[q, k] == True

Examples:
>>> import stim
>>> import numpy as np
>>> sim = stim.FlipSimulator(
... batch_size=2,
... num_qubits=3,
... disable_stabilizer_randomization=True,
... )
>>> sim.broadcast_pauli_errors(
... pauli='X',
... mask=np.asarray([[True, False],[False, False],[True, True]]),
... )
>>> sim.peek_pauli_flips()
[stim.PauliString("+X_X"), stim.PauliString("+__X")]

>>> sim.broadcast_pauli_errors(
... pauli='Z',
... mask=np.asarray([[False, True],[False, False],[True, True]]),
... )
>>> sim.peek_pauli_flips()
[stim.PauliString("+X_Y"), stim.PauliString("+Z_Y")]
"""
```

<a name="stim.FlipSimulator.do"></a>
```python
# stim.FlipSimulator.do
Expand Down
38 changes: 38 additions & 0 deletions doc/stim.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -4670,6 +4670,44 @@ class FlipSimulator:
>>> sim.batch_size
42
"""
def broadcast_pauli_errors(
self,
*,
pauli: Union[str, int],
mask: np.ndarray,
) -> None:
"""Applies a pauli over all qubits in all simulation indices, filtered by mask.

Args:
pauli: The pauli, specified as an integer or string.
Uses the convention 0=I, 1=X, 2=Y, 3=Z.
Any value from [0, 1, 2, 3, 'X', 'Y', 'Z', 'I', '_'] is allowed.
mask: a np.bool_ array with shape (qubit, simulation_instance)
The pauli error is only applied to qubits q and simulation indices k
where mask[q, k] == True

Examples:
>>> import stim
>>> import numpy as np
>>> sim = stim.FlipSimulator(
... batch_size=2,
... num_qubits=3,
... disable_stabilizer_randomization=True,
... )
>>> sim.broadcast_pauli_errors(
... pauli='X',
... mask=np.asarray([[True, False],[False, False],[True, True]]),
... )
>>> sim.peek_pauli_flips()
[stim.PauliString("+X_X"), stim.PauliString("+__X")]

>>> sim.broadcast_pauli_errors(
... pauli='Z',
... mask=np.asarray([[False, True],[False, False],[True, True]]),
... )
>>> sim.peek_pauli_flips()
[stim.PauliString("+X_Y"), stim.PauliString("+Z_Y")]
"""
def do(
self,
obj: Union[stim.Circuit, stim.CircuitInstruction, stim.CircuitRepeatBlock],
Expand Down
38 changes: 38 additions & 0 deletions glue/python/src/stim/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -4670,6 +4670,44 @@ class FlipSimulator:
>>> sim.batch_size
42
"""
def broadcast_pauli_errors(
self,
*,
pauli: Union[str, int],
mask: np.ndarray,
) -> None:
"""Applies a pauli over all qubits in all simulation indices, filtered by mask.

Args:
pauli: The pauli, specified as an integer or string.
Uses the convention 0=I, 1=X, 2=Y, 3=Z.
Any value from [0, 1, 2, 3, 'X', 'Y', 'Z', 'I', '_'] is allowed.
mask: a np.bool_ array with shape (qubit, simulation_instance)
The pauli error is only applied to qubits q and simulation indices k
where mask[q, k] == True

Examples:
>>> import stim
>>> import numpy as np
>>> sim = stim.FlipSimulator(
... batch_size=2,
... num_qubits=3,
... disable_stabilizer_randomization=True,
... )
>>> sim.broadcast_pauli_errors(
... pauli='X',
... mask=np.asarray([[True, False],[False, False],[True, True]]),
... )
>>> sim.peek_pauli_flips()
[stim.PauliString("+X_X"), stim.PauliString("+__X")]

>>> sim.broadcast_pauli_errors(
... pauli='Z',
... mask=np.asarray([[False, True],[False, False],[True, True]]),
... )
>>> sim.peek_pauli_flips()
[stim.PauliString("+X_Y"), stim.PauliString("+Z_Y")]
"""
def do(
self,
obj: Union[stim.Circuit, stim.CircuitInstruction, stim.CircuitRepeatBlock],
Expand Down
98 changes: 98 additions & 0 deletions src/stim/simulators/frame_simulator.pybind.cc
Original file line number Diff line number Diff line change
Expand Up @@ -770,4 +770,102 @@ void stim_pybind::pybind_frame_simulator_methods(
[stim.PauliString("+YX__")]
)DOC")
.data());

c.def(
"broadcast_pauli_errors",
[](FrameSimulator<MAX_BITWORD_WIDTH> &self,
const pybind11::object &pauli,
const pybind11::object &mask
) {
uint8_t p = 255;
try {
p = pybind11::cast<uint8_t>(pauli);
if (p >= 4) {
throw pybind11::cast_error();
}
} catch (const pybind11::cast_error &) {
try {
std::string s = pybind11::cast<std::string>(pauli);
if (s == "X") {
p = 1;
} else if (s == "Y") {
p = 2;
} else if (s == "Z") {
p = 3;
} else if (s == "I" || s == "_") {
p = 0;
} else {
throw pybind11::cast_error();
}
} catch (const pybind11::cast_error &) {
throw std::invalid_argument(
"broadcast_pauli_errors only accepts pauli arguments in ['I', '_', 'X', 'Y', 'Z', 0,1,2,3]");
}
}

bool flip_z_part = p & 2;
bool flip_x_part = (0b0110 >> p) & 1; // parity of 2 bit number


if (!pybind11::isinstance<pybind11::array_t<bool>>(mask)) {
throw std::invalid_argument(
"broadcast_pauli_errors can only accept mask that is a 2D array of np.bool_");
}
const pybind11::array_t<bool> &arr = pybind11::cast<pybind11::array_t<bool>>(mask);

if (arr.ndim() != 2) {
throw std::invalid_argument(
"broadcast_pauli_errors can only accept mask that is a 2D array of np.bool_");
}

size_t major = arr.shape(0);
size_t minor = arr.shape(1);
auto u = arr.unchecked<2>();
This conversation was marked as resolved.
Show resolved Hide resolved
for (size_t i = 0; i < major; i++){
for (size_t j = 0; j < minor; j++){
auto b = u.data(i, j);
self.x_table[i][j] ^= *b & flip_x_part;
self.z_table[i][j] ^= *b & flip_z_part;
}
}
},
pybind11::kw_only(),
pybind11::arg("pauli"),
pybind11::arg("mask"),
clean_doc_string(R"DOC(
@signature def broadcast_pauli_errors(self, *, pauli: Union[str, int], mask: np.ndarray) -> None:
Applies a pauli over all qubits in all simulation indices, filtered by mask.

Args:
pauli: The pauli, specified as an integer or string.
Uses the convention 0=I, 1=X, 2=Y, 3=Z.
Any value from [0, 1, 2, 3, 'X', 'Y', 'Z', 'I', '_'] is allowed.
mask: a np.bool_ array with shape (qubit, simulation_instance)
The pauli error is only applied to qubits q and simulation indices k
where mask[q, k] == True

Examples:
>>> import stim
>>> import numpy as np
>>> sim = stim.FlipSimulator(
... batch_size=2,
... num_qubits=3,
... disable_stabilizer_randomization=True,
... )
>>> sim.broadcast_pauli_errors(
... pauli='X',
... mask=np.asarray([[True, False],[False, False],[True, True]]),
... )
>>> sim.peek_pauli_flips()
[stim.PauliString("+X_X"), stim.PauliString("+__X")]

>>> sim.broadcast_pauli_errors(
... pauli='Z',
... mask=np.asarray([[False, True],[False, False],[True, True]]),
... )
>>> sim.peek_pauli_flips()
[stim.PauliString("+X_Y"), stim.PauliString("+Z_Y")]

)DOC")
.data());
}
137 changes: 137 additions & 0 deletions src/stim/simulators/frame_simulator_pybind_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,143 @@ def test_set_pauli_flip():
stim.PauliString('XZ___'),
]

def test_broadcast_pauli_errors():
sim = stim.FlipSimulator(
This conversation was marked as resolved.
Show resolved Hide resolved
batch_size=2,
num_qubits=3,
disable_stabilizer_randomization=True,
)
sim.broadcast_pauli_errors(
pauli='X',
mask=np.asarray([
[True, False],
[False, False],
[True, True]]
),
)
peek = sim.peek_pauli_flips()
assert peek == [
stim.PauliString("+X_X"),
stim.PauliString("+__X")
]
sim.broadcast_pauli_errors(
pauli='Z',
mask=np.asarray([
[True, True],
[True, False],
[False, False]]
),
)
peek = sim.peek_pauli_flips()
assert peek == [
stim.PauliString("+YZX"),
stim.PauliString("+Z_X")
]
sim.broadcast_pauli_errors(
This conversation was marked as resolved.
Show resolved Hide resolved
pauli='Y',
mask=np.asarray([
[True, False],
[False, True],
[False, True]]
),
)
peek = sim.peek_pauli_flips()
assert peek == [
stim.PauliString("+_ZX"),
stim.PauliString("+ZYZ")
]
sim.broadcast_pauli_errors(
pauli='I',
mask=np.asarray([
[True, True],
[False, True],
[True, True]]
),
)
peek = sim.peek_pauli_flips()
assert peek == [
stim.PauliString("+_ZX"),
stim.PauliString("+ZYZ")
]

# do it again with ints
sim = stim.FlipSimulator(
batch_size=2,
num_qubits=3,
disable_stabilizer_randomization=True,
)
sim.broadcast_pauli_errors(
pauli=1,
mask=np.asarray([
[True, False],
[False, False],
[True, True]]
),
)
peek = sim.peek_pauli_flips()
assert peek == [
stim.PauliString("+X_X"),
stim.PauliString("+__X")
]
sim.broadcast_pauli_errors(
pauli=3,
mask=np.asarray([
[True, True],
[True, False],
[False, False]]
),
)
peek = sim.peek_pauli_flips()
assert peek == [
stim.PauliString("+YZX"),
stim.PauliString("+Z_X")
]
sim.broadcast_pauli_errors(
pauli=2,
mask=np.asarray([
[True, False],
[False, True],
[False, True]]
),
)
peek = sim.peek_pauli_flips()
assert peek == [
stim.PauliString("+_ZX"),
stim.PauliString("+ZYZ")
]
sim.broadcast_pauli_errors(
pauli=0,
mask=np.asarray([
[True, True],
[False, True],
[True, True]]
),
)
peek = sim.peek_pauli_flips()
assert peek == [
stim.PauliString("+_ZX"),
stim.PauliString("+ZYZ")
]

with pytest.raises(Exception):
This conversation was marked as resolved.
Show resolved Hide resolved
sim.broadcast_pauli_errors(
pauli='whoops',
mask=np.asarray([
[True, True],
[False, True],
[True, True]]
),
)
with pytest.raises(Exception):
This conversation was marked as resolved.
Show resolved Hide resolved
sim.broadcast_pauli_errors(
pauli=4,
mask=np.asarray([
[True, True],
[False, True],
[True, True]]
),
)


def test_repro_heralded_pauli_channel_1_bug():
circuit = stim.Circuit("""
Expand Down
Loading