Exemplo n.º 1
0
    def test_serialize_deserialize_special_case_one_qubit(self, gate):
        """Check output state equality."""
        q0 = cirq.GridQubit(0, 0)
        c = cirq.Circuit(gate(q0))

        c = cirq.resolve_parameters(c, cirq.ParamResolver({"alpha":
                                                           0.1234567}))
        before = c.unitary()
        c2 = serializer.deserialize_circuit(serializer.serialize_circuit(c))
        after = c2.unitary()
        self.assertAllClose(before, after)
Exemplo n.º 2
0
 def test_analytic_expectation_empty_circuit(self):
     """Test empty circuits"""
     test_op = cirq_ops._get_cirq_analytical_expectation(
         cirq.sim.sparse_simulator.Simulator())
     bits = cirq.GridQubit.rect(1, 5)
     test_pauli_sum = serializer.serialize_paulisum(
         cirq.PauliSum.from_pauli_strings([cirq.Z(bits[0])
                                           ])).SerializeToString()
     test_empty_circuit = serializer.serialize_circuit(
         cirq.Circuit()).SerializeToString()
     _ = test_op([test_empty_circuit], [], [[]], [[test_pauli_sum]])
Exemplo n.º 3
0
    def test_append_input_checking(self):
        """Check that the append op has correct input checking."""
        test_circuit = serializer.serialize_circuit(
            cirq.Circuit(cirq.X.on(cirq.GridQubit(0, 0)))).SerializeToString()
        with self.assertRaisesRegex(TypeError, 'Cannot convert \\[1\\]'):
            tfq_utility_ops.append_circuit([test_circuit], [1])
        with self.assertRaisesRegex(TypeError, 'Cannot convert \\[1\\]'):
            tfq_utility_ops.append_circuit([1], [test_circuit])
        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'Unparseable proto'):
            tfq_utility_ops.append_circuit(['wrong'], ['wrong'])
        with self.assertRaisesRegex(
                tf.errors.InvalidArgumentError,
                'programs and programs_to_append must have matching sizes.'):
            tfq_utility_ops.append_circuit([test_circuit],
                                           [test_circuit, test_circuit])
        with self.assertRaisesRegex(
                tf.errors.InvalidArgumentError,
                'programs and programs_to_append must have matching sizes.'):
            tfq_utility_ops.append_circuit([test_circuit, test_circuit],
                                           [test_circuit])
        with self.assertRaisesRegex(
                tf.errors.InvalidArgumentError,
                'programs and programs_to_append must have matching sizes'):
            tfq_utility_ops.append_circuit([], [test_circuit])

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'programs must be rank 1. Got rank 2'):
            tfq_utility_ops.append_circuit([[test_circuit, test_circuit]],
                                           [[test_circuit, test_circuit]])

        with self.assertRaisesRegex(TypeError,
                                    'missing 1 required positional argument'):
            # pylint: disable=no-value-for-parameter
            tfq_utility_ops.append_circuit([test_circuit])
            # pylint: enable=no-value-for-parameter

        with self.assertRaisesRegex(TypeError,
                                    '2 positional arguments but 3 were given'):
            # pylint: disable=too-many-function-args
            tfq_utility_ops.append_circuit([test_circuit], [test_circuit],
                                           [test_circuit])
            # pylint: enable=too-many-function-args

        # These tests really just makes sure we can cast output
        res = tfq_utility_ops.append_circuit([], [])

        self.assertDTypeEqual(res.numpy().astype(np.str), np.dtype('<U1'))
Exemplo n.º 4
0
    def test_cirq_analytical_expectation_op_inputs(self):
        """Test input checking in the state sim op."""
        test_op = cirq_ops._get_cirq_analytical_expectation(
            cirq.sim.sparse_simulator.Simulator())
        bits = cirq.GridQubit.rect(1, 5)
        test_circuit = serializer.serialize_circuit(
            cirq.testing.random_circuit(bits, MOMENT_DEPTH,
                                        0.9)).SerializeToString()
        test_pauli_sum = serializer.serialize_paulisum(
            cirq.PauliSum.from_pauli_strings([cirq.Z(bits[0])
                                              ])).SerializeToString()
        with self.assertRaisesRegex(
                tf.errors.InvalidArgumentError,
                'symbol_names tensor must be of type string'):
            _ = test_op([test_circuit], [0], [[0]], [[test_pauli_sum]])
        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'programs tensor must be of type string'):
            _ = test_op([0], ['rx'], [[0]], [test_pauli_sum])
        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'real-valued numeric tensor.'):
            _ = test_op([test_circuit], ['rx'], 'junk', [[test_pauli_sum]])
        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'size of symbol_names tensor must match'):
            _ = test_op([test_circuit], ['rx'], [[1, 1]], [[test_pauli_sum]])
        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'size of symbol_names tensor must match'):
            _ = test_op([test_circuit], ['rx', 'ry'], [[1]],
                        [[test_pauli_sum]])
        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'first dimension of symbol_values tensor'):
            _ = test_op([test_circuit, test_circuit], ['rx'], [[1]],
                        [test_pauli_sum])
        with self.assertRaisesRegex(
                tf.errors.InvalidArgumentError,
                'pauli_sums tensor must be of type string.'):
            _ = test_op([test_circuit], ['rx'], [[1]], 0)
        with self.assertRaisesRegex(
                tf.errors.InvalidArgumentError,
                'pauli_sums tensor must have the same batch shape'):
            _ = test_op([test_circuit], ['rx'], [[1]],
                        [[test_pauli_sum], [test_pauli_sum]])

        _ = test_op([test_circuit], ['rx'], [[1]], [[test_pauli_sum]])
        _ = test_op([test_circuit], [], [[]], [[test_pauli_sum]])
Exemplo n.º 5
0
 def recur(items_to_convert, curr_type=None):
     tensored_items = []
     for item in items_to_convert:
         if isinstance(item, (list, np.ndarray, tuple)):
             tensored_items.append(recur(item, curr_type))
         elif isinstance(item, (cirq.PauliSum, cirq.PauliString)) and\
                 not curr_type == cirq.Circuit:
             curr_type = cirq.PauliSum
             tensored_items.append(
                 serializer.serialize_paulisum(item).SerializeToString())
         elif isinstance(item, cirq.Circuit) and\
                 not curr_type == cirq.PauliSum:
             curr_type = cirq.Circuit
             tensored_items.append(
                 serializer.serialize_circuit(item).SerializeToString())
         else:
             raise TypeError("Incompatible item passed into "
                             " convert_to_tensor. Tensor detected type: {}."
                             " got: {}".format(curr_type, type(item)))
     return tensored_items
Exemplo n.º 6
0
    def test_cirq_sampling_op_inputs(self):
        """test input checking in the cirq sampling op."""
        test_op = cirq_ops._get_cirq_samples(
            cirq.sim.sparse_simulator.Simulator())

        bits = cirq.GridQubit.rect(1, 5)
        test_circuit = serializer.serialize_circuit(
            cirq.testing.random_circuit(bits, MOMENT_DEPTH,
                                        0.9)).SerializeToString()

        with self.assertRaisesRegex(
                tf.errors.InvalidArgumentError,
                'symbol_names tensor must be of type string'):
            _ = test_op([test_circuit], [0], [[0]], [10])
        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'programs tensor must be of type string'):
            _ = test_op([0], ['rx'], [[0]], [10])
        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'real-valued numeric tensor.'):
            _ = test_op([test_circuit], ['rx'], 'junk', [10])
        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'size of symbol_names tensor must match'):
            _ = test_op([test_circuit], ['rx'], [[1, 1]], [10])
        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'size of symbol_names tensor must match'):
            _ = test_op([test_circuit], ['rx', 'ry'], [[1]], [10])
        with self.assertRaisesRegex(
                tf.errors.InvalidArgumentError,
                'num_samples tensor must be of integer type'):
            _ = test_op([test_circuit], ['rx'], [[1]], "junk")
        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'num_samples tensor must have size 1'):
            _ = test_op([test_circuit], ['rx'], [[1]], [10, 10])

        _ = test_op([test_circuit], ['rx'], [[1]], [10])
        _ = test_op([test_circuit], [], [[]], [10])
Exemplo n.º 7
0
 def test_serialize_circuit_wrong_type(self, inp):
     """Attempt to serialize invalid objects types."""
     with self.assertRaises(TypeError):
         serializer.serialize_circuit(input)
Exemplo n.º 8
0
 def test_serialize_noise_channel_unsupported_value(self):
     """Ensure serializing invalid channels fails gracefully."""
     qubit = cirq.LineQubit(5)
     simple_circuit = cirq.Circuit(cirq.depolarize(0.3)(qubit))
     with self.assertRaises(ValueError):
         serializer.serialize_circuit(simple_circuit)
Exemplo n.º 9
0
 def test_serialize_circuit_valid_number_types(self, gate_with_param):
     """Tests number datatype support by our serializer."""
     self.assertAllClose(
         gate_with_param.unitary(),
         serializer.deserialize_circuit(
             serializer.serialize_circuit(gate_with_param)).unitary())
Exemplo n.º 10
0
 def test_serialize_circuit_valid(self, circ_proto_pair):
     """Test conversion of cirq Circuits to tfq_gate_set proto."""
     self.assertProtoEquals(
         serializer.serialize_circuit(circ_proto_pair[0]),
         circ_proto_pair[1])
Exemplo n.º 11
0
 def test_sample_empty_circuit(self):
     """Test empty circuits"""
     test_op = cirq_ops._get_cirq_samples(cirq.Simulator())
     test_empty_circuit = serializer.serialize_circuit(
         cirq.Circuit()).SerializeToString()
     _ = test_op([test_empty_circuit], [], [[]], [10])
Exemplo n.º 12
0
 def _simulate_circuit(self, circuit, params):
     # TODO: implement backend switch
     return tfq_simulate_ops.tfq_simulate_state(
         [str(serialize_circuit(circuit))] * params.batch_size, ["None"],
         [[0]] * params.batch_size)