From aac35ae0f2d6b9d46498ab2e26eb4f3c5f4cba55 Mon Sep 17 00:00:00 2001 From: Michael Broughton Date: Sat, 3 Apr 2021 02:07:09 -0700 Subject: [PATCH] added docstring snippet. --- .../ops/noise/noisy_sampled_expectation_op.py | 33 +++++++++++++++++++ .../noisy_sampled_expectation_op_test.py | 2 +- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op.py b/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op.py index eee7ae100..b40663371 100644 --- a/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op.py +++ b/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op.py @@ -32,6 +32,39 @@ def sampled_expectation(programs, symbol_names, symbol_values, pauli_sums, calculated after each run. Once all the runs are finished, these quantities are averaged together. + + >>> # Prepare some inputs. + >>> qubit = cirq.GridQubit(0, 0) + >>> my_symbol = sympy.Symbol('alpha') + >>> my_circuit_tensor = tfq.convert_to_tensor([ + ... cirq.Circuit( + ... cirq.H(qubit) ** my_symbol, + ... cirq.depolarize(0.01)(qubit) + ... ) + ... ]) + >>> my_values = np.array([[0.123]]) + >>> my_paulis = tfq.convert_to_tensor([[ + ... 3.5 * cirq.X(qubit) - 2.2 * cirq.Y(qubit) + ... ]]) + >>> my_num_samples = np.array([[100]]) + >>> # This op can now be run with: + >>> output = tfq.noise.sampled_expectation( + ... my_circuit_tensor, ['alpha'], my_values, my_paulis, my_num_samples) + >>> output + tf.Tensor([[0.71530885]], shape=(1, 1), dtype=float32) + + + In order to make the op differentiable, a `tfq.differentiator` object is + needed. see `tfq.differentiators` for more details. Below is a simple + example of how to make the from the above code block differentiable: + + + >>> diff = tfq.differentiators.ForwardDifference() + >>> my_differentiable_op = diff.generate_differentiable_op( + ... sampled_op=tfq.noise.sampled_expectation + ... ) + + Args: programs: `tf.Tensor` of strings with shape [batch_size] containing the string representations of the circuits to be executed. diff --git a/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op_test.py b/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op_test.py index d0a06be19..fb15e9861 100644 --- a/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op_test.py +++ b/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op_test.py @@ -262,7 +262,7 @@ def test_simulate_consistency(self, batch_size, n_qubits, noisy): cirq_exps = batch_util.batch_calculate_expectation( circuit_batch, resolver_batch, batch_pauli_sums, cirq.DensityMatrixSimulator() if noisy else cirq.Simulator()) - tol = 0.35 if noisy else 0.25 + tol = 0.35 self.assertAllClose(cirq_exps, op_exps, atol=tol, rtol=tol) @parameterized.parameters([{