def test_json_bit_packing_and_dtype(use_records: bool) -> None: shape = (256, 3, 256) if use_records else (256, 256) prng = np.random.RandomState(1234) bits = prng.randint(2, size=shape).astype(np.uint8) digits = prng.randint(256, size=shape).astype(np.uint8) params = cirq.ParamResolver({}) if use_records: bits_result = cirq.ResultDict(params=params, records={'m': bits}) digits_result = cirq.ResultDict(params=params, records={'m': digits}) else: bits_result = cirq.ResultDict(params=params, measurements={'m': bits}) digits_result = cirq.ResultDict(params=params, measurements={'m': digits}) bits_json = cirq.to_json(bits_result) digits_json = cirq.to_json(digits_result) loaded_bits_result = cirq.read_json(json_text=bits_json) loaded_digits_result = cirq.read_json(json_text=digits_json) if use_records: assert loaded_bits_result.records['m'].dtype == np.uint8 assert loaded_digits_result.records['m'].dtype == np.uint8 else: assert loaded_bits_result.measurements['m'].dtype == np.uint8 assert loaded_digits_result.measurements['m'].dtype == np.uint8 np.testing.assert_allclose(len(bits_json), len(digits_json) / 8, rtol=0.02)
def test_construct_from_repeated_measurements(): r = cirq.ResultDict( params=None, records={ 'a': np.array([[[0, 0], [0, 1]], [[1, 0], [1, 1]]]), 'b': np.array([[[0, 0, 0]], [[1, 1, 1]]]), }, ) with pytest.raises(ValueError): _ = r.measurements assert np.all( r.records['a'] == np.array([[[0, 0], [0, 1]], [[1, 0], [1, 1]]])) assert np.all(r.records['b'] == np.array([[[0, 0, 0]], [[1, 1, 1]]])) assert r.repetitions == 2 r2 = cirq.ResultDict( params=None, records={ 'a': np.array([[[0, 0]], [[1, 1]]]), 'b': np.array([[[0, 0, 0]], [[1, 1, 1]]]), }, ) assert np.all(r2.measurements['a'] == np.array([[0, 0], [1, 1]])) assert np.all(r2.measurements['b'] == np.array([[0, 0, 0], [1, 1, 1]])) assert np.all(r2.records['a'] == np.array([[[0, 0]], [[1, 1]]])) assert np.all(r2.records['b'] == np.array([[[0, 0, 0]], [[1, 1, 1]]])) assert r2.repetitions == 2
def test_repr(): v = cirq.ResultDict(params=cirq.ParamResolver({'a': 2}), measurements={'xy': np.array([[1, 0], [0, 1]])}) cirq.testing.assert_equivalent_repr(v) v = cirq.ResultDict( params=cirq.ParamResolver({'a': 2}), records={'xy': np.array([[[0, 0], [0, 1]], [[1, 0], [1, 1]]])}, ) cirq.testing.assert_equivalent_repr(v)
def test_run_simulator_sweeps(): expected_records = {'a': np.array([[[1]]])} simulator = FakeSimulatesSamples(expected_records) circuit = cirq.Circuit(cirq.measure(cirq.LineQubit(0), key='k')) param_resolvers = [cirq.ParamResolver({}), cirq.ParamResolver({})] expected_results = [ cirq.ResultDict(records=expected_records, params=param_resolvers[0]), cirq.ResultDict(records=expected_records, params=param_resolvers[1]), ] assert expected_results == simulator.run_sweep(program=circuit, repetitions=10, params=param_resolvers)
def test_results_to_proto(): measurements = [ v2.MeasureInfo('foo', [q(0, 0)], slot=0, invert_mask=[False], tags=[]) ] trial_results = [ [ cirq.ResultDict( params=cirq.ParamResolver({'i': 0}), measurements={ 'foo': np.array([[0], [1], [0], [1]], dtype=bool) }, ), cirq.ResultDict( params=cirq.ParamResolver({'i': 1}), measurements={ 'foo': np.array([[0], [1], [1], [0]], dtype=bool) }, ), ], [ cirq.ResultDict( params=cirq.ParamResolver({'i': 0}), measurements={ 'foo': np.array([[0], [1], [0], [1]], dtype=bool) }, ), cirq.ResultDict( params=cirq.ParamResolver({'i': 1}), measurements={ 'foo': np.array([[0], [1], [1], [0]], dtype=bool) }, ), ], ] proto = v2.results_to_proto(trial_results, measurements) assert isinstance(proto, v2.result_pb2.Result) assert len(proto.sweep_results) == 2 deserialized = v2.results_from_proto(proto, measurements) assert len(deserialized) == 2 for sweep_results, expected in zip(deserialized, trial_results): assert len(sweep_results) == len(expected) for trial_result, expected_trial_result in zip(sweep_results, expected): assert trial_result.params == expected_trial_result.params assert trial_result.repetitions == expected_trial_result.repetitions np.testing.assert_array_equal( trial_result.measurements['foo'], expected_trial_result.measurements['foo'])
def run_sweep( self, program: cirq.AbstractCircuit, params: cirq.Sweepable, repetitions: int = 1 ) -> Sequence[cirq.Result]: """Samples from the given Circuit. In contrast to run, this allows for sweeping over different parameter values. Args: program: The circuit to simulate. Should be generated using AQTSampler.generate_circuit_from_list params: Parameters to run with the program. repetitions: The number of repetitions to simulate. Returns: Result list for this run; one for each possible parameter resolver. """ # TODO: Use measurement name from circuit. # Github issue: https://github.com/quantumlib/Cirq/issues/2199 meas_name = 'm' trial_results: List[cirq.Result] = [] for param_resolver in cirq.to_resolvers(params): id_str = uuid.uuid1() num_qubits = len(program.all_qubits()) json_str = self._generate_json(circuit=program, param_resolver=param_resolver) results = self._send_json( json_str=json_str, id_str=id_str, repetitions=repetitions, num_qubits=num_qubits ) results = results.astype(bool) res_dict = {meas_name: results} trial_results.append(cirq.ResultDict(params=param_resolver, measurements=res_dict)) return trial_results
def test_sample_heavy_set_with_parity(): """Test that we correctly sample a circuit's heavy set with a parity map""" sampler = Mock(spec=cirq.Simulator) # Construct a result that returns [1, 0, 1, 0] for the physical qubit # measurement, and [0, 1, 1, 0] for the ancilla qubit measurement. The first # bitstring "10" is valid and heavy. The second "01" is valid and not # heavy. The third and fourth bitstrings "11" and "00" are not valid and # dropped. result = cirq.ResultDict( params=cirq.ParamResolver({}), measurements={ '0': np.array([[1], [0]]), '1': np.array([[0], [1]]), '2': np.array([[1], [1]]), '3': np.array([[0], [0]]), }, ) sampler.run = MagicMock(return_value=result) circuit = cirq.Circuit(cirq.measure(*cirq.LineQubit.range(4))) compilation_result = CompilationResult( circuit=circuit, mapping={q: q for q in cirq.LineQubit.range(4)}, parity_map={ cirq.LineQubit(0): cirq.LineQubit(1), cirq.LineQubit(2): cirq.LineQubit(3) }, ) probability = cirq.contrib.quantum_volume.sample_heavy_set( compilation_result, [1], sampler=sampler, repetitions=1) # The first output is in the heavy set. The second one isn't, but it is # dropped. assert probability == 0.5
def test_text_diagram_jupyter(): result = cirq.ResultDict( params=cirq.ParamResolver({}), measurements={ 'ab': np.array([[0, 1], [0, 1], [0, 1], [1, 0], [0, 1]], dtype=bool), 'c': np.array([[0], [0], [1], [0], [1]], dtype=bool), }, ) # Test Jupyter console output from class FakePrinter: def __init__(self): self.text_pretty = '' def text(self, to_print): self.text_pretty += to_print p = FakePrinter() result._repr_pretty_(p, False) assert p.text_pretty == 'ab=00010, 11101\nc=00101' # Test cycle handling p = FakePrinter() result._repr_pretty_(p, True) assert p.text_pretty == 'ResultDict(...)'
def to_cirq_result(self, params: Optional[cirq.ParamResolver] = None) -> cirq.Result: """Returns a `cirq.Result` for these results. `cirq.Result` contains a less dense representation of results than that returned by the IonQ API. Typically these results are also ordered by when they were run, though that contract is implicit. Because the IonQ API does not retain that ordering information, the order of these `cirq.Result` objects should *not* be interpetted as representing the order in which the circuit was repeated. Correlations between measurements keys are preserved. Args: params: The `cirq.ParamResolver` used to generate these results. Returns: The `cirq.Result` for these results. Raises: ValueError: If the circuit used to produce this result had no measurement gates (and hence no measurement keys). """ if len(self.measurement_dict()) == 0: raise ValueError( 'Can convert to cirq results only if the circuit had measurement gates ' 'with measurement keys.' ) measurements = {} for key, targets in self.measurement_dict().items(): qpu_results = self.ordered_results(key) measurements[key] = np.array( list(cirq.big_endian_int_to_bits(x, bit_count=len(targets)) for x in qpu_results) ) return cirq.ResultDict(params=params or cirq.ParamResolver({}), measurements=measurements)
def test_results_to_proto_sweep_repetitions(): measurements = [ v2.MeasureInfo('foo', [q(0, 0)], slot=0, invert_mask=[False], tags=[]) ] trial_results = [[ cirq.ResultDict( params=cirq.ParamResolver({'i': 0}), measurements={'foo': np.array([[0]], dtype=bool)}, ), cirq.ResultDict( params=cirq.ParamResolver({'i': 1}), measurements={'foo': np.array([[0], [1]], dtype=bool)}, ), ]] with pytest.raises(ValueError, match='Different numbers of repetitions'): v2.results_to_proto(trial_results, measurements)
def test_result_addition_invalid(): a = cirq.ResultDict( params=cirq.ParamResolver({'ax': 1}), measurements={ 'q0': np.array([[0, 1], [1, 0], [0, 1]], dtype=bool), 'q1': np.array([[0], [0], [1]], dtype=bool), }, ) b = cirq.ResultDict( params=cirq.ParamResolver({'bad': 1}), measurements={ 'q0': np.array([[0, 1], [1, 0], [0, 1]], dtype=bool), 'q1': np.array([[0], [0], [1]], dtype=bool), }, ) c = cirq.ResultDict( params=cirq.ParamResolver({'ax': 1}), measurements={ 'bad': np.array([[0, 1], [1, 0], [0, 1]], dtype=bool), 'q1': np.array([[0], [0], [1]], dtype=bool), }, ) d = cirq.ResultDict( params=cirq.ParamResolver({'ax': 1}), measurements={ 'q0': np.array([[0, 1], [1, 0], [0, 1]], dtype=bool), 'q1': np.array([[0, 1], [0, 1], [1, 1]], dtype=bool), }, ) e = cirq.ResultDict( params=cirq.ParamResolver({'ax': 1}), records={ 'q0': np.array([[0, 1], [1, 0], [0, 1]], dtype=bool), 'q1': np.array([[[0], [0]], [[0], [1]], [[1], [0]]], dtype=bool), }, ) with pytest.raises(ValueError, match='different parameters'): _ = a + b with pytest.raises(ValueError, match='different measurement shapes'): _ = a + c with pytest.raises(ValueError, match='different measurement shapes'): _ = a + d with pytest.raises(ValueError, match='different measurement shapes'): _ = a + e with pytest.raises(TypeError): _ = a + 'junk'
def test_df_large(): result = cirq.ResultDict( params=cirq.ParamResolver({}), measurements={ 'a': np.array([[0 for _ in range(76)]] * 10_000, dtype=bool), 'd': np.array([[1 for _ in range(76)]] * 10_000, dtype=bool), }, )
def test_run_simulator_sweeps_with_deprecated_run(): expected_measurements = {'a': np.array([[1]])} simulator = FakeSimulatesSamples(expected_measurements) circuit = cirq.Circuit(cirq.measure(cirq.LineQubit(0), key='k')) param_resolvers = [cirq.ParamResolver({}), cirq.ParamResolver({})] expected_records = {'a': np.array([[[1]]])} expected_results = [ cirq.ResultDict(records=expected_records, params=param_resolvers[0]), cirq.ResultDict(records=expected_records, params=param_resolvers[1]), ] with cirq.testing.assert_deprecated( 'values in the output of simulator._run must be 3D', deadline='v0.15', ): assert expected_results == simulator.run_sweep( program=circuit, repetitions=10, params=param_resolvers )
def test_result_equality(): et = cirq.testing.EqualsTester() et.add_equality_group( cirq.ResultDict(params=cirq.ParamResolver({}), measurements={'a': np.array([[0]] * 5)}), cirq.ResultDict(params=cirq.ParamResolver({}), records={'a': np.array([[[0]]] * 5)}), ) et.add_equality_group( cirq.ResultDict(params=cirq.ParamResolver({}), measurements={'a': np.array([[0]] * 6)})) et.add_equality_group( cirq.ResultDict(params=cirq.ParamResolver({}), measurements={'a': np.array([[1]] * 5)})) et.add_equality_group( cirq.ResultDict(params=cirq.ParamResolver({}), records={'a': np.array([[[0], [1]]] * 5)}))
def run_sweep( self, program: 'cirq.AbstractCircuit', params: 'cirq.Sweepable', repetitions: int = 1 ) -> Sequence['cirq.Result']: results: List[cirq.Result] = [] for param_resolver in cirq.to_resolvers(params): resolved_circuit = cirq.resolve_parameters(program, param_resolver) measurements = self._run(resolved_circuit, repetitions=repetitions) results.append(cirq.ResultDict(params=param_resolver, measurements=measurements)) return results
def test_executable_result(): rtinfo = cg.RuntimeInfo(execution_index=5) er = cg.ExecutableResult( spec=_get_example_spec(name='test-spec'), runtime_info=rtinfo, raw_data=cirq.ResultDict(params=cirq.ParamResolver(), measurements={'z': np.ones((1_000, 4))}), ) cg_assert_equivalent_repr(er)
def test_str(): result = cirq.ResultDict( params=cirq.ParamResolver({}), measurements={ 'ab': np.array([[0, 1], [0, 1], [0, 1], [1, 0], [0, 1]]), 'c': np.array([[0], [0], [1], [0], [1]]), }, ) assert str(result) == 'ab=00010, 11101\nc=00101' result = cirq.ResultDict( params=cirq.ParamResolver({}), measurements={ 'ab': np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]), 'c': np.array([[0], [1], [2], [3], [4]]), }, ) assert str(result) == 'ab=13579, 2 4 6 8 10\nc=01234'
def test_result_addition_valid(): a = cirq.ResultDict( params=cirq.ParamResolver({'ax': 1}), measurements={ 'q0': np.array([[0, 1], [1, 0], [0, 1]], dtype=bool), 'q1': np.array([[0], [0], [1]], dtype=bool), }, ) b = cirq.ResultDict( params=cirq.ParamResolver({'ax': 1}), measurements={ 'q0': np.array([[0, 1]], dtype=bool), 'q1': np.array([[0]], dtype=bool), }, ) c = a + b np.testing.assert_array_equal(c.measurements['q0'], np.array([[0, 1], [1, 0], [0, 1], [0, 1]])) np.testing.assert_array_equal(c.measurements['q1'], np.array([[0], [0], [1], [0]])) # Add results with repeated measurements. a = cirq.ResultDict( params=cirq.ParamResolver({'ax': 1}), records={ 'q0': np.array([[[0, 1]], [[1, 0]], [[0, 1]]], dtype=bool), 'q1': np.array([[[0], [0]], [[0], [1]], [[1], [0]]], dtype=bool), }, ) b = cirq.ResultDict( params=cirq.ParamResolver({'ax': 1}), records={ 'q0': np.array([[[0, 1]]], dtype=bool), 'q1': np.array([[[1], [1]]], dtype=bool), }, ) c = a + b np.testing.assert_array_equal( c.records['q0'], np.array([[[0, 1]], [[1, 0]], [[0, 1]], [[0, 1]]])) np.testing.assert_array_equal( c.records['q1'], np.array([[[0], [0]], [[0], [1]], [[1], [0]], [[1], [1]]]))
def run_sweep(self, program: 'cirq.AbstractCircuit', params: 'cirq.Sweepable', repetitions: int = 1) -> Sequence['cirq.Result']: results = np.zeros((repetitions, 1), dtype=bool) for idx in range(repetitions // 4): results[idx][0] = 1 return [ cirq.ResultDict(params=pr, measurements={'z': results}) for pr in cirq.study.to_resolvers(params) ]
def test_construct_from_measurements(): r = cirq.ResultDict( params=None, measurements={ 'a': np.array([[0, 0], [1, 1]]), 'b': np.array([[0, 0, 0], [1, 1, 1]]), }, ) assert np.all(r.measurements['a'] == np.array([[0, 0], [1, 1]])) assert np.all(r.measurements['b'] == np.array([[0, 0, 0], [1, 1, 1]])) assert np.all(r.records['a'] == np.array([[[0, 0]], [[1, 1]]])) assert np.all(r.records['b'] == np.array([[[0, 0, 0]], [[1, 1, 1]]]))
def _execute_and_read_result( quantum_computer: QuantumComputer, executable: QuantumExecutable, measurement_id_map: Dict[str, str], resolver: cirq.ParamResolverOrSimilarType, memory_map: Optional[Dict[str, Union[int, float, Sequence[int], Sequence[float]]]] = None, ) -> cirq.Result: """Execute the `pyquil.api.QuantumExecutable` and parse the measurements into a `cirq.Result`. Args: quantum_computer: The `pyquil.api.QuantumComputer` on which to execute and from which to read results. executable: The fully compiled `pyquil.api.QuantumExecutable` to run. measurement_id_map: A dict mapping cirq measurement keys to pyQuil read out regions. resolver: The `cirq.ParamResolverOrSimilarType` to include on the returned `cirq.Result`. memory_map: A dict of values to write to memory values on the `quantum_computer`. The `pyquil.api.QuantumAbstractMachine` reads these values into memory regions on the pre-compiled `executable` during execution. Returns: A `cirq.Result` with measurements read from the `quantum_computer`. Raises: ValueError: measurement_id_map references an undefined pyQuil readout region. """ if memory_map is None: memory_map = {} for region_name, values in memory_map.items(): executable.write_memory(region_name=region_name, value=values) qam_execution_result = quantum_computer.qam.run(executable) measurements = {} # For every key, value in QuilOutput#measurement_id_map, use the value to read # Rigetti QCS results and assign to measurements by key. for cirq_memory_key, pyquil_region in measurement_id_map.items(): readout = qam_execution_result.readout_data.get(pyquil_region) if readout is None: raise ValueError(f'readout data does not have values for region "{pyquil_region}"') measurements[cirq_memory_key] = readout logger.debug(f"measurement_id_map {measurement_id_map}") logger.debug(f"measurements {measurements}") # collect results in a cirq.Result. result = cirq.ResultDict( params=cast(cirq.ParamResolver, resolver or cirq.ParamResolver({})), measurements=measurements, ) # noqa return result
def test_service_run(target, expected_results): service = ionq.Service(remote_host='http://example.com', api_key='key') mock_client = mock.MagicMock() mock_client.create_job.return_value = { 'id': 'job_id', 'status': 'ready', } mock_client.get_job.return_value = { 'id': 'job_id', 'status': 'completed', 'target': target, 'metadata': { 'shots': '4', 'measurement0': f'a{chr(31)}0' }, 'qubits': '1', 'data': { 'histogram': { '0': '0.25', '1': '0.75' } }, 'status': 'completed', } service._client = mock_client a = sympy.Symbol('a') q = cirq.LineQubit(0) circuit = cirq.Circuit((cirq.X**a)(q), cirq.measure(q, key='a')) params = cirq.ParamResolver({'a': 0.5}) result = service.run( circuit=circuit, repetitions=4, target=target, name='bacon', param_resolver=params, seed=2, ) assert result == cirq.ResultDict( params=params, measurements={'a': np.array(expected_results)}) create_job_kwargs = mock_client.create_job.call_args[1] # Serialization induces a float, so we don't validate full circuit. assert create_job_kwargs['serialized_program'].body['qubits'] == 1 assert create_job_kwargs['serialized_program'].metadata == { 'measurement0': f'a{chr(31)}0' } assert create_job_kwargs['repetitions'] == 4 assert create_job_kwargs['target'] == target assert create_job_kwargs['name'] == 'bacon'
def to_cirq_result( self, params: cirq.ParamResolver = None, seed: cirq.RANDOM_STATE_OR_SEED_LIKE = None, override_repetitions=None, ) -> cirq.Result: """Samples from the simulation probability result, producing a `cirq.Result`. The IonQ simulator returns the probabilities of different bitstrings. This converts such a representation to a randomly generated sample from the simulator. Note that it does this on every subsequent call of this method, so repeated calls do not produce the same `cirq.Result`s. When a job was created by the IonQ API, it had a number of repetitions and this is used, unless `override_repetitions` is set here. Args: params: Any parameters which were used to generated this result. seed: What to use for generating the randomness. If None, then `np.random` is used. If an integer, `np.random.RandomState(seed) is used. Otherwise if another randomness generator is used, it will be used. override_repetitions: Repetitions were supplied when the IonQ API ran the simulation, but different repetitions can be supplied here and will override. Returns: A `cirq.Result` corresponding to a sample from the probability distribution returned from the simulator. Raises: ValueError: If the circuit used to produce this result had no measurement gates (and hence no measurement keys). """ if len(self.measurement_dict()) == 0: raise ValueError( 'Can convert to cirq results only if the circuit had measurement gates ' 'with measurement keys.' ) rand = cirq.value.parse_random_state(seed) measurements = {} values, weights = zip(*list(self.probabilities().items())) indices = rand.choice( range(len(values)), p=weights, size=override_repetitions or self.repetitions() ) rand_values = np.array(values)[indices] for key, targets in self.measurement_dict().items(): bits = [ [(value >> (self.num_qubits() - target - 1)) & 1 for target in targets] for value in rand_values ] measurements[key] = np.array(bits) return cirq.ResultDict(params=params or cirq.ParamResolver({}), measurements=measurements)
def test_engine_result_from_result_dict(): res = cg.EngineResult( job_id='my_job_id', job_finished_time=_DT, params=None, measurements={'a': np.array([[0, 0], [1, 1]]), 'b': np.array([[0, 0, 0], [1, 1, 1]])}, ) res2 = cirq.ResultDict( params=None, measurements={'a': np.array([[0, 0], [1, 1]]), 'b': np.array([[0, 0, 0], [1, 1, 1]])}, ) assert res2 != res assert res != res2 assert res == cg.EngineResult.from_result(res2, job_id='my_job_id', job_finished_time=_DT)
def test_run_delegation(create_job, get_results): create_job.return_value = ( 'steve', qtypes.QuantumJob( name='projects/a/programs/b/jobs/steve', execution_status=qtypes.ExecutionStatus( state=qtypes.ExecutionStatus.State.SUCCESS), ), ) get_results.return_value = qtypes.QuantumResult(result=util.pack_any( Merge( """sweep_results: [{ repetitions: 4, parameterized_results: [{ params: { assignments: { key: 'a' value: 1 } }, measurement_results: { key: 'q' qubit_measurement_results: [{ qubit: { id: '1_1' } results: '\006' }] } }] }] """, v2.result_pb2.Result(), ))) program = cg.EngineProgram('a', 'b', EngineContext()) param_resolver = cirq.ParamResolver({}) results = program.run(job_id='steve', repetitions=10, param_resolver=param_resolver, processor_ids=['mine']) assert results == cirq.ResultDict( params=cirq.ParamResolver({'a': 1.0}), measurements={ 'q': np.array([[False], [True], [True], [False]], dtype=bool) }, )
def test_multi_measurement_histogram(): result = cirq.ResultDict( params=cirq.ParamResolver({}), measurements={ 'ab': np.array([[0, 1], [0, 1], [0, 1], [1, 0], [0, 1]], dtype=bool), 'c': np.array([[0], [0], [1], [0], [1]], dtype=bool), }, ) assert result.multi_measurement_histogram( keys=['ab']) == collections.Counter({ (1, ): 4, (2, ): 1 }) assert result.multi_measurement_histogram( keys=['c']) == collections.Counter({ (0, ): 3, (1, ): 2 }) assert result.multi_measurement_histogram( keys=['ab', 'c']) == collections.Counter({ (1, 0): 2, (1, 1): 2, (2, 0): 1 }) assert result.multi_measurement_histogram( keys=[], fold_func=lambda e: None) == collections.Counter({None: 5}) assert result.multi_measurement_histogram( keys=['ab'], fold_func=lambda e: None) == collections.Counter({None: 5}) assert result.multi_measurement_histogram( keys=['ab', 'c'], fold_func=lambda e: None) == collections.Counter({None: 5}) assert result.multi_measurement_histogram( keys=['ab', 'c'], fold_func=lambda e: tuple(tuple(f) for f in e)) == collections.Counter({ ((False, True), (False, )): 2, ((False, True), (True, )): 2, ((True, False), (False, )): 1 })
def _trial_sweep_from_proto( msg: result_pb2.SweepResult, measure_map: Dict[str, MeasureInfo] = None, ) -> Sequence[cirq.Result]: """Converts a SweepResult proto into List of list of trial results. Args: msg: v2 Result message to convert. measure_map: A mapping of measurement keys to a measurement configuration containing qubit ordering. If no measurement config is provided, then all results will be returned in the order specified within the result. Returns: A list containing a list of trial results for the sweep. Raises: ValueError: If a qubit already exists in the measurement results. """ trial_sweep: List[cirq.Result] = [] for pr in msg.parameterized_results: m_data: Dict[str, np.ndarray] = {} for mr in pr.measurement_results: qubit_results: OrderedDict[cirq.GridQubit, np.ndarray] = OrderedDict() for qmr in mr.qubit_measurement_results: qubit = v2.grid_qubit_from_proto_id(qmr.qubit.id) if qubit in qubit_results: raise ValueError(f'Qubit already exists: {qubit}.') qubit_results[qubit] = unpack_bits(qmr.results, msg.repetitions) if measure_map: ordered_results = [ qubit_results[qubit] for qubit in measure_map[mr.key].qubits ] else: ordered_results = list(qubit_results.values()) m_data[mr.key] = np.array(ordered_results).transpose() trial_sweep.append( cirq.ResultDict( params=cirq.ParamResolver(dict(pr.params.assignments)), measurements=m_data, )) return trial_sweep
def test_executable_group_result(tmpdir): egr = cg.ExecutableGroupResult( runtime_configuration=cg.QuantumRuntimeConfiguration( processor_record=cg.SimulatedProcessorWithLocalDeviceRecord( 'rainbow'), run_id='unit-test', ), shared_runtime_info=cg.SharedRuntimeInfo(run_id='my run'), executable_results=[ cg.ExecutableResult( spec=_get_example_spec(name=f'test-spec-{i}'), runtime_info=cg.RuntimeInfo(execution_index=i), raw_data=cirq.ResultDict( params=cirq.ParamResolver(), measurements={'z': np.ones((1_000, 4))}), ) for i in range(3) ], )
def test_sample_heavy_set(): """Test that we correctly sample a circuit's heavy set""" sampler = Mock(spec=cirq.Simulator) # Construct a result that returns "1", "2", "3", "0" result = cirq.ResultDict( params=cirq.ParamResolver({}), measurements={'mock': np.array([[0, 1], [1, 0], [1, 1], [0, 0]])}, ) sampler.run = MagicMock(return_value=result) circuit = cirq.Circuit(cirq.measure(*cirq.LineQubit.range(2))) compilation_result = CompilationResult(circuit=circuit, mapping={}, parity_map={}) probability = cirq.contrib.quantum_volume.sample_heavy_set( compilation_result, [1, 2, 3], sampler=sampler, repetitions=10 ) # The first 3 of our outputs are in the heavy set, and then the rest are # not. assert probability == 0.75
def _get_job_results_v1( result: v1.program_pb2.Result) -> Sequence[cirq.Result]: trial_results = [] for sweep_result in result.sweep_results: sweep_repetitions = sweep_result.repetitions key_sizes = [(m.key, len(m.qubits)) for m in sweep_result.measurement_keys] for result in sweep_result.parameterized_results: data = result.measurement_results measurements = v1.unpack_results(data, sweep_repetitions, key_sizes) trial_results.append( cirq.ResultDict( params=cirq.ParamResolver(result.params.assignments), measurements=measurements, )) return trial_results