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 serialize(serializer: str, num_gates: int, nesting_depth: int) -> int: """"Runs a round-trip of the serializer.""" circuit = cirq.Circuit() for _ in range(num_gates): which = np.random.choice(['expz', 'expw', 'exp11']) if which == 'expw': q1 = cirq.GridQubit(0, np.random.randint(NUM_QUBITS)) circuit.append( cirq.PhasedXPowGate(phase_exponent=np.random.random(), exponent=np.random.random()).on(q1)) elif which == 'expz': q1 = cirq.GridQubit(0, np.random.randint(NUM_QUBITS)) circuit.append(cirq.Z(q1)**np.random.random()) elif which == 'exp11': q1 = cirq.GridQubit(0, np.random.randint(NUM_QUBITS - 1)) q2 = cirq.GridQubit(0, q1.col + 1) circuit.append(cirq.CZ(q1, q2)**np.random.random()) cs = [circuit] for _ in range(1, nesting_depth): fc = cs[-1].freeze() cs.append(cirq.Circuit(fc.to_op(), fc.to_op())) test_circuit = cs[-1] if serializer == _JSON: json_data = cirq.to_json(test_circuit) assert json_data is not None data_size = len(json_data) cirq.read_json(json_text=json_data) elif serializer == _JSON_GZIP: gzip_data = cirq.to_json_gzip(test_circuit) assert gzip_data is not None data_size = len(gzip_data) cirq.read_json_gzip(gzip_raw=gzip_data) return data_size
def test_to_from_strings(): x_json_text = """{ "cirq_type": "_PauliX", "exponent": 1.0, "global_shift": 0.0 }""" assert cirq.to_json(cirq.X) == x_json_text assert cirq.read_json(json_text=x_json_text) == cirq.X with pytest.raises(ValueError, match='specify ONE'): cirq.read_json(io.StringIO(), json_text=x_json_text)
def test_datetime(): naive_dt = datetime.datetime.now() with pytest.raises(TypeError): cirq.to_json(naive_dt) utc_dt = naive_dt.astimezone(datetime.timezone.utc) assert utc_dt == cirq.read_json(json_text=cirq.to_json(utc_dt)) pst_dt = naive_dt.astimezone(tz=datetime.timezone( offset=datetime.timedelta(hours=-8))) assert utc_dt == cirq.read_json(json_text=cirq.to_json(pst_dt))
def test_invalid_type_deserialize(): def custom_resolver(name): if name == 'SerializableTypeObject': return SerializableTypeObject test_resolvers = [custom_resolver] + cirq.DEFAULT_RESOLVERS invalid_json = '{\n "cirq_type": "SerializableTypeObject",\n "test_type": "bad_type"\n}' with pytest.raises(ValueError, match='Could not resolve type'): _ = cirq.read_json(json_text=invalid_json, resolvers=test_resolvers) factory_json = '{\n "cirq_type": "SerializableTypeObject",\n "test_type": "sympy.Add"\n}' with pytest.raises(ValueError, match='maps to a factory method'): _ = cirq.read_json(json_text=factory_json, resolvers=test_resolvers)
def test_metadata_json_load_logic(): qubits = cirq.LineQubit.range(4) graph = nx.star_graph(3) metadata = cirq.DeviceMetadata(qubits, graph) str_rep = cirq.to_json(metadata) assert metadata == cirq.read_json(json_text=str_rep) qubits = None graph = None metadata = cirq.DeviceMetadata(qubits, graph) str_rep = cirq.to_json(metadata) output = cirq.read_json(json_text=str_rep) assert metadata == output
def test_fail_to_resolve(): buffer = io.StringIO() buffer.write(""" { "cirq_type": "MyCustomClass", "data": [1, 2, 3] } """) buffer.seek(0) with pytest.raises(ValueError) as e: cirq.read_json(buffer) assert e.match("Could not resolve type 'MyCustomClass' " "during deserialization")
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 test_type_serialization(mod_spec: ModuleJsonTestSpec, cirq_obj_name: str, cls): if cirq_obj_name in mod_spec.tested_elsewhere: pytest.skip("Tested elsewhere.") if cirq_obj_name in mod_spec.not_yet_serializable: return pytest.xfail(reason="Not serializable (yet)") if cls is None: pytest.skip(f'No serialization for None-mapped type: {cirq_obj_name}') try: typename = cirq.json_cirq_type(cls) except ValueError as e: pytest.skip(f'No serialization for non-Cirq type: {str(e)}') def custom_resolver(name): if name == 'SerializableTypeObject': return SerializableTypeObject sto = SerializableTypeObject(cls) test_resolvers = [custom_resolver] + cirq.DEFAULT_RESOLVERS expected_json = (f'{{\n "cirq_type": "SerializableTypeObject",\n' f' "test_type": "{typename}"\n}}') assert cirq.to_json(sto) == expected_json assert cirq.read_json(json_text=expected_json, resolvers=test_resolvers) == sto assert_json_roundtrip_works(sto, resolvers=test_resolvers)
def test_old_json(): """Older versions of PauliStringPhasor did not have a qubit field.""" old_json = """ { "cirq_type": "PauliStringPhasor", "pauli_string": { "cirq_type": "PauliString", "qubit_pauli_map": [ [ { "cirq_type": "LineQubit", "x": 0 }, { "cirq_type": "_PauliX", "exponent": 1.0, "global_shift": 0.0 } ], [ { "cirq_type": "LineQubit", "x": 1 }, { "cirq_type": "_PauliY", "exponent": 1.0, "global_shift": 0.0 } ], [ { "cirq_type": "LineQubit", "x": 2 }, { "cirq_type": "_PauliZ", "exponent": 1.0, "global_shift": 0.0 } ] ], "coefficient": { "cirq_type": "complex", "real": 1.0, "imag": 0.0 } }, "exponent_neg": 0.2, "exponent_pos": 0.1 } """ phasor = cirq.read_json(json_text=old_json) assert phasor == cirq.PauliStringPhasor( ((1 + 0j) * cirq.X(cirq.LineQubit(0)) * cirq.Y(cirq.LineQubit(1)) * cirq.Z(cirq.LineQubit(2))), qubits=(cirq.LineQubit(0), cirq.LineQubit(1), cirq.LineQubit(2)), exponent_neg=0.2, exponent_pos=0.1, )
def test_measure_grouped_settings_read_checkpoint(tmpdir): qubits = cirq.LineQubit.range(1) (q,) = qubits setting = cw.InitObsSetting( init_state=cirq.KET_ZERO(q), observable=cirq.Z(q), ) grouped_settings = {setting: [setting]} circuit = cirq.Circuit(cirq.I.on_each(*qubits)) with pytest.raises(ValueError, match=r'same filename.*'): _ = cw.measure_grouped_settings( circuit=circuit, grouped_settings=grouped_settings, sampler=cirq.Simulator(), stopping_criteria=cw.RepetitionsStoppingCriteria(1_000, repetitions_per_chunk=500), checkpoint=True, checkpoint_fn=f'{tmpdir}/obs.json', checkpoint_other_fn=f'{tmpdir}/obs.json', # Same filename ) _ = cw.measure_grouped_settings( circuit=circuit, grouped_settings=grouped_settings, sampler=cirq.Simulator(), stopping_criteria=cw.RepetitionsStoppingCriteria(1_000, repetitions_per_chunk=500), checkpoint=True, checkpoint_fn=f'{tmpdir}/obs.json', checkpoint_other_fn=f'{tmpdir}/obs.prev.json', ) results = cirq.read_json(f'{tmpdir}/obs.json') (result,) = results # one group assert result.n_repetitions == 1_000 assert result.means() == [1.0]
def _send_serialized_circuit(self, serialization_str: str, repetitions: int = 1) -> cirq.study.Result: """Sends the json string to the remote Pasqal device Args: serialization_str: Json representation of the circuit. repetitions: Number of repetitions. Returns: json representation of the results """ simulate_url = f'{self.remote_host}/simulate/no-noise/submit' submit_response = requests.post( simulate_url, verify=False, headers={ "Repetitions": str(repetitions), **self._authorization_header, }, data=serialization_str, ) submit_response.raise_for_status() task_id = submit_response.text result_serialized = self._retrieve_serialized_result(task_id) result = cirq.read_json(json_text=result_serialized) return result
def load_median_device_calibration( processor_id: str) -> calibration.Calibration: """Loads a median `cirq_google.Calibration` for the given device. Real calibration data from Google's 'rainbow' and 'weber' devices has been saved in Cirq. The calibrations selected are roughly representative of the median performance for that chip. A description of the stored metrics can be found on the [calibration page](https://quantumai.google/cirq/google/calibration). Args: processor_id: name of the processor to simulate. Raises: ValueError: if processor_id is not a supported QCS processor. """ cal_name = MEDIAN_CALIBRATIONS.get(processor_id, None) if cal_name is None: raise ValueError( f"Got processor_id={processor_id}, but no median calibration " "is defined for that processor.") path = pathlib.Path(__file__).parent.parent.resolve() with path.joinpath('devices', 'calibrations', cal_name).open() as f: cal = cast(calibration.Calibration, cirq.read_json(f)) cal.timestamp = MEDIAN_CALIBRATION_TIMESTAMPS[processor_id] return cal
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_commutes(): for A, B in itertools.product([cirq.X, cirq.Y, cirq.Z], repeat=2): assert cirq.commutes(A, B) == (A == B) with pytest.raises(TypeError): assert cirq.commutes(cirq.X, 'X') assert cirq.commutes(cirq.X, 'X', default='default') == 'default' assert cirq.commutes(cirq.Z, cirq.read_json(json_text=cirq.to_json(cirq.Z)))
def test_pathlib_paths(tmpdir): path = pathlib.Path(tmpdir) / 'op.json' cirq.to_json(cirq.X, path) assert cirq.read_json(path) == cirq.X gzip_path = pathlib.Path(tmpdir) / 'op.gz' cirq.to_json_gzip(cirq.X, gzip_path) assert cirq.read_json_gzip(gzip_path) == cirq.X
def test_op_roundtrip_filename(tmpdir): filename = f'{tmpdir}/op.json' q = cirq.LineQubit(5) op1 = cirq.rx(.123).on(q) cirq.to_json(op1, filename) assert os.path.exists(filename) op2 = cirq.read_json(filename) assert op1 == op2
def test_datetime(): naive_dt = datetime.datetime.now() re_naive_dt = cirq.read_json(json_text=cirq.to_json(naive_dt)) assert re_naive_dt != naive_dt, 'loads in with timezone' assert re_naive_dt.timestamp() == naive_dt.timestamp() utc_dt = naive_dt.astimezone(datetime.timezone.utc) re_utc_dt = cirq.read_json(json_text=cirq.to_json(utc_dt)) assert re_utc_dt == utc_dt assert re_utc_dt == re_naive_dt pst_dt = naive_dt.astimezone(tz=datetime.timezone( offset=datetime.timedelta(hours=-8))) re_pst_dt = cirq.read_json(json_text=cirq.to_json(pst_dt)) assert re_pst_dt == pst_dt assert re_pst_dt == utc_dt assert re_pst_dt == re_naive_dt
def test_quantum_executable_group_serialization(tmpdir): exes = _get_quantum_executables() eg = QuantumExecutableGroup(exes) cirq.testing.assert_equivalent_repr(eg, global_vals={'cirq_google': cirq_google}) cirq.to_json(eg, f'{tmpdir}/eg.json') eg_reconstructed = cirq.read_json(f'{tmpdir}/eg.json') assert eg == eg_reconstructed
def test_json_serialization(): def custom_resolver(cirq_type: str): if cirq_type == "MSGate": return cirq.ops.MSGate return None assert cirq.read_json( json_text=cirq.to_json(cirq.ms(np.pi / 2)), resolvers=[custom_resolver] ) == cirq.ms(np.pi / 2) assert custom_resolver('X') is None
def test_json_serialization(): def custom_resolver(cirq_type: str) -> Union[Callable[..., cirq.Gate], None]: if cirq_type == "MSGate": return cirq.ion.ion_gates.MSGate return None assert cirq.read_json( json_text=cirq.to_json(cirq.ms(np.pi / 2)), resolvers=[custom_resolver] ) == cirq.ms(np.pi / 2) assert custom_resolver('X') is None
def load_experiment( file_or_fn: Union[None, IO, pathlib.Path, str]) -> FermiHubbardExperiment: """Loads experiment from the JSON file. Args: file_or_fn: File description as passed to cirq.to_json function. """ data = cirq.read_json(file_or_fn, resolvers=cirq.DEFAULT_RESOLVERS + [FermiHubbardExperiment.cirq_resolvers().get]) return cast(FermiHubbardExperiment, data)
def test_griddevice_json_load_with_defaults(): qubits = cirq.GridQubit.rect(2, 3) qubit_pairs = [(a, b) for a in qubits for b in qubits if a != b and a.is_adjacent(b)] gateset = cirq.Gateset(cirq.XPowGate, cirq.YPowGate, cirq.ZPowGate, cirq.CZ) # Don't set parameters with default values metadata = cirq.GridDeviceMetadata(qubit_pairs, gateset) rep_str = cirq.to_json(metadata) assert metadata == cirq.read_json(json_text=rep_str)
def assert_repr_and_json_test_data_agree(repr_path: pathlib.Path, json_path: pathlib.Path, inward_only: bool): if not repr_path.exists() and not json_path.exists(): return rel_repr_path = f'{TEST_DATA_REL}/{repr_path.name}' rel_json_path = f'{TEST_DATA_REL}/{json_path.name}' try: json_from_file = json_path.read_text() json_obj = cirq.read_json(json_text=json_from_file) except Exception as ex: # coverage: ignore # coverage: ignore raise IOError( f'Failed to parse test json data from {rel_json_path}.') from ex try: repr_obj = _eval_repr_data_file(repr_path) except Exception as ex: # coverage: ignore # coverage: ignore raise IOError( f'Failed to parse test repr data from {rel_repr_path}.') from ex assert proper_eq(json_obj, repr_obj), ( f'The json data from {rel_json_path} did not parse ' f'into an object equivalent to the repr data from {rel_repr_path}.\n' f'\n' f'json object: {json_obj!r}\n' f'repr object: {repr_obj!r}\n') if not inward_only: json_from_cirq = cirq.to_json(repr_obj) json_from_cirq_obj = json.loads(json_from_cirq) json_from_file_obj = json.loads(json_from_file) assert json_from_cirq_obj == json_from_file_obj, ( f'The json produced by cirq no longer agrees with the json in the ' f'{rel_json_path} test data file.\n' f'\n' f'You must either fix the cirq code to continue to produce the ' f'same output, or you must move the old test data to ' f'{rel_json_path}_inward and create a fresh {rel_json_path} file.\n' f'\n' f'test data json:\n' f'{json_from_file}\n' f'\n' f'cirq produced json:\n' f'{json_from_cirq}\n')
def test_griddevice_json_load(): qubits = cirq.GridQubit.rect(2, 3) qubit_pairs = [(a, b) for a in qubits for b in qubits if a != b and a.is_adjacent(b)] gateset = cirq.Gateset(cirq.XPowGate, cirq.YPowGate, cirq.ZPowGate) duration = { cirq.Gateset(cirq.XPowGate): cirq.Duration(nanos=1), cirq.Gateset(cirq.YPowGate): cirq.Duration(picos=2), cirq.Gateset(cirq.ZPowGate): cirq.Duration(picos=3), } metadata = cirq.GridDeviceMetadata(qubit_pairs, gateset, gate_durations=duration) rep_str = cirq.to_json(metadata) assert metadata == cirq.read_json(json_text=rep_str)
def test_sample_2q_parallel_xeb_circuits(tmpdir): circuits = rqcg.generate_library_of_2q_circuits( n_library_circuits=5, two_qubit_gate=cirq.ISWAP**0.5, max_cycle_depth=10) cycle_depths = [5, 10] graph = _gridqubits_to_graph_device(cirq.GridQubit.rect(3, 2)) combs = rqcg.get_random_combinations_for_device( n_library_circuits=len(circuits), n_combinations=5, device_graph=graph, random_state=10, ) df = sample_2q_xeb_circuits( sampler=cirq.Simulator(), circuits=circuits, cycle_depths=cycle_depths, combinations_by_layer=combs, dataset_directory=f'{tmpdir}/my_dataset', ) n_pairs = sum(len(c.pairs) for c in combs) assert len(df) == len(cycle_depths) * len(circuits) * n_pairs for (circuit_i, cycle_depth), row in df.iterrows(): assert 0 <= circuit_i < len(circuits) assert cycle_depth in cycle_depths assert len(row['sampled_probs']) == 4 assert np.isclose(np.sum(row['sampled_probs']), 1) assert 0 <= row['layer_i'] < 4 assert 0 <= row[ 'pair_i'] < 2 # in 3x2 graph, there's a max of 2 pairs per layer assert len(df['pair'].unique()) == 7 # seven pairs in 3x2 graph # Test loading from dataset chunks = [ record for fn in glob.glob(f'{tmpdir}/my_dataset/*') for record in cirq.read_json(fn) ] df2 = pd.DataFrame(chunks).set_index(['circuit_i', 'cycle_depth']) df2['pair'] = [tuple(row['pair']) for _, row in df2.iterrows()] actual_index_names = ['layer_i', 'pair_i', 'combination_i', 'cycle_depth'] _assert_frame_approx_equal( df.reset_index().set_index(actual_index_names), df2.reset_index().set_index(actual_index_names), atol=1e-5, )
def test_run_sweep_params(client): client().create_program.return_value = ( 'prog', quantum.QuantumProgram(name='projects/proj/programs/prog'), ) client().create_job.return_value = ( 'job-id', quantum.QuantumJob(name='projects/proj/programs/prog/jobs/job-id', execution_status={'state': 'READY'}), ) client().get_job.return_value = quantum.QuantumJob( execution_status={'state': 'SUCCESS'}, update_time=_to_timestamp('2019-07-09T23:39:59Z')) client().get_job_results.return_value = quantum.QuantumResult( result=util.pack_any(_RESULTS_V2)) processor = cg.EngineProcessor('a', 'p', EngineContext()) job = processor.run_sweep( program=_CIRCUIT, params=[cirq.ParamResolver({'a': 1}), cirq.ParamResolver({'a': 2})]) results = job.results() assert len(results) == 2 for i, v in enumerate([1, 2]): assert results[i].repetitions == 1 assert results[i].params.param_dict == {'a': v} assert results[i].measurements == {'q': np.array([[0]], dtype='uint8')} for result in results: assert result.job_id == job.id() assert result.job_finished_time is not None assert results == cirq.read_json(json_text=cirq.to_json(results)) client().create_program.assert_called_once() client().create_job.assert_called_once() run_context = v2.run_context_pb2.RunContext() client().create_job.call_args[1]['run_context'].Unpack(run_context) sweeps = run_context.parameter_sweeps assert len(sweeps) == 2 for i, v in enumerate([1.0, 2.0]): assert sweeps[i].repetitions == 1 assert sweeps[i].sweep.sweep_function.sweeps[ 0].single_sweep.points.points == [v] client().get_job.assert_called_once() client().get_job_results.assert_called_once()
def test_run_sweep(mock_post, mock_get): """Test running a sweep. Encodes a random binary number in the qubits, sweeps between odd and even without noise and checks if the results match. """ qs = [cirq_pasqal.ThreeDQubit(i, j, 0) for i in range(3) for j in range(3)] par = sympy.Symbol('par') sweep = cirq.Linspace(key='par', start=0.0, stop=1.0, length=2) num = np.random.randint(0, 2**9) binary = bin(num)[2:].zfill(9) device = cirq_pasqal.PasqalVirtualDevice(control_radius=1, qubits=qs) ex_circuit = cirq.Circuit() for i, b in enumerate(binary[:-1]): if b == '1': ex_circuit.append(cirq.X(qs[-i - 1]), strategy=cirq.InsertStrategy.NEW) ex_circuit_odd = copy.deepcopy(ex_circuit) ex_circuit_odd.append(cirq.X(qs[0]), strategy=cirq.InsertStrategy.NEW) ex_circuit_odd.append(cirq.measure(*qs), strategy=cirq.InsertStrategy.NEW) xpow = cirq.XPowGate(exponent=par) ex_circuit.append([xpow(qs[0])], strategy=cirq.InsertStrategy.NEW) ex_circuit.append(cirq.measure(*qs), strategy=cirq.InsertStrategy.NEW) mock_get.return_value = MockGet(cirq.to_json(ex_circuit_odd)) sampler = _make_sampler(device) with pytest.raises(ValueError, match="Non-empty moment after measurement"): wrong_circuit = copy.deepcopy(ex_circuit) wrong_circuit.append(cirq.X(qs[0])) sampler.run_sweep(program=wrong_circuit, params=sweep, repetitions=1) data = sampler.run_sweep(program=ex_circuit, params=sweep, repetitions=1) submitted_json = mock_post.call_args[1]['data'] assert cirq.read_json(json_text=submitted_json) == ex_circuit_odd assert mock_post.call_count == 2 assert data[1] == ex_circuit_odd
def test_quantum_executable(tmpdir): qubits = cirq.GridQubit.rect(2, 2) exe = QuantumExecutable( spec=_get_example_spec(name='example-program'), circuit=_get_random_circuit(qubits), measurement=BitstringsMeasurement(n_repetitions=10), ) # Check args get turned into immutable fields assert isinstance(exe.circuit, cirq.FrozenCircuit) assert hash(exe) is not None assert hash(dataclasses.astuple(exe)) is not None assert hash(dataclasses.astuple(exe)) == exe._hash prog2 = QuantumExecutable( spec=_get_example_spec(name='example-program'), circuit=_get_random_circuit(qubits), measurement=BitstringsMeasurement(n_repetitions=10), ) assert exe == prog2 assert hash(exe) == hash(prog2) prog3 = QuantumExecutable( spec=_get_example_spec(name='example-program'), circuit=_get_random_circuit(qubits), measurement=BitstringsMeasurement( n_repetitions=20), # note: changed n_repetitions ) assert exe != prog3 assert hash(exe) != hash(prog3) with pytest.raises(dataclasses.FrozenInstanceError): prog3.measurement.n_repetitions = 10 cirq.to_json(exe, f'{tmpdir}/exe.json') exe_reconstructed = cirq.read_json(f'{tmpdir}/exe.json') assert exe == exe_reconstructed assert (str(exe) == "QuantumExecutable(spec=cirq_google.KeyValueExecutableSpec(" "executable_family='cirq_google.algo_benchmarks.example', " "key_value_pairs=(('name', 'example-program'),)))") cirq.testing.assert_equivalent_repr( exe, global_vals={'cirq_google': cirq_google})
def test_run_batch(simulation_type): program = ParentProgram( [ cirq.Circuit( cirq.X(Q)**sympy.Symbol('t'), cirq.measure(Q, key='m')), cirq.Circuit( cirq.X(Q)**sympy.Symbol('x'), cirq.measure(Q, key='m2')), ], None, ) job = SimulatedLocalJob( job_id='test_job', processor_id='test1', parent_program=program, simulation_type=simulation_type, repetitions=100, sweeps=[ cirq.Points(key='t', points=[1, 0]), cirq.Points(key='x', points=[0, 1]) ], ) if simulation_type == LocalSimulationType.ASYNCHRONOUS: # Note: The simulation could have finished already assert (job.execution_status() == quantum.ExecutionStatus.State.RUNNING or job.execution_status() == quantum.ExecutionStatus.State.SUCCESS) else: assert job.execution_status() == quantum.ExecutionStatus.State.READY results = job.batched_results() assert np.all(results[0][0].measurements['m'] == 1) assert np.all(results[0][1].measurements['m'] == 0) assert np.all(results[1][0].measurements['m2'] == 0) assert np.all(results[1][1].measurements['m2'] == 1) assert job.execution_status() == quantum.ExecutionStatus.State.SUCCESS # Using flattened results results = job.results() assert np.all(results[0].measurements['m'] == 1) assert np.all(results[1].measurements['m'] == 0) assert np.all(results[2].measurements['m2'] == 0) assert np.all(results[3].measurements['m2'] == 1) for result in results: assert result.job_id == 'test_job' assert result.job_finished_time is not None assert results == cirq.read_json(json_text=cirq.to_json(results))