Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Explicitly convert
prob
interface in `ProbsMP.process_density_matri…
…x` (#6737) **Context:** Previous `ProbsMP.process_density_matrix` has potential to alter the interface. Here we convert it explicitly. Specifically, when dealing with batched density matrices, the previous `ProbabilityMP` did not track the interface of input `density_matrix`. ```python import numpy as np import pennylane as qml from pennylane.measurements import ProbabilityMP as OriginalProbabilityMP from pennylane.typing import TensorLike from pennylane.wires import Wires class CustomProbabilityMP(OriginalProbabilityMP): """Custom ProbabilityMP overriding process_density_matrix.""" def process_density_matrix(self, density_matrix: TensorLike, wire_order: Wires): if len(np.shape(density_matrix)) == 2: prob = qml.math.diagonal(density_matrix) else: prob = qml.math.array( [qml.math.diagonal(density_matrix[i]) for i in range(np.shape(density_matrix)[0])] ) # Commented out convert_like to simulate behavior without it. # prob = qml.math.convert_like(prob, density_matrix) # Creating a pseudo-state using the diagonal probabilities p_state = qml.math.sqrt(prob) return self.process_state(p_state, wire_order) # Instantiate the custom ProbabilityMP class custom_prob_mp = CustomProbabilityMP() # Define a density matrix as a NumPy array density_matrix = qml.math.array(np.array([[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], ]), like='torch') # Define the wire order wire_order = Wires([0, 1]) # Attempt to call process_density_matrix without convert_like result = custom_prob_mp.process_density_matrix(density_matrix, wire_order) print("Result without convert_like:", result) # Result without convert_like: [[0.5 0.5] # [0.5 0.5]] ``` With the fixed `ProbabilityMP` we have ```python # Instantiate the custom ProbabilityMP class with convert_like uncommented new_prob_mp = OriginalProbabilityMP() # Use qml.math.convert_like internally to ensure compatibility result = new_prob_mp.process_density_matrix(density_matrix, wire_order) print("Result with convert_like:", result) # Result with convert_like: tensor([[0.5000, 0.5000], # [0.5000, 0.5000]], dtype=torch.float64) ``` **Description of the Change:** Enforce the probs to match input interface via `qml.math.convert_like` **Benefits:** This PR is blocking #6684. Its merge into master will free new `default.mixed` from many roundabout solutions. **Possible Drawbacks:** **Related GitHub Issues:**
- Loading branch information