def test_results_from_proto_default_ordering(): proto = result_pb2.Result() sr = proto.sweep_results.add() sr.repetitions = 8 pr = sr.parameterized_results.add() pr.params.assignments.update({'i': 1}) mr = pr.measurement_results.add() mr.key = 'foo' for qubit, results in [ (q(0, 1), 0b1100_1100), (q(1, 1), 0b1010_1010), (q(0, 0), 0b1111_0000), ]: qmr = mr.qubit_measurement_results.add() qmr.qubit.id = qubit.proto_id() qmr.results = bytes([results]) trial_results = v2.results_from_proto(proto) trial = trial_results[0][0] assert trial.params == cirq.ParamResolver({'i': 1}) assert trial.repetitions == 8 np.testing.assert_array_equal( trial.measurements['foo'], np.array([ [0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0], [0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1], ], dtype=bool))
def results_to_proto( trial_sweeps: Iterable[Iterable[study.TrialResult]], measurements: List[MeasureInfo], *, out: Optional[result_pb2.Result] = None, ) -> result_pb2.Result: """Converts trial results from multiple sweeps to v2 protobuf message. Args: trial_sweeps: Iterable over sweeps and then over trial results within each sweep. measurements: List of info about measurements in the program. out: Optional message to populate. If not given, create a new message. """ if out is None: out = result_pb2.Result() for trial_sweep in trial_sweeps: sweep_result = out.sweep_results.add() for i, trial_result in enumerate(trial_sweep): if i == 0: sweep_result.repetitions = trial_result.repetitions elif trial_result.repetitions != sweep_result.repetitions: raise ValueError( 'different numbers of repetitions in one sweep') pr = sweep_result.parameterized_results.add() pr.params.assignments.update(trial_result.params.param_dict) for m in measurements: mr = pr.measurement_results.add() mr.key = m.key m_data = trial_result.measurements[m.key] for i, qubit in enumerate(m.qubits): qmr = mr.qubit_measurement_results.add() qmr.qubit.id = v2.qubit_to_proto_id(qubit) qmr.results = pack_bits(m_data[:, i]) return out
def test_results_from_proto_duplicate_qubit(): measurements = [v2.MeasureInfo('foo', [q(0, 0), q(0, 1), q(1, 1)], slot=0)] proto = result_pb2.Result() sr = proto.sweep_results.add() sr.repetitions = 8 pr = sr.parameterized_results.add() pr.params.assignments.update({'i': 0}) mr = pr.measurement_results.add() mr.key = 'foo' for qubit, results in [ (q(0, 0), 0b1100_1100), (q(0, 1), 0b1010_1010), (q(0, 1), 0b1111_0000), ]: qmr = mr.qubit_measurement_results.add() qmr.qubit.id = qubit.proto_id() qmr.results = bytes([results]) with pytest.raises(ValueError, match='qubit already exists'): v2.results_from_proto(proto, measurements)