From 92592ab7ff73478bee6597da31cfd9e837b5605a Mon Sep 17 00:00:00 2001 From: Gadi Aleksandrowicz Date: Mon, 25 Nov 2024 11:28:10 +0200 Subject: [PATCH] Fixed a bug in pauli truncation and add relevant test --- src/framework/circuit.hpp | 7 ++++++- .../backends/aer_simulator/test_save_expval.py | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/framework/circuit.hpp b/src/framework/circuit.hpp index ef79862ee7..b37b5483a8 100644 --- a/src/framework/circuit.hpp +++ b/src/framework/circuit.hpp @@ -683,6 +683,11 @@ void Circuit::set_params(bool truncation) { void Circuit::remap_qubits(Op &op) const { // truncate save_expval if (op.type == OpType::save_expval || op.type == OpType::save_expval_var) { + // map each qubit to its location in the pauli strings + std::unordered_map ops_pauli_qubit_map; + for (size_t i = 0; i < op.qubits.size(); ++i) { + ops_pauli_qubit_map[op.qubits[i]] = op.qubits.size() - 1 - i; + } int_t nparams = op.expval_params.size(); for (int_t i = 0; i < nparams; i++) { std::string &pauli = std::get<0>(op.expval_params[i]); @@ -690,7 +695,7 @@ void Circuit::remap_qubits(Op &op) const { new_pauli.resize(qubitmap_.size()); for (auto q = qubitmap_.cbegin(); q != qubitmap_.cend(); q++) { new_pauli[qubitmap_.size() - 1 - q->second] = - pauli[pauli.size() - 1 - q->first]; + pauli[ops_pauli_qubit_map[q->first]]; } pauli = new_pauli; } diff --git a/test/terra/backends/aer_simulator/test_save_expval.py b/test/terra/backends/aer_simulator/test_save_expval.py index 36131907f5..b602e16c76 100644 --- a/test/terra/backends/aer_simulator/test_save_expval.py +++ b/test/terra/backends/aer_simulator/test_save_expval.py @@ -271,3 +271,21 @@ def test_save_expval_var_stabilizer_pauli_cache_blocking(self, method, device, p blocking_qubits=2, max_parallel_threads=1, ) + + @supported_methods( + [ + "automatic", + "stabilizer", + "statevector", + "density_matrix", + "matrix_product_state", + "tensor_network", + ], + ) + def test_save_expval_truncation(self, method, device): + """Test save expval when qubits are not in use and are truncated""" + circ = QuantumCircuit(3) + circ.x(1) + oper = qi.Pauli("ZZ") + qubits = [1, 2] # qubit 0 will be truncated + self._test_save_expval(circ, oper, qubits, False, method=method, device=device)