Invalid 1D state-vector lengths bypass shape validation in Pauli expectation calculations
Description
PauliString.expectation_from_state_vector does not correctly validate the shape of one-dimensional state vectors whose lengths are not powers of two.
For invalid state vectors with lengths such as 3, 5, or 7, the intended shape-validation check can be bypassed. Depending on the execution path, this results in downstream reshape or normalization errors instead of a clear ValueError indicating an invalid state-vector shape.
A related validation-order issue exists in LinearCombinationOfPauliStrings.expectation_from_state_vector. When the state vector has an invalid length, qubit-mapping validation may raise a misleading error before the state-vector shape is checked.
Steps to Reproduce
Case 1: PauliString
import numpy as np
import cirq
q0 = cirq.LineQubit(0)
ps = cirq.Z(q0)
bad_state = np.zeros(3, dtype=np.complex128)
ps.expectation_from_state_vector(
bad_state,
{q0: 0},
check_preconditions=False,
)
Actual behavior:
The method reaches an internal reshape operation and raises:
ValueError: cannot reshape array of size 3 into shape (2,)
Case 2: LinearCombinationOfPauliStrings
import numpy as np
import cirq
qubits = cirq.LineQubit.range(3)
lc = cirq.PauliSum.from_pauli_strings([
cirq.X(qubits[0]),
cirq.X(qubits[1]),
cirq.X(qubits[2]),
])
state_7 = np.zeros(7, dtype=np.complex128)
lc.expectation_from_state_vector(
state_7,
qubit_map={q: i for i, q in enumerate(qubits)},
)
Actual behavior:
The method raises a misleading qubit-mapping error, indicating that the mapping is invalid for a state over two qubits, instead of reporting that the state vector has an invalid length.
Expected Behavior
Both methods should validate the state-vector shape before performing operations that depend on the number of qubits or the qubit mapping.
For a one-dimensional state vector, its length must be a positive power of two. Invalid lengths should raise a clear ValueError during initial validation rather than causing downstream reshape, normalization, or misleading qubit-mapping errors.
Environment
- Cirq version:
1.8.0.dev0 - Commit:
14a2359d44acf5d60df89344995b6121c913c163
Additional Notes
The issue appears to involve both the state-vector shape-validation logic and the order in which validation is performed.
Regression tests should cover invalid one-dimensional state-vector lengths, including 3, 5, and 7, for both PauliString and LinearCombinationOfPauliStrings, ensuring that an appropriate shape-related ValueError is raised.
I would be happy to contribute a fix and regression tests if this issue is confirmed.
@NiranjanRSoorej06 Thank you for this report. This does indeed look like a bug.
Hi @mhucka , I hope the PR looks good. Please do mention suggestions, if any. Thank you.