# Revised code snippet: Calculate PauliString expectation value from state vector
```python
def expectation_from_state_vector(self, state_vector: np.ndarray, qubit_map: Mapping[TKey, int]) -> float:
"""
Evaluate the expectation value of this PauliString given a state vector.
Args:
state_vector: An array representing a valid state vector.
qubit_map: A map from all qubits used in this PauliString to the
indices of the qubits that `state` is defined over.
Returns:
The expectation value of the input state.
"""
# If state_vector is 1D, reshape it to be a multidimensional tensor
if len(state_vector.shape) == 1:
num_qubits = state_vector.shape[0].bit_length() - 1
state_vector = np.reshape(state_vector, (2,) * num_qubits)
# Create a copy of the state vector
ket = np.copy(state_vector)
# Apply Pauli operators to the state vector
for qubit, pauli in self.items():
# Create a buffer to store the intermediate calculation
buffer = np.empty(ket.shape, dtype=state_vector.dtype)
# Specify the target tensor and the qubit axis for applying the unitary
args = protocols.ApplyUnitaryArgs(
target_tensor=ket, available_buffer=buffer, axes=(qubit_map[qubit],)
)
# Apply the Pauli operator to the state vector
ket = protocols.apply_unitary(pauli, args)
# Calculate the expectation value of the input state using tensor dot product
expectation_value = np.tensordot(state_vector.conj(), ket, axes=len(ket.shape)).item()
# Multiply the expectation value by the coefficient of the PauliString
return self.coefficient * expectation_value
Note: The code has been revised to include clear variable names, added comments, and improved code structure to enhance human readability.
| Associated Context | |
| ------------------------------------------ | ---------------------------------------- |
| Type | Code Snippet ( ***.py*** ) |
| Associated Tags | `cirq` `https://github.com/davidmerwin` `http://quantumai.google/cirq` |
| Description | 'No Description Provided' |
| Related Links | [https://github.com/davidmerwin](https://github.com/davidmerwin)<br>[http://quantumai.google/cirq](http://quantumai.google/cirq) |
| Related People | [David Merwin](mailto:davidmerwin1992@gmail.com), [David Jeffrey Merwin](mailto:merwin1992@protonmail.com), [CIRQ](mailto:cirq-maintainers@googlegroups.com), [Jack C](mailto:chengzp.1@gmail.com) |
| Sensitive Information | No Sensitive Information Detected |
| Shareable Link | https://davidmerwin.pieces.cloud/?p=007f4db189 |