def test_deserialize_bad_operation_id(self): """Ensure error is raised when deserializing bad operation.""" proto = program_pb2.Program( language=program_pb2.Language(arg_function_language='', gate_set='my_gate_set'), circuit=program_pb2.Circuit( scheduling_strategy=program_pb2.Circuit.MOMENT_BY_MOMENT, moments=[ program_pb2.Moment(operations=[]), program_pb2.Moment(operations=[ program_pb2.Operation( gate=program_pb2.Gate(id='UNKNOWN_GATE'), args={ 'half_turns': program_pb2.Arg( arg_value=program_pb2.ArgValue( float_value=1.0)) }, qubits=[program_pb2.Qubit(id='1_1')]) ]), ])) with self.assertRaisesRegex( ValueError, expected_regex='problem in moment 1 handling an ' 'operation with the following'): MY_GATE_SET.deserialize(proto)
def test_serialize_deserialize_empty_circuit(self): """Verify empty case serialize deserialize works.""" circuit = cirq.Circuit() proto = program_pb2.Program( language=program_pb2.Language(arg_function_language='', gate_set='my_gate_set'), circuit=program_pb2.Circuit( scheduling_strategy=program_pb2.Circuit.MOMENT_BY_MOMENT, moments=[])) self.assertEqual(proto, MY_GATE_SET.serialize(circuit)) self.assertEqual(MY_GATE_SET.deserialize(proto), circuit)
def test_deserialize_invalid_gate_set(self): """Deserializing an invalid gate set should error if element not in.""" proto = program_pb2.Program( language=program_pb2.Language(gate_set='not_my_gate_set'), circuit=program_pb2.Circuit( scheduling_strategy=program_pb2.Circuit.MOMENT_BY_MOMENT, moments=[])) with self.assertRaisesRegex(ValueError, expected_regex='not_my_gate_set'): MY_GATE_SET.deserialize(proto) proto.language.gate_set = '' with self.assertRaisesRegex(ValueError, expected_regex='Missing gate set'): MY_GATE_SET.deserialize(proto) proto = program_pb2.Program(circuit=program_pb2.Circuit( scheduling_strategy=program_pb2.Circuit.MOMENT_BY_MOMENT, moments=[])) with self.assertRaisesRegex(ValueError, expected_regex='Missing gate set'): MY_GATE_SET.deserialize(proto)
def test_deserialize_empty_moment(self): """Ensure deserialize empty moment works.""" circuit = cirq.Circuit([cirq.Moment()]) proto = program_pb2.Program( language=program_pb2.Language(arg_function_language='', gate_set='my_gate_set'), circuit=program_pb2.Circuit( scheduling_strategy=program_pb2.Circuit.MOMENT_BY_MOMENT, moments=[ program_pb2.Moment(), ])) self.assertEqual(MY_GATE_SET.deserialize(proto), circuit)
def _parse_single(item): try: if b'tfq_gate_set' in item: # Return a circuit parsing obj = program_pb2.Program() obj.ParseFromString(item) out = serializer.deserialize_circuit(obj) return out # Return a PauliSum parsing. obj = pauli_sum_pb2.PauliSum() obj.ParseFromString(item) out = serializer.deserialize_paulisum(obj) return out except Exception: raise TypeError('Error decoding item: ' + str(item))
def _batch_deserialize_helper(programs, symbol_names, symbol_values): """Helper function that converts tensors to cirq constructs. Converts the string representation of the circuits in `programs` to `cirq.Circuit` objects and produces a corresponding `cirq.ParamResolver` constructed using `symbol_names` and `symbol_values`. 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`. Returns: `tuple` containing a `list` of `cirq.Circuit`s constructed from programs and a `list` of `cirq.ParamResolver`s. """ de_ser_symbol_names = [x.decode('UTF-8') for x in symbol_names.numpy()] de_ser_programs = [] resolvers = [] # TODO(zaqqwerty): investigate parallelization of this loop for program, values in zip(programs, symbol_values): program = program.numpy() values = values.numpy().astype(float) circuit_proto = program_pb2.Program() circuit_proto.ParseFromString(program) circuit = serializer.deserialize_circuit(circuit_proto) resolver = cirq.study.resolver.ParamResolver( dict(zip(de_ser_symbol_names, values))) de_ser_programs.append(circuit) resolvers.append(resolver) return de_ser_programs, resolvers
def test_serialize_deserialize_circuit(self): """Verify one to one serialize deserialize consistency.""" q0 = cirq.GridQubit(1, 1) q1 = cirq.GridQubit(1, 2) circuit = cirq.Circuit(cirq.X(q0), cirq.X(q1), cirq.X(q0)) proto = program_pb2.Program( language=program_pb2.Language(arg_function_language='', gate_set='my_gate_set'), circuit=program_pb2.Circuit( scheduling_strategy=program_pb2.Circuit.MOMENT_BY_MOMENT, moments=[ program_pb2.Moment(operations=[ X_SERIALIZER.to_proto(cirq.X(q0)), X_SERIALIZER.to_proto(cirq.X(q1)) ]), program_pb2.Moment( operations=[X_SERIALIZER.to_proto(cirq.X(q0))]), ])) self.assertEqual(proto, MY_GATE_SET.serialize(circuit)) self.assertEqual(MY_GATE_SET.deserialize(proto), circuit)
def serialize(self, program, msg=None, *, arg_function_language=None): """Serialize a Circuit to cirq.google.api.v2.Program proto. Args: program: The Circuit to serialize. """ if msg is None: msg = program_pb2.Program() msg.language.gate_set = self.gate_set_name if isinstance(program, cirq.Circuit): self._serialize_circuit( program, msg.circuit, arg_function_language=arg_function_language) if arg_function_language is None: arg_function_language = (_infer_function_language_from_circuit( msg.circuit)) else: raise NotImplementedError( f'Unrecognized program type: {type(program)}') msg.language.arg_function_language = arg_function_language return msg
def _build_op_proto(gate_id, arg_names, arg_vals, qubit_ids): """Helper function to generate proto for a given circuit spec. Understand how it works from this example: _build_op_proto("HP", ['exponent', 'global_shift'], ['alpha', 0.0], ['0_0']) would produce the following: language { gate_set: "tfq_gate_set" } circuit { scheduling_strategy: MOMENT_BY_MOMENT moments { operations { gate { id: "HP" } args { key: "global_shift" value { arg_value { float_value: 0.0 } } } args { key: "exponent" value { symbol: "alpha" } } args { key: "control_qubits" value { arg_value: "" } } args { key: "control_values" value { arg_value: "" } } qubits { id: "0_0" } } } } """ program_proto = program_pb2.Program() program_proto.language.gate_set = 'tfq_gate_set' circuit_proto = program_proto.circuit circuit_proto.scheduling_strategy = circuit_proto.MOMENT_BY_MOMENT circuit_proto.moments.add(operations=[program_pb2.Operation( gate = program_pb2.Gate(id=gate_id), args = {arg_names[i]: (program_pb2.Arg(symbol=arg_vals[i]) \ if isinstance(arg_vals[i], str) else \ program_pb2.Arg( arg_value=program_pb2.ArgValue( float_value=np.round(float(arg_vals[i]), 6)))) \ for i in range(len(arg_vals))}, qubits=[program_pb2.Qubit( id=q_id) for q_id in qubit_ids])]) # Add in empty control information t = program_proto.circuit.moments[0].operations[0] t.args['control_qubits'].arg_value.string_value = '' t.args['control_values'].arg_value.string_value = '' return program_proto