Skip to content

Commit c2f3714

Browse files
SampleMP.process_samples does not raise an error when the observable is multiplied by a complex coefficient (#8271)
**Context:** If an observable is multiplied by a complex coefficient, the `indices` array created within `process_raw_samples` as `indices = samples @ powers_of_two` might be created with complex values. This creates issues when we try to use them as actual indices. **Description of the Change:** We move the conversion to the requested `dtype` selected by the user just before returning, so we avoid any possible implicit casting unintentionally performed under the hood in the execution workflow. **Benefits:** `process_samples` works with complex values when the `dtype` argument is specified **Possible Drawbacks:** None that I can think of. **Related GitHub Issues:** None
1 parent 58570ba commit c2f3714

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

‎doc/releases/changelog-dev.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
* The `qml.sample` function can now receive an optional `dtype` parameter
77
which sets the type and precision of the samples returned by this measurement process.
88
[(#8189)](https://github.com/PennyLaneAI/pennylane/pull/8189)
9+
[(#8271)](https://github.com/PennyLaneAI/pennylane/pull/8271)
910

1011
* The Resource estimation toolkit was upgraded and has migrated from
1112
:mod:`~.labs` to PennyLane as the :mod:`~.estimator` module.

‎pennylane/measurements/process_samples.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@ def process_raw_samples(
5050
5151
"""
5252

53-
samples = samples.astype(dtype) if dtype is not None else samples
5453
wire_map = dict(zip(wire_order, range(len(wire_order))))
5554
mapped_wires = [wire_map[w] for w in mp.wires]
5655
# Select the samples from samples that correspond to ``shot_range`` if provided
@@ -70,6 +69,7 @@ def process_raw_samples(
7069
# pylint: disable=protected-access
7170
if mp.obs is None and not isinstance(mp.mv, MeasurementValue) and mp._eigvals is None:
7271
# if no observable was provided then return the raw samples
72+
samples = samples.astype(dtype) if dtype is not None else samples
7373
return samples if bin_size is None else samples.T.reshape(num_wires, bin_size, -1)
7474

7575
# If we're sampling observables
@@ -97,4 +97,5 @@ def process_raw_samples(
9797
else:
9898
samples = eigvals[indices]
9999

100+
samples = samples.astype(dtype) if dtype is not None else samples
100101
return samples if bin_size is None else samples.reshape((bin_size, -1))

‎tests/measurements/test_sample.py‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -408,11 +408,27 @@ class DummyOp(Operator): # pylint: disable=too-few-public-methods
408408
with pytest.raises(EigvalsUndefinedError, match="Cannot compute samples of"):
409409
qml.sample(op=DummyOp(0)).process_samples(samples=np.array([[1, 0]]), wire_order=[0])
410410

411-
def test_process_samples_dtype(self):
411+
@pytest.mark.parametrize(
412+
"coeffs, dtype",
413+
[
414+
(1, "int8"),
415+
(1, "int16"),
416+
(1, "int32"),
417+
(1, "int64"),
418+
(1, "float16"),
419+
(1, "float32"),
420+
(1, "float64"),
421+
(1j, "complex64"),
422+
(1 + 1j, "complex128"),
423+
],
424+
)
425+
def test_process_samples_dtype(self, coeffs, dtype):
412426
"""Test that the dtype argument changes the dtype of the returned samples."""
413427
samples = np.zeros(10, dtype="int64")
414-
processed_samples = qml.sample(dtype="int8").process_samples(samples, wire_order=[0])
415-
assert processed_samples.dtype == np.dtype("int8")
428+
processed_samples = qml.sample(coeffs * qml.X(0), dtype=dtype).process_samples(
429+
samples, wire_order=[0]
430+
)
431+
assert processed_samples.dtype == np.dtype(dtype)
416432

417433
def test_sample_allowed_with_parameter_shift(self):
418434
"""Test that qml.sample doesn't raise an error with parameter-shift and autograd."""

0 commit comments

Comments
 (0)