Ejemplo n.º 1
0
    def test_sampled_expectation_empty(self, op_and_sim, n_qubits,
                                       symbol_names, max_paulisum_length):
        """Test empty circuits for sampled expectation using cirq and tfq."""
        op = op_and_sim[0]
        sim = op_and_sim[1]

        qubits = cirq.GridQubit.rect(1, n_qubits)
        circuit_batch = [cirq.Circuit() for _ in range(BATCH_SIZE)]
        resolver_batch = [cirq.ParamResolver({}) for _ in range(BATCH_SIZE)]

        symbol_values_array = np.array([[0.0 for _ in symbol_names]
                                        for _ in resolver_batch])

        pauli_sums = util.random_pauli_sums(qubits, max_paulisum_length,
                                            BATCH_SIZE)
        num_samples = [[1000]] * BATCH_SIZE

        op_expectations = op(
            util.convert_to_tensor(circuit_batch), symbol_names,
            symbol_values_array,
            util.convert_to_tensor([[psum] for psum in pauli_sums]),
            num_samples)

        cirq_expectations = batch_util.batch_calculate_sampled_expectation(
            circuit_batch, resolver_batch, [[x] for x in pauli_sums],
            num_samples, sim)

        self.assertAllClose(op_expectations.numpy().flatten(),
                            cirq_expectations.flatten(),
                            rtol=1e-1,
                            atol=1e-1)
Ejemplo n.º 2
0
    def test_sampled_expectation(self, op_and_sim, n_qubits, symbol_names,
                                 max_paulisum_length):
        """Compute sampled expectations using cirq and tfq."""
        op = op_and_sim[0]
        sim = op_and_sim[1]

        qubits = cirq.GridQubit.rect(1, n_qubits)
        circuit_batch, resolver_batch = \
            util.random_symbol_circuit_resolver_batch(
                qubits, symbol_names, BATCH_SIZE)

        symbol_values_array = np.array(
            [[resolver[symbol] for symbol in symbol_names]
             for resolver in resolver_batch])

        pauli_sums = util.random_pauli_sums(qubits, max_paulisum_length,
                                            BATCH_SIZE)
        num_samples = [[2000]] * BATCH_SIZE

        op_expectations = op(
            util.convert_to_tensor(circuit_batch), symbol_names,
            symbol_values_array,
            util.convert_to_tensor([[psum] for psum in pauli_sums]),
            num_samples)

        cirq_expectations = batch_util.batch_calculate_sampled_expectation(
            circuit_batch, resolver_batch, [[x] for x in pauli_sums],
            num_samples, sim)

        self.assertAllClose(op_expectations.numpy().flatten(),
                            cirq_expectations.flatten(),
                            rtol=1e-1,
                            atol=1e-1)
Ejemplo n.º 3
0
    def test_no_circuit(self, sim):
        """Test functions with no circuits and empty arrays."""
        # (1) Test expectation
        results = batch_util.batch_calculate_expectation([], [], [[]], sim)
        self.assertDTypeEqual(results, np.float32)
        self.assertEqual(np.zeros(shape=(0, 0)).shape, results.shape)

        # (2) Test sampled_expectation
        results = batch_util.batch_calculate_sampled_expectation([], [], [[]],
                                                                 [[]], sim)
        self.assertDTypeEqual(results, np.float32)
        self.assertEqual(np.zeros(shape=(0, 0)).shape, results.shape)

        # (3) Test state
        results = batch_util.batch_calculate_state([], [], sim)
        self.assertDTypeEqual(results, np.complex64)
        if isinstance(sim, cirq.Simulator):
            self.assertEqual(np.zeros(shape=(0, 0)).shape, results.shape)
        else:
            self.assertEqual(np.zeros(shape=(0, 0, 0)).shape, results.shape)

        # (4) Test sampling
        results = batch_util.batch_sample([], [], [], sim)
        self.assertDTypeEqual(results, np.int8)
        self.assertEqual(np.zeros(shape=(0, 0, 0)).shape, results.shape)
Ejemplo n.º 4
0
    def test_empty_circuits(self, sim):
        """Test functions with empty circuits."""
        # Common preparation
        resolver_batch = [cirq.ParamResolver({}) for _ in range(BATCH_SIZE)]
        circuit_batch = [cirq.Circuit() for _ in range(BATCH_SIZE)]
        qubits = cirq.GridQubit.rect(1, N_QUBITS)
        ops = util.random_pauli_sums(qubits, PAULI_LENGTH, BATCH_SIZE)
        n_samples = [[1000] for _ in range(len(ops))]
        # If there is no op on a qubit, the expectation answer is -2.0
        true_expectation = (-2.0, )

        # (1) Test expectation
        results = batch_util.batch_calculate_expectation(
            circuit_batch, resolver_batch, [[x] for x in ops], sim)

        for _, _, result, _ in zip(circuit_batch, resolver_batch, results,
                                   ops):
            self.assertAllClose(true_expectation, result, rtol=1e-5, atol=1e-5)

        self.assertDTypeEqual(results, np.float32)

        # (2) Test sampled_expectation
        results = batch_util.batch_calculate_sampled_expectation(
            circuit_batch, resolver_batch, [[x] for x in ops], n_samples, sim)

        for _, _, result, _ in zip(circuit_batch, resolver_batch, results,
                                   ops):
            self.assertAllClose(true_expectation, result, rtol=1.0, atol=1e-1)

        self.assertDTypeEqual(results, np.float32)

        # (3) Test state
        results = batch_util.batch_calculate_state(circuit_batch,
                                                   resolver_batch, sim)

        for circuit, resolver, result in zip(circuit_batch, resolver_batch,
                                             results):
            r = _pad_state(sim, sim.simulate(circuit, resolver), 0)
            self.assertAllClose(r, result, rtol=1e-5, atol=1e-5)

        self.assertDTypeEqual(results, np.complex64)

        # (4) Test sampling
        n_samples = 2000 * (2**N_QUBITS)
        results = batch_util.batch_sample(circuit_batch, resolver_batch,
                                          n_samples, sim)

        for circuit, resolver, a in zip(circuit_batch, resolver_batch,
                                        results):
            state = sim.simulate(circuit, resolver)
            r = _sample_helper(sim, state, len(circuit.all_qubits()),
                               n_samples)
            self.assertAllClose(r, a, atol=1e-5)

        self.assertDTypeEqual(results, np.int32)
    def test_sampled_expectation_no_circuits(self, op_and_sim):
        """Test no circuits for states using cirq and tfq."""
        op = op_and_sim[0]
        sim = op_and_sim[1]

        circuit_batch = tf.raw_ops.Empty(shape=(0,), dtype=tf.string)
        empty_params = tf.raw_ops.Empty(shape=(0, 0), dtype=tf.float32)
        empty_ops = tf.raw_ops.Empty(shape=(0, 0), dtype=tf.string)
        empty_samples = tf.raw_ops.Empty(shape=(0, 0), dtype=tf.int32)

        op_exp = op(circuit_batch, [], empty_params, empty_ops,
                    empty_samples).numpy()
        cirq_exp = batch_util.batch_calculate_sampled_expectation([], [], [[]],
                                                                  [], sim)
        self.assertEqual(op_exp.shape, cirq_exp.shape)
Ejemplo n.º 6
0
    def test_batch_sampled_expectation(self, sim):
        """Test expectation."""
        qubits = cirq.GridQubit.rect(1, N_QUBITS)
        circuit_batch, resolver_batch = _get_mixed_batch(
            qubits + [cirq.GridQubit(9, 9)], SYMBOLS, BATCH_SIZE)

        ops = util.random_pauli_sums(qubits, PAULI_LENGTH, BATCH_SIZE)
        n_samples = [[1000] for _ in range(len(ops))]

        results = batch_util.batch_calculate_sampled_expectation(
            circuit_batch, resolver_batch, [[x] for x in ops], n_samples, sim)

        for circuit, resolver, result, op in zip(circuit_batch, resolver_batch,
                                                 results, ops):
            r = _expectation_helper(sim, circuit, resolver, op)
            self.assertAllClose(r, result, rtol=1.0, atol=1e-1)

        self.assertDTypeEqual(results, np.float32)
Ejemplo n.º 7
0
    def cirq_sampled_expectation(programs, symbol_names, symbol_values,
                                 pauli_sums, num_samples):
        """Calculate the sampled expectation value of circuits wrt some
        operator(s).

        Estimates the expectation value for all the `cirq.PauliSum`s in
        `pauli_sums` on each `cirq.Circuit` in `programs`. Each circuit will
        have the values in `symbol_values` resolved into the symbols in the
        circuit (with the ordering defined by `symbol_names`).

        ```python

        symbol_names = ['a', 'b', 'c']
        programs = tfq.convert_to_tensor(
            [cirq.Circuit(H(q0) ** sympy.Symbol('a'),
                          X(q1) ** sympy.Symbol('b'),
                          Y(q2) ** sympy.Symbol('c'))]
        )

        symbol_values = [[3,2,1]]
        pauli_sums = tfq.convert_to_tensor(
            [1.5 * cirq.Z(q0) * cirq.Z(q1)]
        )
        n_samples = [[100]]

        cirq_sampled_expectation(
            programs, symbol_names, sybmol_values, pauli_sums, n_samples)
        ```

        Would place the values of 3 into the Symbol labeled 'a', 2 into the
        symbol labeled 'b' and 1 into the symbol labeled 'c'. Then it would
        estimate the ZZ expectation on this circuit by draw samples from the
        circuit 100 times.

        Args:
            programs: `tf.Tensor` of strings with shape [batch_size] containing
                the string representations of the circuits to be executed.
            symbol_names: `tf.Tensor` of strings with shape [n_params], which
                is used to specify the order in which the values in
                `symbol_values` should be placed inside of the circuits in
                `programs`.
            symbol_values: `tf.Tensor` of real numbers with shape
                [batch_size, n_params] specifying parameter values to resolve
                into the circuits specified by programs, following the ordering
                dictated by `symbol_names`.
            pauli_sums: `tf.Tensor` of strings with shape [batch_size, n_ops]
                containing the string representation of the operators that will
                be used on all of the circuits in the expectation calculations.
            num_samples: `tf.Tensor` with `n_samples[i][j]` is equal to the
                number of samples to draw in each term of `pauli_sums[i][j]`
                when estimating the expectation.

        Returns:
            `tf.Tensor` with shape [batch_size, n_ops] that holds the
                expectation value for each circuit with each op applied to it
                (after resolving the corresponding parameters in).
        """
        _input_check_helper(programs, symbol_names, symbol_values)
        if not (pauli_sums.dtype == tf.dtypes.string):
            raise TypeError('pauli_sums tensor must be of type string.')
        if not (pauli_sums.shape[0] == programs.shape[0]) or \
            len(pauli_sums.shape) != 2:
            raise TypeError('pauli_sums tensor must have the same batch shape '
                            'as programs tensor.')

        if not (num_samples.dtype == tf.dtypes.int32 or
                num_samples.dtype == tf.dtypes.int64):
            raise TypeError('num_samples tensor must be of type int32 of '
                            'int64.')
        if not (num_samples.shape == pauli_sums.shape):
            raise TypeError('num_samples tensor must have the same shape '
                            'as pauli_sums tensor. got: {} expected: {}'.format(
                                num_samples.shape, pauli_sums.shape))
        if tf.less_equal(num_samples, 0).numpy().any():
            raise TypeError('num_samples contains sample value <= 0.')

        programs, resolvers = _batch_deserialize_helper(programs, symbol_names,
                                                        symbol_values)

        num_samples = num_samples.numpy().tolist()

        sum_inputs = []
        for sub_list in pauli_sums.numpy():
            to_append = []
            for x in sub_list:
                obj = pauli_sum_pb2.PauliSum()
                obj.ParseFromString(x)
                to_append.append(serializer.deserialize_paulisum(obj))
            sum_inputs.append(to_append)

        expectations = batch_util.batch_calculate_sampled_expectation(
            programs, resolvers, sum_inputs, num_samples, sampler)

        return expectations