diff --git a/qadence/backends/pyqtorch/backend.py b/qadence/backends/pyqtorch/backend.py index 6378d365..e303533f 100644 --- a/qadence/backends/pyqtorch/backend.py +++ b/qadence/backends/pyqtorch/backend.py @@ -108,7 +108,7 @@ def circuit(self, circuit: QuantumCircuit) -> ConvertedCircuit: original_circ = circuit if len(passes) > 0: circuit = transpile(*passes)(circuit) - # setting noise on blocks + # Setting noise in the circuit. if self.config.noise: set_noise(circuit, self.config.noise) @@ -136,8 +136,6 @@ def observable(self, observable: AbstractBlock, n_qubits: int) -> ConvertedObser scale_primitive_blocks_only, ] block = transpile(*transpilations)(observable) # type: ignore[call-overload] - # we do not set noise on the observable blocks - # as this would not be correct when computing expectations operations = convert_block(block, n_qubits, self.config) native = pyq.Observable(operations=operations) return ConvertedObservable(native=native, abstract=block, original=observable) diff --git a/tests/qadence/test_noise/test_digital_noise.py b/tests/qadence/test_noise/test_digital_noise.py index 60f50363..d65409c7 100644 --- a/tests/qadence/test_noise/test_digital_noise.py +++ b/tests/qadence/test_noise/test_digital_noise.py @@ -104,20 +104,28 @@ def test_expectation_digital_noise(noisy_config: NoiseProtocol | list[NoiseProto circuit = QuantumCircuit(2, block) observable = hamiltonian_factory(circuit.n_qubits, detuning=Z) noise = NoiseHandler(noisy_config, {"error_probability": 0.1}) + backend = backend_factory(backend=BackendName.PYQTORCH, diff_mode=DiffMode.AD) # Construct a quantum model. model = QuantumModel(circuit=circuit, observable=observable) noiseless_expectation = model.expectation(values={}) + (pyqtorch_circ, pyqtorch_obs, embed, params) = backend.convert(circuit, observable) + native_noisy_expectation = backend.expectation( + pyqtorch_circ, pyqtorch_obs, embed(params, {}), noise=noise + ) + assert not torch.allclose(noiseless_expectation, native_noisy_expectation) + noisy_model = QuantumModel(circuit=circuit, observable=observable, noise=noise) - noisy_expectation = noisy_model.expectation(values={}) - assert not torch.allclose(noiseless_expectation, noisy_expectation) + noisy_model_expectation = noisy_model.expectation(values={}) + assert torch.allclose(noisy_model_expectation, native_noisy_expectation) - backend = backend_factory(backend=BackendName.PYQTORCH, diff_mode=DiffMode.AD) (pyqtorch_circ, pyqtorch_obs, embed, params) = backend.convert(circuit, observable) - native_expectation = backend.expectation(pyqtorch_circ, pyqtorch_obs, embed(params, {})) + noisy_converted_model_expectation = backend.expectation( + pyqtorch_circ, pyqtorch_obs, embed(params, {}) + ) - assert torch.allclose(noisy_expectation, native_expectation) + assert torch.allclose(noisy_converted_model_expectation, native_noisy_expectation) @pytest.mark.parametrize(