def test_run_simulator_sweeps(): simulator = cirq.SimulatesSamples() expected_measurements = {'a': np.array([[1]])} simulator._run.return_value = expected_measurements circuit = mock.Mock(cirq.Circuit) circuit.__iter__ = mock.Mock(return_value=iter([])) param_resolvers = [ mock.Mock(cirq.ParamResolver), mock.Mock(cirq.ParamResolver) ] for resolver in param_resolvers: resolver.param_dict = {} expected_results = [ cirq.Result(measurements=expected_measurements, params=param_resolvers[0]), cirq.Result(measurements=expected_measurements, params=param_resolvers[1]), ] assert expected_results == simulator.run_sweep(program=circuit, repetitions=10, params=param_resolvers) simulator._run.assert_called_with(circuit=circuit, repetitions=10, param_resolver=mock.ANY) assert simulator._run.call_count == 2
def test_trial_result_equality(): et = cirq.testing.EqualsTester() et.add_equality_group( cirq.Result(params=cirq.ParamResolver({}), measurements={'a': np.array([[0]] * 5)})) et.add_equality_group( cirq.Result(params=cirq.ParamResolver({}), measurements={'a': np.array([[0]] * 6)})) et.add_equality_group( cirq.Result(params=cirq.ParamResolver({}), measurements={'a': np.array([[1]] * 5)}))
def test_results_to_proto(): measurements = [ v2.MeasureInfo('foo', [q(0, 0)], slot=0, invert_mask=[False], tags=[]) ] trial_results = [ [ cirq.Result( params=cirq.ParamResolver({'i': 0}), measurements={ 'foo': np.array([[0], [1], [0], [1]], dtype=bool), }, ), cirq.Result( params=cirq.ParamResolver({'i': 1}), measurements={ 'foo': np.array([[0], [1], [1], [0]], dtype=bool), }, ), ], [ cirq.Result( params=cirq.ParamResolver({'i': 0}), measurements={ 'foo': np.array([[0], [1], [0], [1]], dtype=bool), }, ), cirq.Result( 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 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.Result( 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 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. 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 = list(self.counts(key).elements()) measurements[key] = np.array( list( cirq.big_endian_int_to_bits(x, bit_count=len(targets)) for x in qpu_results)) return cirq.Result(params=params or cirq.ParamResolver({}), measurements=measurements)
def test_deprecated_json(): with cirq.testing.assert_logs('TrialResult was used but is deprecated'): result = cirq.read_json( json_text="""{ "cirq_type": "TrialResult", "params": { "cirq_type": "ParamResolver", "param_dict": [] }, "measurements": { "0,1": { "packed_digits": "fcc0", "binary": true, "dtype": "uint8", "shape": [ 5, 2 ] } } } """ ) assert result == cirq.Result( params=cirq.ParamResolver({}), measurements={ '0,1': np.array([[1, 1], [1, 1], [1, 1], [0, 0], [1, 1]], dtype=np.uint8) }, )
def run_sweep( self, program: cirq.AbstractCircuit, params: cirq.Sweepable, repetitions: int = 1 ) -> List[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' assert isinstance(program.device, cirq.IonDevice) trial_results = [] # type: List[cirq.Result] for param_resolver in cirq.to_resolvers(params): id_str = uuid.uuid1() num_qubits = len(program.device.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.Result(params=param_resolver, measurements=res_dict)) return trial_results
def test_text_diagram_jupyter(): result = cirq.Result( 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 == 'Result(...)'
def test_json_bit_packing_and_dtype(): prng = np.random.RandomState(1234) bits = prng.randint(2, size=(256, 256)).astype(np.uint8) digits = prng.randint(256, size=(256, 256)).astype(np.uint8) bits_result = cirq.Result(params=cirq.ParamResolver({}), measurements={'m': bits}) digits_result = cirq.Result(params=cirq.ParamResolver({}), 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) 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_executable_result(): rtinfo = cg.RuntimeInfo(execution_index=5) er = cg.ExecutableResult( spec=_get_example_spec(name='test-spec'), runtime_info=rtinfo, raw_data=cirq.Result(params=cirq.ParamResolver(), measurements={'z': np.ones((1_000, 4))}), ) cg_assert_equivalent_repr(er)
def test_str(): result = cirq.Result( 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.Result( 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 _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.Result( params=cast(cirq.ParamResolver, resolver or cirq.ParamResolver({})), measurements=measurements, ) # noqa return result
def test_results_to_proto_sweep_repetitions(): measurements = [ v2.MeasureInfo('foo', [q(0, 0)], slot=0, invert_mask=[False], tags=[]) ] trial_results = [[ cirq.Result( params=cirq.ParamResolver({'i': 0}), measurements={ 'foo': np.array([[0]], dtype=bool), }, ), cirq.Result( 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 run_sweep(self, program, params, repetitions): """Returns all ones in the correct sample shape.""" return [ cirq.Result( params=param, measurements={ 'tfq': np.array([[1] * len(program.all_qubits())] * repetitions, dtype=np.int32), }) for param in cirq.to_resolvers(params) ]
def test_trial_result_addition_valid(): a = cirq.Result( 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.Result( 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]]))
def run_sweep( self, program: 'cirq.AbstractCircuit', params: 'cirq.Sweepable', repetitions: int = 1, ) -> List['cirq.Result']: results = np.zeros((repetitions, 1), dtype=bool) for idx in range(repetitions // 4): results[idx][0] = 1 return [ cirq.Result(params=pr, measurements={'z': results}) for pr in cirq.study.to_resolvers(params) ]
def test_trial_result_addition_invalid(): a = cirq.Result( 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.Result( 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.Result( 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.Result( 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), }, ) with pytest.raises(ValueError, match='same parameters'): _ = a + b with pytest.raises(ValueError, match='same measurement keys'): _ = a + c with pytest.raises(ValueError): _ = a + d with pytest.raises(TypeError): _ = a + 'junk'
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.Result(params=params, measurements={'a': 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 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=_to_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.Result( params=cirq.ParamResolver({'a': 1.0}), measurements={ 'q': np.array([[False], [True], [True], [False]], dtype=bool) }, )
def test_executable_group_result(tmpdir): egr = cg.ExecutableGroupResult( runtime_configuration=cg.QuantumRuntimeConfiguration( processor=_MockEngineProcessor(), 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.Result(params=cirq.ParamResolver(), measurements={'z': np.ones((1_000, 4))}), ) for i in range(3) ], )
def run_sweep( self, program: 'cirq.Circuit', params: 'cirq.Sweepable', repetitions: int = 1, ) -> List['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.Result(params=param_resolver, measurements=measurements)) return results
def test_run_simulator_run(): simulator = cirq.SimulatesSamples() expected_measurements = {'a': np.array([[1]])} simulator._run.return_value = expected_measurements circuit = mock.Mock(cirq.Circuit) circuit.__iter__ = mock.Mock(return_value=iter([])) param_resolver = mock.Mock(cirq.ParamResolver) param_resolver.param_dict = {} expected_result = cirq.Result(measurements=expected_measurements, params=param_resolver) assert expected_result == simulator.run(program=circuit, repetitions=10, param_resolver=param_resolver) simulator._run.assert_called_once_with(circuit=circuit, repetitions=10, param_resolver=param_resolver)
def test_filesystem_saver(tmpdir, patch_cirq_default_resolvers): assert patch_cirq_default_resolvers run_id = 'asdf' fs_saver = _FilesystemSaver(base_data_dir=tmpdir, run_id=run_id) rt_config = cg.QuantumRuntimeConfiguration( processor=_MockEngineProcessor(), run_id=run_id) shared_rt_info = cg.SharedRuntimeInfo(run_id=run_id) fs_saver.initialize(rt_config, shared_rt_info=shared_rt_info) # Test 1: assert fs_saver.initialize() has worked. rt_config2 = cirq.read_json_gzip( f'{tmpdir}/{run_id}/QuantumRuntimeConfiguration.json.gz') shared_rt_info2 = cirq.read_json_gzip( f'{tmpdir}/{run_id}/SharedRuntimeInfo.json.gz') assert rt_config == rt_config2 assert shared_rt_info == shared_rt_info2 # Test 2: assert `consume_result()` works. # you shouldn't actually mutate run_id in the shared runtime info, but we want to test # updating the shared rt info object: shared_rt_info.run_id = 'updated_run_id' exe_result = cg.ExecutableResult( spec=None, runtime_info=cg.RuntimeInfo(execution_index=0), raw_data=cirq.Result(params=cirq.ParamResolver({}), measurements={'z': np.ones((100, 5))}), ) fs_saver.consume_result(exe_result=exe_result, shared_rt_info=shared_rt_info) shared_rt_info3 = cirq.read_json_gzip( f'{tmpdir}/{run_id}/SharedRuntimeInfo.json.gz') exe_result3 = cirq.read_json_gzip( f'{tmpdir}/{run_id}/ExecutableResult.0.json.gz') assert shared_rt_info == shared_rt_info3 assert exe_result == exe_result3 # Test 3: assert loading egr_record works. egr_record: cg.ExecutableGroupResultFilesystemRecord = cirq.read_json_gzip( f'{fs_saver.data_dir}/ExecutableGroupResultFilesystemRecord.json.gz') assert egr_record == fs_saver.egr_record exegroup_result: cg.ExecutableGroupResult = egr_record.load( base_data_dir=tmpdir) assert exegroup_result.shared_runtime_info == shared_rt_info assert exegroup_result.runtime_configuration == rt_config assert exegroup_result.executable_results[0] == exe_result
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.Result(params=params or cirq.ParamResolver({}), measurements=measurements)
def _trial_sweep_from_proto( msg: result_pb2.SweepResult, measure_map: Dict[str, MeasureInfo] = None, ) -> List[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.Result( params=cirq.ParamResolver(dict(pr.params.assignments)), measurements=m_data, )) return trial_sweep
def _get_job_results_v1(result: v1.program_pb2.Result) -> List[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.Result( params=cirq.ParamResolver(result.params.assignments), measurements=measurements, )) return trial_results
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.Result( 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 test_df(): result = cirq.Result( 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), }, ) remove_end_measurements = pd.DataFrame(data={ 'ab': [1, 1, 2], 'c': [0, 1, 0] }, index=[1, 2, 3]) pd.testing.assert_frame_equal(result.data.iloc[1:-1], remove_end_measurements) # Frequency counting. df = result.data assert len(df[df['ab'] == 1]) == 4 assert df.c.value_counts().to_dict() == {0: 3, 1: 2}
def test_histogram(): result = cirq.Result( 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.histogram(key='ab') == collections.Counter({1: 4, 2: 1}) assert result.histogram(key='ab', fold_func=tuple) == collections.Counter({ (False, True): 4, (True, False): 1 }) assert result.histogram(key='ab', fold_func=lambda e: None) == collections.Counter({ None: 5, }) assert result.histogram(key='c') == collections.Counter({0: 3, 1: 2})
def test_print_logger(capsys): pl = _PrintLogger(n_total=10) shared_rt_info = cg.SharedRuntimeInfo(run_id='hi mom') pl.initialize() for i in range(10): exe_result = cg.ExecutableResult( spec=None, runtime_info=cg.RuntimeInfo(execution_index=i), raw_data=cirq.Result(params=cirq.ParamResolver({}), measurements={}), ) pl.consume_result(exe_result, shared_rt_info) pl.finalize() assert capsys.readouterr().out == ('\n\r1 / 10' '\r2 / 10' '\r3 / 10' '\r4 / 10' '\r5 / 10' '\r6 / 10' '\r7 / 10' '\r8 / 10' '\r9 / 10' '\r10 / 10\n')